@@ -170,8 +170,13 @@ private static IEnumerable<string> EnumerateHomebrewCellarCandidatePaths(string
170170 {
171171 versionDirectories = Directory
172172 . EnumerateDirectories ( formulaDirectory )
173+ . Select ( CreateHomebrewCellarVersionCandidate )
174+ . OrderByDescending ( static candidate => candidate . Parsed )
175+ . ThenByDescending ( static candidate => candidate . Version )
176+ . ThenByDescending ( static candidate => candidate . Revision )
177+ . ThenByDescending ( static candidate => candidate . Path , StringComparer . Ordinal )
173178 . Take ( MaxHomebrewCellarVersions )
174- . OrderByDescending ( static path => path , StringComparer . Ordinal )
179+ . Select ( static candidate => candidate . Path )
175180 . ToArray ( ) ;
176181 }
177182 catch ( Exception ex ) when ( ex is IOException
@@ -187,6 +192,24 @@ or NotSupportedException
187192 yield return Path . Combine ( versionDirectory , "bin" , "gh" ) ;
188193 }
189194
195+ private static HomebrewCellarVersionCandidate CreateHomebrewCellarVersionCandidate ( string path )
196+ {
197+ var directoryName = Path . GetFileName ( path ) ;
198+ var versionText = directoryName ;
199+ var revision = 0 ;
200+ var revisionSeparator = directoryName . LastIndexOf ( '_' ) ;
201+ if ( revisionSeparator >= 0 )
202+ {
203+ versionText = directoryName [ ..revisionSeparator ] ;
204+ if ( ! int . TryParse ( directoryName [ ( revisionSeparator + 1 ) ..] , out revision ) || revision < 0 )
205+ return new HomebrewCellarVersionCandidate ( path , new Version ( 0 , 0 ) , 0 , Parsed : false ) ;
206+ }
207+
208+ return Version . TryParse ( versionText , out var version )
209+ ? new HomebrewCellarVersionCandidate ( path , version , revision , Parsed : true )
210+ : new HomebrewCellarVersionCandidate ( path , new Version ( 0 , 0 ) , 0 , Parsed : false ) ;
211+ }
212+
190213 private static bool IsMacHomebrewCellarGhPath ( string path )
191214 {
192215 if ( ! OperatingSystem . IsMacOS ( ) || ! Path . IsPathFullyQualified ( path ) )
@@ -249,4 +272,10 @@ private static bool ProbeVersion(string executablePath, CancellationToken cancel
249272 }
250273
251274 private sealed record GitHubCliExecutableResolution ( string ? Path , GitExecutableStatus Status ) ;
275+
276+ private sealed record HomebrewCellarVersionCandidate (
277+ string Path ,
278+ Version Version ,
279+ int Revision ,
280+ bool Parsed ) ;
252281}
0 commit comments