// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Management.Automation; using System.Management.Automation.Internal; using System.Management.Automation.Language; using System.Text; namespace Microsoft.PowerShell.Commands.Utility { /// /// Join-Object implementation. /// [Cmdlet(VerbsCommon.Join, "String", RemotingCapability = RemotingCapability.None, DefaultParameterSetName = "default")] [OutputType(typeof(string))] public sealed class JoinStringCommand : PSCmdlet { /// A bigger default to not get re-allocations in common use cases. private const int DefaultOutputStringCapacity = 256; private readonly StringBuilder _outputBuilder = new(DefaultOutputStringCapacity); private CultureInfo _cultureInfo = CultureInfo.InvariantCulture; private string _separator; private char _quoteChar; private bool _firstInputObject = true; /// /// Gets or sets the property name or script block to use as the value to join. /// [Parameter(Position = 0)] [ArgumentCompleter(typeof(PropertyNameCompleter))] public PSPropertyExpression Property { get; set; } /// /// Gets or sets the delimiter to join the output with. /// [Parameter(Position = 1)] [ArgumentCompleter(typeof(SeparatorArgumentCompleter))] [AllowEmptyString] public string Separator { get => _separator ?? LanguagePrimitives.ConvertTo(GetVariableValue("OFS")); set => _separator = value; } /// /// Gets or sets text to include before the joined input text. /// [Parameter] [Alias("op")] public string OutputPrefix { get; set; } /// /// Gets or sets text to include after the joined input text. /// [Parameter] [Alias("os")] public string OutputSuffix { get; set; } /// /// Gets or sets if the output items should we wrapped in single quotes. /// [Parameter(ParameterSetName = "SingleQuote")] public SwitchParameter SingleQuote { get; set; } /// /// Gets or sets if the output items should we wrapped in double quotes. /// [Parameter(ParameterSetName = "DoubleQuote")] public SwitchParameter DoubleQuote { get; set; } /// /// Gets or sets a format string that is applied to each input object. /// [Parameter(ParameterSetName = "Format")] [ArgumentCompleter(typeof(FormatStringArgumentCompleter))] public string FormatString { get; set; } /// /// Gets or sets if the current culture should be used with formatting instead of the invariant culture. /// [Parameter] public SwitchParameter UseCulture { get; set; } /// /// Gets or sets the input object to join into text. /// [Parameter(ValueFromPipeline = true)] public PSObject[] InputObject { get; set; } /// protected override void BeginProcessing() { _quoteChar = SingleQuote ? '\'' : DoubleQuote ? '"' : char.MinValue; _outputBuilder.Append(OutputPrefix); if (UseCulture) { _cultureInfo = CultureInfo.CurrentCulture; } } /// protected override void ProcessRecord() { if (InputObject != null) { foreach (PSObject inputObject in InputObject) { if (inputObject != null && inputObject != AutomationNull.Value) { var inputValue = Property == null ? inputObject : Property.GetValues(inputObject, false, true).FirstOrDefault()?.Result; // conversion to string always succeeds. if (!LanguagePrimitives.TryConvertTo(inputValue, _cultureInfo, out var stringValue)) { throw new PSInvalidCastException("InvalidCastFromAnyTypeToString", ExtendedTypeSystem.InvalidCastCannotRetrieveString, null); } if (_firstInputObject) { _firstInputObject = false; } else { _outputBuilder.Append(Separator); } if (_quoteChar != char.MinValue) { _outputBuilder.Append(_quoteChar); _outputBuilder.Append(stringValue); _outputBuilder.Append(_quoteChar); } else if (string.IsNullOrEmpty(FormatString)) { _outputBuilder.Append(stringValue); } else { _outputBuilder.AppendFormat(_cultureInfo, FormatString, inputValue); } } } } } /// protected override void EndProcessing() { _outputBuilder.Append(OutputSuffix); WriteObject(_outputBuilder.ToString()); } } /// /// Provides completion for the Separator parameter of the Join-String cmdlet. /// public sealed class SeparatorArgumentCompleter : IArgumentCompleter { private const string NewLineText = #if UNIX "`n"; #else "`r`n"; #endif private static readonly CompletionHelpers.CompletionDisplayInfoMapper SeparatorDisplayInfoMapper = separator => separator switch { "," => ( ToolTip: TabCompletionStrings.SeparatorCommaToolTip, ListItemText: "Comma"), ", " => ( ToolTip: TabCompletionStrings.SeparatorCommaSpaceToolTip, ListItemText: "Comma-Space"), ";" => ( ToolTip: TabCompletionStrings.SeparatorSemiColonToolTip, ListItemText: "Semi-Colon"), "; " => ( ToolTip: TabCompletionStrings.SeparatorSemiColonSpaceToolTip, ListItemText: "Semi-Colon-Space"), "-" => ( ToolTip: TabCompletionStrings.SeparatorDashToolTip, ListItemText: "Dash"), " " => ( ToolTip: TabCompletionStrings.SeparatorSpaceToolTip, ListItemText: "Space"), NewLineText => ( ToolTip: StringUtil.Format(TabCompletionStrings.SeparatorNewlineToolTip, NewLineText), ListItemText: "Newline"), _ => ( ToolTip: separator, ListItemText: separator), }; private static readonly IReadOnlyList s_separatorValues = new List(capacity: 7) { ",", ", ", ";", "; ", NewLineText, "-", " ", }; /// /// Returns completion results for Separator parameter. /// /// The command name. /// The parameter name. /// The word to complete. /// The command AST. /// The fake bound parameters. /// List of Completion Results. public IEnumerable CompleteArgument( string commandName, string parameterName, string wordToComplete, CommandAst commandAst, IDictionary fakeBoundParameters) => CompletionHelpers.GetMatchingResults( wordToComplete, possibleCompletionValues: s_separatorValues, displayInfoMapper: SeparatorDisplayInfoMapper, resultType: CompletionResultType.ParameterValue); } /// /// Provides completion for the FormatString parameter of the Join-String cmdlet. /// public sealed class FormatStringArgumentCompleter : IArgumentCompleter { private static readonly IReadOnlyList s_formatStringValues = new List(capacity: 4) { "[{0}]", "{0:N2}", #if UNIX "`n `${0}", "`n [string] `${0}", #else "`r`n `${0}", "`r`n [string] `${0}", #endif }; /// /// Returns completion results for FormatString parameter. /// /// The command name. /// The parameter name. /// The word to complete. /// The command AST. /// The fake bound parameters. /// List of Completion Results. public IEnumerable CompleteArgument( string commandName, string parameterName, string wordToComplete, CommandAst commandAst, IDictionary fakeBoundParameters) => CompletionHelpers.GetMatchingResults( wordToComplete, possibleCompletionValues: s_formatStringValues, matchStrategy: CompletionHelpers.WildcardPatternEscapeMatch); } }