Skip to content

Commit

Permalink
basename_natural: Improve performance
Browse files Browse the repository at this point in the history
  • Loading branch information
mingmingrr committed Jan 28, 2024
1 parent 136416c commit 64a1a38
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 17 deletions.
22 changes: 11 additions & 11 deletions ranger/container/fsobject.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@

_UNSAFE_CHARS = '\n' + ''.join(map(chr, range(32))) + ''.join(map(chr, range(128, 256)))
_SAFE_STRING_TABLE = maketrans(_UNSAFE_CHARS, '?' * len(_UNSAFE_CHARS))
_EXTRACT_NUMBER_RE = re.compile(r'(\d+|\D)')
_EXTRACT_NUMBER_RE = re.compile(r'\d+|\D+')


def safe_path(path):
Expand Down Expand Up @@ -157,21 +157,21 @@ def filetype(self):
@lazy_property
def basename_natural(self):
basename_list = []
for string in _EXTRACT_NUMBER_RE.split(self.relative_path):
try:
basename_list += [('0', int(string))]
except ValueError:
basename_list += [(string, 0)]
for string in _EXTRACT_NUMBER_RE.findall(self.relative_path):
if string[0].isdigit():
basename_list.append(('0', int(string)))
else:
basename_list.append((string,))
return basename_list

@lazy_property
def basename_natural_lower(self):
basename_list = []
for string in _EXTRACT_NUMBER_RE.split(self.relative_path_lower):
try:
basename_list += [('0', int(string))]
except ValueError:
basename_list += [(string, 0)]
for string in _EXTRACT_NUMBER_RE.findall(self.relative_path_lower):
if string[0].isdigit():
basename_list.append(('0', int(string)))
else:
basename_list.append((string,))
return basename_list

@lazy_property
Expand Down
13 changes: 7 additions & 6 deletions tests/ranger/container/test_fsobject.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def test_basename_natural1():
"hello",
"hello1", "hello2",
"hello11", "hello12",
"hello100", "hello101", "hello111", "hello112",
"hello100", "hello101", "hello111", "hello112"
)
]
assert fsos == sorted(fsos[::-1], key=operator.attrgetter("basename_natural"))
Expand All @@ -42,11 +42,12 @@ def test_basename_natural2():
fsos = [
create_filesystem_object(path)
for path in (
"hello", "hello.txt",
"hello0.txt", "hello1.txt", "hello2.txt", "hello3.txt"
"hello10.txt", "hello11.txt", "hello12.txt", "hello13.txt"
"hello100.txt", "hello101.txt", "hello102.txt", "hello103.txt"
"hello110.txt", "hello111.txt", "hello112.txt", "hello113.txt"
"hello",
"hello0.txt", "hello1.txt", "hello2.txt", "hello3.txt",
"hello10.txt", "hello11.txt", "hello12.txt", "hello13.txt",
"hello100.txt", "hello101.txt", "hello102.txt", "hello103.txt",
"hello110.txt", "hello111.txt", "hello112.txt", "hello113.txt",
"hello.txt"
)
]
assert fsos == sorted(fsos[::-1], key=operator.attrgetter("basename_natural"))
Expand Down

0 comments on commit 64a1a38

Please sign in to comment.