File size: 1,859 Bytes
8c763fb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#nullable enable
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace System.Management.Automation
{
/// <summary>
/// To make it easier to specify a version, we add some conversions that wouldn't happen otherwise:
/// * A simple integer, i.e. 2;
/// * A string without a dot, i.e. "2".
/// </summary>
internal class ArgumentToVersionTransformationAttribute : ArgumentTransformationAttribute
{
/// <inheritdoc/>
public override object Transform(EngineIntrinsics engineIntrinsics, object inputData)
{
object version = PSObject.Base(inputData);
if (version is string versionStr)
{
if (TryConvertFromString(versionStr, out var convertedVersion))
{
return convertedVersion;
}
if (versionStr.Contains('.'))
{
// If the string contains a '.', let the Version constructor handle the conversion.
return inputData;
}
}
if (version is double)
{
// The conversion to int below is wrong, but the usual conversions will turn
// the double into a string, so just return the original object.
return inputData;
}
if (LanguagePrimitives.TryConvertTo<int>(version, out var majorVersion))
{
return new Version(majorVersion, 0);
}
return inputData;
}
protected virtual bool TryConvertFromString(string versionString, [NotNullWhen(true)] out Version? version)
{
version = null;
return false;
}
}
}
|