diff --git a/swh/core/tests/test_utils.py b/swh/core/tests/test_utils.py --- a/swh/core/tests/test_utils.py +++ b/swh/core/tests/test_utils.py @@ -119,3 +119,15 @@ actual_commonname2 = utils.commonname(b"/some/where/to/", b"/some/where/to/go/to") # then assert b"go/to" == actual_commonname2 + + +def test_numfile_sotkey(): + assert utils.numfile_sortkey("00-xxx.sql") == (0, "-xxx.sql") + assert utils.numfile_sortkey("01-xxx.sql") == (1, "-xxx.sql") + assert utils.numfile_sortkey("10-xxx.sql") == (10, "-xxx.sql") + assert utils.numfile_sortkey("99-xxx.sql") == (99, "-xxx.sql") + assert utils.numfile_sortkey("100-xxx.sql") == (100, "-xxx.sql") + assert utils.numfile_sortkey("00100-xxx.sql") == (100, "-xxx.sql") + assert utils.numfile_sortkey("1.sql") == (1, ".sql") + assert utils.numfile_sortkey("1") == (1, "") + assert utils.numfile_sortkey("toto-01.sql") == (999999, "toto-01.sql") diff --git a/swh/core/utils.py b/swh/core/utils.py --- a/swh/core/utils.py +++ b/swh/core/utils.py @@ -8,6 +8,7 @@ import itertools import os import re +from typing import Tuple @contextmanager @@ -109,14 +110,23 @@ return path1.split(path0)[1] -def numfile_sortkey(fname): +def numfile_sortkey(fname: str) -> Tuple[int, str]: """Simple function to sort filenames of the form: nnxxx.ext where nn is a number according to the numbers. + Returns a tuple (order, remaining), where 'order' is the numeric (int) + value extracted from the file name, and 'remaining' is the remaining part + of the file name. + Typically used to sort sql/nn-swh-xxx.sql files. + + Unmatched file names will return 999999 as order value. + """ - num, rem = re.match(r"(\d*)(.*)", fname).groups() - return (num and int(num) or 99, rem) + m = re.match(r"(\d*)(.*)", fname) + assert m is not None + num, rem = m.groups() + return (int(num) if num else 999999, rem)