|
| 1 | +// Copyright (c) Microsoft Corporation. |
| 2 | +// Licensed under the MIT License. |
| 3 | + |
| 4 | +using System; |
| 5 | +using System.Collections.Generic; |
| 6 | +using System.Diagnostics.ContractsLight; |
| 7 | +using BuildXL.Utilities.Core; |
| 8 | + |
| 9 | +namespace BuildXL.FrontEnd.Nuget |
| 10 | +{ |
| 11 | + /// <summary> |
| 12 | + /// Compares two relative paths in hierarchical order, starting with the atom closer to the root. Each atom is compared as a string, case insensitive. |
| 13 | + /// </summary> |
| 14 | + /// <remarks> |
| 15 | + /// For example, consider these two paths: |
| 16 | + /// |
| 17 | + /// 1- lib/net6.0-android31/Microsoft.Identity.Client.dll |
| 18 | + /// 2- lib/net6.0/Microsoft.Identity.Client.dll |
| 19 | + /// |
| 20 | + /// A regular string-based comparison would determine 1 < 2, because the prefix string 'lib/net6.0-' is lexicographically smaller than 'lib/net6.0/'. On the other hand |
| 21 | + /// this comparer will determine that 2 < 1, because the second atom on both paths is the first one that differs (starting from the root) and the string 'net6.0' is less than the string 'net6.0-android31'. |
| 22 | + /// </remarks> |
| 23 | + internal class NugetRelativePathComparer : IComparer<RelativePath> |
| 24 | + { |
| 25 | + private readonly StringTable m_stringTable; |
| 26 | + |
| 27 | + /// <nodoc/> |
| 28 | + public NugetRelativePathComparer(StringTable stringTable) |
| 29 | + { |
| 30 | + Contract.Requires(stringTable != null); |
| 31 | + m_stringTable = stringTable; |
| 32 | + } |
| 33 | + |
| 34 | + /// <inheritdoc/> |
| 35 | + public int Compare(RelativePath left, RelativePath right) |
| 36 | + { |
| 37 | + Contract.Requires(left.IsValid); |
| 38 | + Contract.Requires(right.IsValid); |
| 39 | + |
| 40 | + var leftAtoms = left.GetAtoms(); |
| 41 | + var rightAtoms = right.GetAtoms(); |
| 42 | + // Let's go in order, starting from the atom closer to the root |
| 43 | + for(var i = 0; i < Math.Min(leftAtoms.Length, rightAtoms.Length); i++) |
| 44 | + { |
| 45 | + // Each pair is compared as strings - case insensitive (even on Linux, nuget is case insensitive across the board, so path differing in casing should be |
| 46 | + // understood as the same path |
| 47 | + var comparison = StringComparer.OrdinalIgnoreCase.Compare(leftAtoms[i].ToString(m_stringTable), rightAtoms[i].ToString(m_stringTable)); |
| 48 | + |
| 49 | + // If the pair of atoms are different, that determines the comparison of the whole path |
| 50 | + if (comparison != 0) |
| 51 | + { |
| 52 | + return comparison; |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + // If all atoms are the same up to the minimum length that is present on both sides, |
| 57 | + // the one with less atoms is smaller |
| 58 | + return leftAtoms.Length - rightAtoms.Length; |
| 59 | + |
| 60 | + } |
| 61 | + } |
| 62 | +} |
0 commit comments