Skip to content

Commit 3c95f6d

Browse files
committed
Use natural sort for image names
By doing so, numbers are treated separately from strings and they are compared based on their integer value, rather than their alphabetical characters. Thus, 8.10 is considered "greater than" 8.9, whereas it would not be in a standard alphanumeric sort. This sort is to be used for the image listing, as well as the actual routine which selects an image for launch. I prefer this rather than the much simpler approach of sorting by the "time_created" of the image, because in my experience, images are named based on the date and version info when they were created. It's totally possible for an old image to be uploaded after a newer one. Sorting based on the image's timestamp would make it difficult to resolve that situation, whereas the natural sort easily selects the latest based on the embedded dates in the name. Signed-off-by: Stephen Brennan <stephen.s.brennan@oracle.com>
1 parent ad3ed69 commit 3c95f6d

File tree

2 files changed

+12
-2
lines changed

2 files changed

+12
-2
lines changed

yo/main.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,7 @@
115115
from yo.util import current_yo_version
116116
from yo.util import fmt_allow_deny
117117
from yo.util import latest_yo_version
118+
from yo.util import natural_sort
118119
from yo.util import shlex_join
119120
from yo.util import standardize_name
120121
from yo.util import strftime
@@ -1903,7 +1904,7 @@ def run(self) -> None:
19031904
images = list(
19041905
filter(lambda x: x.os == os and x.os_version == ver, images)
19051906
)
1906-
images.sort(key=lambda i: i.name, reverse=True)
1907+
images.sort(key=lambda i: natural_sort(i.name), reverse=True)
19071908
if self.args.verbose:
19081909
self.c.con.print(images)
19091910
else:
@@ -2296,7 +2297,7 @@ def compatible(image: YoImage) -> bool:
22962297

22972298
images = self.c.list_official_images()
22982299
images = list(filter(compatible, images))
2299-
images.sort(key=lambda i: i.name, reverse=True)
2300+
images.sort(key=lambda i: natural_sort(i.name), reverse=True)
23002301
if not images:
23012302
raise YoExc(
23022303
f"No matching images for {os_config} and shape {shape}..."

yo/util.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -343,3 +343,12 @@ def current_yo_version() -> t.Tuple[int, int, int]:
343343
ver_str = pkg_resources.get_distribution("yo").version
344344
g1, g2, g3 = ver_str.split(".")
345345
return (int(g1), int(g2), int(g3))
346+
347+
348+
_NATURAL_SORT_RE = re.compile(r"([0-9]+)")
349+
350+
351+
def natural_sort(s: str) -> t.List[t.Union[str, int]]:
352+
return [
353+
int(f) if f and f[0].isdigit() else f for f in _NATURAL_SORT_RE.split(s)
354+
]

0 commit comments

Comments
 (0)