1#!/usr/bin/env python3
2"""
3
4
5"""
6# Imports:
7from __future__ import annotations
8
9# ##-- stdlib imports
10import datetime
11import enum
12import functools as ftz
13import itertools as itz
14import logging as logmod
15import pathlib as pl
16import re
17import time
18import types
19import collections
20import contextlib
21import hashlib
22from copy import deepcopy
23from uuid import UUID, uuid1
24from weakref import ref
25import atexit # for @atexit.register
26import faulthandler
27# ##-- end stdlib imports
28
29from jgdv import Proto, Mixin
30from bibtexparser import model, Library
31import bibble._interface as API
32from bibble.util.middlecore import IdenBlockMiddleware
33
34# ##-- types
35# isort: off
36import abc
37import collections.abc
38from typing import TYPE_CHECKING, cast, assert_type, assert_never
39from typing import Generic, NewType
40# Protocols:
41from typing import Protocol, runtime_checkable
42# Typing Decorators:
43from typing import no_type_check, final, override, overload
44
45if TYPE_CHECKING:
46 from jgdv import Maybe
47 from typing import Final
48 from typing import ClassVar, Any, LiteralString
49 from typing import Never, Self, Literal
50 from typing import TypeGuard
51 from collections.abc import Iterable, Iterator, Callable, Generator
52 from collections.abc import Sequence, Mapping, MutableMapping, Hashable
53
54 type Field = model.Field
55 type Entry = model.Entry
56##--|
57
58# isort: on
59# ##-- end types
60
61##-- logging
62logging = logmod.getLogger(__name__)
63##-- end logging
64
65# Vars:
66
67# Body:
68
[docs]
69@Proto(API.Middleware_p)
70class EntrySorter(IdenBlockMiddleware):
71 """ Reorder the entries in a library according to a sort key
72 Key defaults to sort by the entry key
73
74 eg: sort by year, or type, or author
75 ie: EntrySorterMiddleware(key=lambda x: x.fields_dict['year'].value)
76 """
77
78 def __init__(self, *args, key:Maybe[Callable]=None, **kwargs) -> None:
79 super().__init__(*args, **kwargs)
80 match key:
81 case x if callable(x):
82 self._key_fn = key
83 case _:
84 self._key_fn = lambda x: x.key
85
86
[docs]
87 def transform(self, library:Library) -> Library:
88 l2 = super().transform(library)
89 # Sort entries
90 entries = sorted(library.entries, key=self._key_fn)
91 l2.remove(entries)
92 l2.add(entries)
93 # Insert
94 return l2