|
| 1 | +// Copyright (c) Microsoft Corporation. |
| 2 | +// Licensed under the MIT License. |
| 3 | + |
| 4 | +namespace Microsoft.DurableTask.Abstractions; |
| 5 | + |
| 6 | +/// <summary> |
| 7 | +/// Utilities for handling Orchestration/Task versioning operations. |
| 8 | +/// </summary> |
| 9 | +public static class TaskOrchestrationVersioningUtils |
| 10 | +{ |
| 11 | + /// <summary> |
| 12 | + /// Compare two versions to each other. |
| 13 | + /// </summary> |
| 14 | + /// <remarks> |
| 15 | + /// This method's comparison is handled in the following order: |
| 16 | + /// 1. The versions are checked if they are empty (non-versioned). Both being empty signifies equality. |
| 17 | + /// 2. If sourceVersion is empty but otherVersion is defined, this is treated as the source being less than the other. |
| 18 | + /// 3. If otherVersion is empty but sourceVersion is defined, this is treated as the source being greater than the other. |
| 19 | + /// 4. Both versions are attempted to be parsed into System.Version and compared as such. |
| 20 | + /// 5. If all else fails, a direct string comparison is done between the versions. |
| 21 | + /// </remarks> |
| 22 | + /// <param name="sourceVersion">The source version that will be compared against the other version.</param> |
| 23 | + /// <param name="otherVersion">The other version to compare against.</param> |
| 24 | + /// <returns>An int representing how sourceVersion compares to otherVersion.</returns> |
| 25 | + public static int CompareVersions(string sourceVersion, string otherVersion) |
| 26 | + { |
| 27 | + // Both versions are empty, treat as equal. |
| 28 | + if (string.IsNullOrWhiteSpace(sourceVersion) && string.IsNullOrWhiteSpace(otherVersion)) |
| 29 | + { |
| 30 | + return 0; |
| 31 | + } |
| 32 | + |
| 33 | + // An empty version in the context is always less than a defined version in the parameter. |
| 34 | + if (string.IsNullOrWhiteSpace(sourceVersion)) |
| 35 | + { |
| 36 | + return -1; |
| 37 | + } |
| 38 | + |
| 39 | + // An empty version in the parameter is always less than a defined version in the context. |
| 40 | + if (string.IsNullOrWhiteSpace(otherVersion)) |
| 41 | + { |
| 42 | + return 1; |
| 43 | + } |
| 44 | + |
| 45 | + // If both versions use the .NET Version class, return that comparison. |
| 46 | + if (System.Version.TryParse(sourceVersion, out Version parsedSourceVersion) && System.Version.TryParse(otherVersion, out Version parsedOtherVersion)) |
| 47 | + { |
| 48 | + return parsedSourceVersion.CompareTo(parsedOtherVersion); |
| 49 | + } |
| 50 | + |
| 51 | + // If we have gotten to here, we don't know the syntax of the versions we are comparing, use a string comparison as a final check. |
| 52 | + return string.Compare(sourceVersion, otherVersion, StringComparison.OrdinalIgnoreCase); |
| 53 | + } |
| 54 | +} |
0 commit comments