notex-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
notex/sessions.py ADDED
@@ -0,0 +1,177 @@
1
+ """Session folders: how they are named, how to recognise them, how to scan a notes tree.
2
+
3
+ Read-only: paths in, sessions out. Nothing prints, exits or reads the environment.
4
+ """
5
+
6
+ import datetime
7
+ import re
8
+ from collections.abc import Iterator
9
+ from pathlib import Path
10
+ from typing import NamedTuple
11
+
12
+ __all__ = [
13
+ 'SESSION_DATE_FORMAT',
14
+ 'SUBJECT_DEPTH',
15
+ 'TERM_DEPTH',
16
+ 'Session',
17
+ 'explicit_counter',
18
+ 'find_sessions',
19
+ 'kind_names',
20
+ 'newest_term',
21
+ 'next_session_name',
22
+ 'session_date',
23
+ 'term_folders',
24
+ 'visible_subdirectories',
25
+ ]
26
+
27
+ # Weekday, day, month and year as they appear in a new folder name, e.g. Sun-11-Oct-2026.
28
+ SESSION_DATE_FORMAT = '%a-%d-%b-%Y'
29
+
30
+ # How many folder levels find_sessions may descend (depth=1 is the sessions directly inside
31
+ # one folder). The tree is ROOT/<degree>/<N>_term/<subject>/[<kind>/]<session>.
32
+ SUBJECT_DEPTH = 2 # a subject, with or without kind folders
33
+ TERM_DEPTH = 3 # a whole term
34
+
35
+ # Folder names that count as a session, old and new shapes alike:
36
+ # 1-Thu-09-Mar-2023-note
37
+ # 01-Sun-11-Oct-2026
38
+ # 21-Mar-Sat-2026
39
+ # 01-25-Oct-Sun-2026
40
+ # 03-15-Nov-2026
41
+ # 2-Tue-03-October-2023-grand
42
+ # Only the date part matters; any counter or suffix around it is ignored.
43
+ _SESSION_PATTERN = re.compile(
44
+ r"""
45
+ (?:^|-) # the date starts the name or follows a dash
46
+ (?P<day>\d{1,2})- # day of the month, 9 or 09
47
+ (?P<month>Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) # month, first three letters
48
+ [a-z]*- # rest of a spelled-out month (October)
49
+ (?:(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)-)? # weekday, when the name has one here
50
+ (?P<year>\d{4}) # four digit year
51
+ (?:-|$) # the date ends the name or precedes a dash
52
+ """,
53
+ re.VERBOSE,
54
+ )
55
+
56
+ # A counter written at the very start of a name: the 01 in 01-Sun-11-Oct-2026.
57
+ _LEADING_COUNTER_PATTERN = re.compile(r'(\d+)-')
58
+
59
+ # What strptime needs to read the three date groups of _SESSION_PATTERN.
60
+ _PARSED_DATE_FORMAT = '%d %b %Y'
61
+
62
+
63
+ class Session(NamedTuple):
64
+ """A session folder together with the date written in its name."""
65
+
66
+ date: datetime.date
67
+ path: Path
68
+
69
+
70
+ def session_date(name: str) -> datetime.date | None:
71
+ """Return the date in a session folder name, or None if the name is not a session.
72
+
73
+ A name that looks like a session but is not a real day (31 Feb) is not one either.
74
+ """
75
+ match = _SESSION_PATTERN.search(name)
76
+ if match is None:
77
+ return None
78
+
79
+ text = f'{match["day"]} {match["month"]} {match["year"]}'
80
+ try:
81
+ return datetime.datetime.strptime(text, _PARSED_DATE_FORMAT).date()
82
+ except ValueError:
83
+ return None
84
+
85
+
86
+ def explicit_counter(name: str) -> int:
87
+ """Return the counter a session name starts with, or 0 if it has none.
88
+
89
+ Digits at the start of the name only count when they come before the date. In
90
+ 21-Mar-Sat-2026 the 21 is the day of the month, not a counter.
91
+ """
92
+ match = _SESSION_PATTERN.search(name)
93
+ if match is None or match.start() == 0:
94
+ return 0
95
+ leading = _LEADING_COUNTER_PATTERN.match(name)
96
+ if leading is None:
97
+ return 0
98
+ return int(leading[1])
99
+
100
+
101
+ def find_sessions(folder: Path, depth: int = SUBJECT_DEPTH) -> Iterator[Session]:
102
+ """Yield the sessions in `folder`, descending at most `depth` levels, in name order.
103
+
104
+ Hidden folders are skipped. A session is never searched for further sessions, and a
105
+ symlink that is not itself a session is not followed, so a link cannot pull another
106
+ tree into the scan.
107
+ """
108
+ for child in visible_subdirectories(folder):
109
+ found_date = session_date(child.name)
110
+ if found_date is not None:
111
+ yield Session(found_date, child)
112
+ elif depth > 1 and not child.is_symlink():
113
+ yield from find_sessions(child, depth - 1)
114
+
115
+
116
+ def visible_subdirectories(folder: Path) -> list[Path]:
117
+ """Return the sub-folders of `folder` whose names do not start with a dot, sorted.
118
+
119
+ A folder that cannot be listed (missing, not a folder, no permission) has none.
120
+ """
121
+ try:
122
+ children = sorted(folder.iterdir())
123
+ except OSError:
124
+ return []
125
+ return [child for child in children if child.is_dir() and not child.name.startswith('.')]
126
+
127
+
128
+ def kind_names(subject_folder: Path) -> list[str]:
129
+ """Return the names of the folders inside a subject that hold sessions (lecture, labs)."""
130
+ return [
131
+ folder.name
132
+ for folder in visible_subdirectories(subject_folder)
133
+ if _contains_sessions(folder)
134
+ ]
135
+
136
+
137
+ def term_folders(root: Path) -> list[Path]:
138
+ """Return every ROOT/<degree>/<N>_term folder, sorted."""
139
+ return sorted(path for path in root.glob('*/*_term') if path.is_dir())
140
+
141
+
142
+ def newest_term(root: Path) -> Path | None:
143
+ """Return the term holding the newest session, or None if the root has no terms.
144
+
145
+ Terms with equally new sessions are ordered by path, so the answer does not depend on
146
+ the order the filesystem lists them in.
147
+ """
148
+ terms = term_folders(root)
149
+ if not terms:
150
+ return None
151
+ # A term without sessions ranks below every other term, so a brand-new empty term has to
152
+ # be named with -T once before it can become the current one.
153
+ return max(terms, key=_term_rank)
154
+
155
+
156
+ def next_session_name(parent: Path, template: str | None, today: datetime.date) -> str:
157
+ """Return the folder name for the next session in `parent`, e.g. 04-Sun-15-Nov-2026-note.
158
+
159
+ The number is one more than the larger of the sessions already in `parent` and the
160
+ highest counter among their names, so a gap left by a deleted session is not reused.
161
+ """
162
+ existing = [session.path.name for session in find_sessions(parent, depth=1)]
163
+ counters = [explicit_counter(name) for name in existing]
164
+ last_number = max([len(existing), *counters])
165
+ suffix = f'-{template}' if template else ''
166
+ return f'{last_number + 1:02d}-{today.strftime(SESSION_DATE_FORMAT)}{suffix}'
167
+
168
+
169
+ def _contains_sessions(folder: Path) -> bool:
170
+ """Tell whether `folder` has at least one session directly inside it."""
171
+ return next(find_sessions(folder, depth=1), None) is not None
172
+
173
+
174
+ def _term_rank(term: Path) -> tuple[datetime.date, str]:
175
+ """Order terms by their newest session, then by path."""
176
+ session_dates = [session.date for session in find_sessions(term, TERM_DEPTH)]
177
+ return max(session_dates, default=datetime.date.min), str(term)