From 85ac6bc35c145015c09f8c8846d567b8213a9f38 Mon Sep 17 00:00:00 2001 From: xenofem Date: Tue, 6 Feb 2024 13:00:44 -0500 Subject: [PATCH] handle cases where the first item isn't numbered --- dlibrary/dlibrary.py | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/dlibrary/dlibrary.py b/dlibrary/dlibrary.py index ef8bbb8..4e2eea6 100755 --- a/dlibrary/dlibrary.py +++ b/dlibrary/dlibrary.py @@ -245,26 +245,31 @@ def complete_prefix_number_ordering(entries): return result def unique_hierarchical_prefix_numbering(entries, start_point=0): - matches = reversed(list(NUMBER_REGEX.finditer(entries[0].name))) + longest_entry = max(entries, key=lambda e: len(e.name)) + matches = reversed(list(NUMBER_REGEX.finditer(longest_entry.name))) for m in matches: pos = m.start() if pos < start_point: return None - prefix = entries[0].name[:pos] - if all(e.name.startswith(prefix) for e in entries): + prefix = longest_entry.name[:pos] + if all(e.name.startswith(prefix) or prefix.startswith(e.stem) for e in entries): numbering = {} for e in entries: - n = NUMBER_REGEX.match(e.name[pos:]) - if n is None: - return None - i = int(n.group()) + if pos >= len(e.stem): + i = 0 + else: + n = NUMBER_REGEX.match(e.name[pos:]) + if n is None: + return None + i = int(n.group()) numbering.setdefault((i,), []).append(e) indices = list(numbering.keys()) for idx in indices: if len(numbering[idx]) > 1: ents_idx = numbering.pop(idx) - next_layer_start = pos + NUMBER_REGEX.match(ents_idx[0].name[pos:]).end() + longest = max(ents_idx, key=lambda e: len(e.name)) + next_layer_start = pos + NUMBER_REGEX.match(longest.name[pos:]).end() sub_numbering = unique_hierarchical_prefix_numbering(ents_idx, start_point=next_layer_start) or alphabetic_numbering(ents_idx, next_layer_start) if not sub_numbering: return None