taskli-cli 1.0.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.
taskli/storage.py ADDED
@@ -0,0 +1,687 @@
1
+ """List storage functions."""
2
+
3
+ import json
4
+ import os
5
+ from collections.abc import Callable
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ from pydantic import ValidationError
10
+
11
+ from . import migrations
12
+ from .env import CONFIG_FILE_NAME, scan_list_names
13
+ from .exceptions import (
14
+ CorruptedConfigFileError,
15
+ CorruptedListFileError,
16
+ InvalidListNameError,
17
+ ListAlreadyExistsError,
18
+ ListNotFoundError,
19
+ OutdatedConfigFileError,
20
+ OutdatedListFileError,
21
+ TaskliError,
22
+ TooManyAncestorListsError,
23
+ )
24
+ from .hierarchy import ancestor_chain, descendant_list_names
25
+ from .models.attributes import Color
26
+ from .models.config import Config
27
+ from .models.query import Sort
28
+ from .models.tasks import TaskliList
29
+
30
+
31
+ def config_file_path(storage_dir: Path) -> Path:
32
+ """Return the config file path within the storage directory.
33
+
34
+ Parameters
35
+ ----------
36
+ storage_dir : Path
37
+ The storage directory.
38
+
39
+ Returns
40
+ -------
41
+ Path
42
+ Path to the config file, `.taskli.json`.
43
+ """
44
+
45
+ return storage_dir / CONFIG_FILE_NAME
46
+
47
+
48
+ def load_config(storage_dir: Path) -> Config:
49
+ """Load the config from disk, creating it with defaults if missing.
50
+
51
+ Parameters
52
+ ----------
53
+ storage_dir : Path
54
+ The storage directory.
55
+
56
+ Returns
57
+ -------
58
+ Config
59
+ The loaded, or newly created and saved, config.
60
+ """
61
+
62
+ path = config_file_path(storage_dir)
63
+ if not path.exists():
64
+ config = Config()
65
+ save_config(storage_dir, config)
66
+
67
+ return config
68
+
69
+ try:
70
+ raw = json.loads(path.read_text())
71
+ except json.JSONDecodeError as e:
72
+ raise CorruptedConfigFileError(
73
+ f"config file '{path}' is corrupted and could not be read."
74
+ ) from e
75
+
76
+ if not isinstance(raw, dict):
77
+ raise CorruptedConfigFileError(
78
+ f"config file '{path}' is corrupted and could not be read."
79
+ )
80
+
81
+ if migrations.config_needs_migration(raw):
82
+ raise OutdatedConfigFileError(
83
+ f"config file '{path}' is on an older schema; run 'tk --migrate'."
84
+ )
85
+
86
+ try:
87
+ return Config.model_validate(raw)
88
+ except ValidationError as e:
89
+ raise CorruptedConfigFileError(
90
+ f"config file '{path}' is corrupted and could not be read."
91
+ ) from e
92
+
93
+
94
+ def save_config(storage_dir: Path, config: Config) -> None:
95
+ """Persist the config to its JSON file.
96
+
97
+ Parameters
98
+ ----------
99
+ storage_dir : Path
100
+ The storage directory.
101
+ config : Config
102
+ The config to save.
103
+ """
104
+
105
+ path = config_file_path(storage_dir)
106
+ raw = config.model_dump(mode="json")
107
+ raw["version"] = migrations.CURRENT_CONFIG_VERSION
108
+ path.write_text(json.dumps(raw, indent=2))
109
+
110
+ return None
111
+
112
+
113
+ def list_file_path(storage_dir: Path, name: str) -> Path:
114
+ """Return the JSON file path for a given list name.
115
+
116
+ Parameters
117
+ ----------
118
+ storage_dir : Path
119
+ The storage directory.
120
+ name : str
121
+ The list name.
122
+
123
+ Returns
124
+ -------
125
+ Path
126
+ Path to the list's JSON file.
127
+
128
+ Notes
129
+ -----
130
+ Cannot have descendant lists with a depth greater than 2.
131
+ """
132
+
133
+ _reserved = {".", "..", "con", "prn", "aux", "nul"}
134
+ lowered = name.lower()
135
+ if lowered in _reserved or "/" in lowered or "\\" in lowered:
136
+ raise InvalidListNameError(f"'{name}' is not a valid list name.")
137
+
138
+ # reject empty segments in a nested name.
139
+ segments = name.split(".")
140
+ if len(segments) > 1 and any(not segment for segment in segments):
141
+ raise InvalidListNameError(f"'{name}' is not a valid list name.")
142
+
143
+ # restrict depth to 2.
144
+ if len(ancestor_chain(name)) > 2:
145
+ raise TooManyAncestorListsError(
146
+ f"'{name}' is nested too deep (max 2 sublist levels)."
147
+ )
148
+
149
+ return storage_dir / f"{name}.json"
150
+
151
+
152
+ def _inherited_color(storage_dir: Path, name: str) -> Color | None:
153
+ """Return the nearest existing ancestor list's color, or None.
154
+
155
+ Parameters
156
+ ----------
157
+ storage_dir : Path
158
+ The storage directory.
159
+ name : str
160
+ The list name whose ancestor colors to inspect.
161
+
162
+ Returns
163
+ -------
164
+ Color | None
165
+ The color of the nearest existing ancestor list, or None when
166
+ no ancestor exists or the nearest ones cannot be loaded.
167
+ """
168
+
169
+ for ancestor in reversed(ancestor_chain(name)):
170
+ if not list_exists(storage_dir, ancestor):
171
+ continue
172
+ try:
173
+ return load_list(storage_dir, ancestor).color
174
+ except TaskliError:
175
+ continue
176
+
177
+ return None
178
+
179
+
180
+ def _new_list_color(
181
+ storage_dir: Path,
182
+ name: str,
183
+ explicit: Color | None,
184
+ config: Config | None,
185
+ ) -> Color | None:
186
+ """Resolve a new list's color: explicit > inherited > default.
187
+
188
+ Parameters
189
+ ----------
190
+ storage_dir : Path
191
+ The storage directory.
192
+ name : str
193
+ The new list's name.
194
+ explicit : Color | None
195
+ A caller-supplied color, which always wins when set.
196
+ config : Config | None
197
+ The active config, or None to keep the pre-inheritance behavior
198
+ (an explicit color, else None).
199
+
200
+ Returns
201
+ -------
202
+ Color | None
203
+ The resolved color for the new list.
204
+ """
205
+
206
+ if explicit is not None:
207
+ return explicit
208
+ if config is None:
209
+ return None
210
+ if config.inherit_sublist_color:
211
+ inherited = _inherited_color(storage_dir, name)
212
+ if inherited is not None:
213
+ return inherited
214
+
215
+ return config.default_color
216
+
217
+
218
+ def ensure_ancestors(
219
+ storage_dir: Path,
220
+ name: str,
221
+ *,
222
+ config: Config | None = None,
223
+ ) -> None:
224
+ """Create any missing ancestor lists in `name`'s dot-chain.
225
+
226
+ Parameters
227
+ ----------
228
+ storage_dir : Path
229
+ The storage directory.
230
+ name : str
231
+ The list name whose ancestors should exist.
232
+ config : Config | None, optional
233
+ When given, each auto-created ancestor resolves its color via
234
+ `_new_list_color`; when None (the default), ancestors are
235
+ created with the bare model default, byte-identical to the
236
+ pre-inheritance behavior.
237
+ """
238
+
239
+ for ancestor in ancestor_chain(name):
240
+ if not list_exists(storage_dir, ancestor):
241
+ if config is None:
242
+ save_list(storage_dir, TaskliList(name=ancestor))
243
+ else:
244
+ save_list(
245
+ storage_dir,
246
+ TaskliList(
247
+ name=ancestor,
248
+ color=_new_list_color(
249
+ storage_dir, ancestor, None, config
250
+ ),
251
+ ),
252
+ )
253
+
254
+ return None
255
+
256
+
257
+ def list_exists(storage_dir: Path, name: str) -> bool:
258
+ """Return whether a list file already exists.
259
+
260
+ Parameters
261
+ ----------
262
+ storage_dir : Path
263
+ The storage directory.
264
+ name : str
265
+ The list name.
266
+
267
+ Returns
268
+ -------
269
+ bool
270
+ True if the list's file exists.
271
+ """
272
+
273
+ return list_file_path(storage_dir, name).exists()
274
+
275
+
276
+ def list_all_lists(storage_dir: Path) -> list[str]:
277
+ """Return the names of all existing lists, sorted.
278
+
279
+ Parameters
280
+ ----------
281
+ storage_dir : Path
282
+ The storage directory.
283
+
284
+ Returns
285
+ -------
286
+ list[str]
287
+ Sorted list names.
288
+ """
289
+
290
+ return scan_list_names(storage_dir)
291
+
292
+
293
+ def create_list(
294
+ storage_dir: Path,
295
+ name: str,
296
+ *,
297
+ color: Color | None = None,
298
+ config: Config | None = None,
299
+ ) -> TaskliList:
300
+ """Create and persist a new, empty list.
301
+
302
+ Parameters
303
+ ----------
304
+ storage_dir : Path
305
+ The storage directory.
306
+ name : str
307
+ The new list's name.
308
+ color : Color | None, optional
309
+ The list's display color, by default none.
310
+ config : Config | None, optional
311
+ When given, an unset `color` is resolved via `_new_list_color`
312
+ (nearest existing ancestor's color, else `config.default_color`);
313
+ when None (the default), an unset `color` stays None.
314
+
315
+ Returns
316
+ -------
317
+ TaskliList
318
+ The newly created, empty list.
319
+ """
320
+
321
+ if list_exists(storage_dir, name):
322
+ raise ListAlreadyExistsError(f"list '{name}' already exists.")
323
+
324
+ # if a descendant list (e.g., sublist), ensure all lists before it have
325
+ # already been created.
326
+ ensure_ancestors(storage_dir, name, config=config)
327
+
328
+ task_list = TaskliList(
329
+ name=name,
330
+ color=_new_list_color(storage_dir, name, color, config),
331
+ )
332
+ save_list(storage_dir, task_list)
333
+
334
+ return task_list
335
+
336
+
337
+ def delete_list(storage_dir: Path, name: str) -> list[str]:
338
+ """Delete a list's file and all of its descendant lists.
339
+
340
+ Parameters
341
+ ----------
342
+ storage_dir : Path
343
+ The storage directory.
344
+ name : str
345
+ The list name.
346
+
347
+ Returns
348
+ -------
349
+ list[str]
350
+ Names of descendant lists that were also deleted.
351
+ """
352
+
353
+ path = list_file_path(storage_dir, name)
354
+ if not path.exists():
355
+ raise ListNotFoundError(f"list '{name}' does not exist.")
356
+
357
+ # delete all descendants of list, if exist.
358
+ descendants = descendant_list_names(name, list_all_lists(storage_dir))
359
+ for descendant in descendants:
360
+ list_file_path(storage_dir, descendant).unlink()
361
+
362
+ path.unlink()
363
+
364
+ return descendants
365
+
366
+
367
+ def rename_list(
368
+ storage_dir: Path, old_name: str, new_name: str
369
+ ) -> list[tuple[str, str]]:
370
+ """Rename a list's file and all of its descendant lists.
371
+
372
+ Parameters
373
+ ----------
374
+ storage_dir : Path
375
+ The storage directory.
376
+ old_name : str
377
+ The list's current name.
378
+ new_name : str
379
+ The list's new name.
380
+
381
+ Returns
382
+ -------
383
+ list[tuple[str, str]]
384
+ (old, new) name pairs for the list and every renamed descendant,
385
+ in old-name-ascending order. Empty if `old_name` == `new_name`.
386
+ """
387
+
388
+ if old_name == new_name:
389
+ return []
390
+
391
+ path = list_file_path(storage_dir, old_name)
392
+ if not path.exists():
393
+ raise ListNotFoundError(f"list '{old_name}' does not exist.")
394
+
395
+ descendants = descendant_list_names(old_name, list_all_lists(storage_dir))
396
+ renames = [(old_name, new_name)] + [
397
+ (descendant, new_name + descendant[len(old_name) :])
398
+ for descendant in descendants
399
+ ]
400
+
401
+ # validate every target before touching any file, so a colliding
402
+ # descendant target doesn't leave a partial rename on disk.
403
+ for _, target in renames:
404
+ if list_exists(storage_dir, target):
405
+ raise ListAlreadyExistsError(f"list '{target}' already exists.")
406
+
407
+ ensure_ancestors(storage_dir, new_name)
408
+
409
+ for old, new in renames:
410
+ task_list = load_list(storage_dir, old)
411
+ task_list.name = new
412
+
413
+ save_list(storage_dir, task_list)
414
+ list_file_path(storage_dir, old).unlink()
415
+
416
+ return renames
417
+
418
+
419
+ def load_list(storage_dir: Path, name: str) -> TaskliList:
420
+ """Load a list from disk, parsing its JSON file.
421
+
422
+ Parameters
423
+ ----------
424
+ storage_dir : Path
425
+ The storage directory.
426
+ name : str
427
+ The list name.
428
+
429
+ Returns
430
+ -------
431
+ TaskliList
432
+ The loaded list.
433
+ """
434
+
435
+ path = list_file_path(storage_dir, name)
436
+ if not path.exists():
437
+ config = load_config(storage_dir)
438
+ canonical_default = config.default_list.replace(
439
+ config.sublist_delimiter, "."
440
+ )
441
+ if name == canonical_default:
442
+ task_list = TaskliList(name=name)
443
+ save_list(storage_dir, task_list)
444
+
445
+ return task_list
446
+
447
+ raise ListNotFoundError(
448
+ f"list '{name}' does not exist. Run 'task --lists' to see "
449
+ "available lists."
450
+ )
451
+
452
+ try:
453
+ raw = json.loads(path.read_text())
454
+ except json.JSONDecodeError as e:
455
+ raise CorruptedListFileError(
456
+ f"list file '{path}' is corrupted and could not be read."
457
+ ) from e
458
+
459
+ if not isinstance(raw, dict):
460
+ raise CorruptedListFileError(
461
+ f"list file '{path}' is corrupted and could not be read."
462
+ )
463
+
464
+ if migrations.list_needs_migration(raw):
465
+ raise OutdatedListFileError(
466
+ f"list file '{path}' is on an older schema; run 'tk --migrate'."
467
+ )
468
+
469
+ try:
470
+ task_list = TaskliList.model_validate(raw)
471
+ except ValidationError as e:
472
+ raise CorruptedListFileError(
473
+ f"list file '{path}' is corrupted and could not be read."
474
+ ) from e
475
+
476
+ task_list.reindex()
477
+
478
+ return task_list
479
+
480
+
481
+ def load_or_create_list(
482
+ storage_dir: Path,
483
+ name: str,
484
+ *,
485
+ config: Config | None = None,
486
+ ) -> TaskliList:
487
+ """Load a list, creating it empty if it doesn't exist yet.
488
+
489
+ Parameters
490
+ ----------
491
+ storage_dir : Path
492
+ The storage directory.
493
+ name : str
494
+ The list name.
495
+ config : Config | None, optional
496
+ When given, a newly created list resolves its color via
497
+ `_new_list_color`; when None (the default), it is created with
498
+ the bare model default.
499
+
500
+ Returns
501
+ -------
502
+ TaskliList
503
+ The loaded or newly created list.
504
+ """
505
+
506
+ if list_exists(storage_dir, name):
507
+ return load_list(storage_dir, name)
508
+
509
+ ensure_ancestors(storage_dir, name, config=config)
510
+
511
+ # `config is None` is the legacy path (bare model default); every
512
+ # current caller in `logic` passes a config.
513
+ if config is None:
514
+ task_list = TaskliList(name=name)
515
+ else:
516
+ task_list = TaskliList(
517
+ name=name,
518
+ color=_new_list_color(storage_dir, name, None, config),
519
+ )
520
+ save_list(storage_dir, task_list)
521
+
522
+ return task_list
523
+
524
+
525
+ def save_list(storage_dir: Path, task_list: TaskliList) -> None:
526
+ """Persist a list to its JSON file.
527
+
528
+ Parameters
529
+ ----------
530
+ storage_dir : Path
531
+ The storage directory.
532
+ task_list : TaskliList
533
+ The list to save.
534
+ """
535
+
536
+ if task_list.view_only:
537
+ raise RuntimeError("refusing to save a view-only (filtered) list")
538
+
539
+ task_list.sort_by_index()
540
+ path = list_file_path(storage_dir, task_list.name)
541
+ raw = task_list.model_dump(mode="json")
542
+ raw["version"] = migrations.CURRENT_LIST_VERSION
543
+ path.write_text(json.dumps(raw, indent=2))
544
+
545
+ return None
546
+
547
+
548
+ def resort_all_lists(storage_dir: Path, sort: Sort) -> None:
549
+ """Resort and reindex every list on disk by ``sort``.
550
+
551
+ Parameters
552
+ ----------
553
+ storage_dir : Path
554
+ The storage directory.
555
+ sort : Sort
556
+ The sort mode to apply.
557
+ """
558
+
559
+ for name in list_all_lists(storage_dir):
560
+ try:
561
+ task_list = load_list(storage_dir, name)
562
+ except TaskliError:
563
+ continue
564
+
565
+ task_list.resort(sort)
566
+ save_list(storage_dir, task_list)
567
+
568
+ return None
569
+
570
+
571
+ def _atomic_write(path: Path, text: str) -> None:
572
+ """Write ``text`` to ``path`` via a sibling temp file and rename."""
573
+
574
+ tmp = path.with_name(path.name + ".tmp")
575
+ tmp.write_text(text)
576
+ os.replace(tmp, path)
577
+
578
+ return None
579
+
580
+
581
+ def _migrate_file(
582
+ path: Path,
583
+ needs_migration: Callable[[dict[str, Any]], bool],
584
+ migrate: Callable[[dict[str, Any]], dict[str, Any]],
585
+ validate: Callable[[dict[str, Any]], object],
586
+ ) -> str:
587
+ """Migrate one file in place, returning its outcome string.
588
+
589
+ Parameters
590
+ ----------
591
+ path : Path
592
+ The file to migrate.
593
+ needs_migration : Callable[[dict[str, Any]], bool]
594
+ Predicate telling whether the parsed dict is on an older schema.
595
+ migrate : Callable[[dict[str, Any]], dict[str, Any]]
596
+ The migration to apply when it is.
597
+ validate : Callable[[dict[str, Any]], object]
598
+ A model validator run on the migrated dict before it is written;
599
+ its return value is ignored, only a raised ``ValidationError``
600
+ matters.
601
+
602
+ Returns
603
+ -------
604
+ str
605
+ ``"current"`` when nothing was pending, ``"migrated"`` when a
606
+ migration was applied and written, or ``"unreadable"`` when the
607
+ file could not be read or parsed, its structure was too malformed
608
+ for the migration to run, or the migrated form failed to validate
609
+ (the file is left untouched in every failing case).
610
+ """
611
+
612
+ try:
613
+ raw = json.loads(path.read_text())
614
+ if not isinstance(raw, dict):
615
+ return "unreadable"
616
+ if not needs_migration(raw):
617
+ return "current"
618
+ migrated = migrate(raw)
619
+ validate(migrated)
620
+ _atomic_write(path, json.dumps(migrated, indent=2))
621
+ except Exception:
622
+ # any failure on one file is reported and skipped rather than
623
+ # aborting the whole --migrate walk.
624
+ return "unreadable"
625
+
626
+ return "migrated"
627
+
628
+
629
+ def migrate_all(storage_dir: Path) -> list[tuple[str, str]]:
630
+ """Migrate every on-disk file to the current schema, in place.
631
+
632
+ Walks the config file first, then every list, migrating any that is
633
+ on an older schema and leaving current ones untouched. Idempotent: a
634
+ second call over an already-migrated directory reports every file as
635
+ ``"current"``.
636
+
637
+ Parameters
638
+ ----------
639
+ storage_dir : Path
640
+ The storage directory.
641
+
642
+ Returns
643
+ -------
644
+ list[tuple[str, str]]
645
+ One ``(name, outcome)`` pair per file, config first then lists in
646
+ name order. ``outcome`` is ``"migrated"``, ``"current"``, or
647
+ ``"unreadable"`` (see ``_migrate_file``).
648
+ """
649
+
650
+ results: list[tuple[str, str]] = []
651
+
652
+ config_path = config_file_path(storage_dir)
653
+ if config_path.exists():
654
+ results.append(
655
+ (
656
+ "config",
657
+ _migrate_file(
658
+ config_path,
659
+ migrations.config_needs_migration,
660
+ migrations.migrate_config,
661
+ Config.model_validate,
662
+ ),
663
+ )
664
+ )
665
+
666
+ for name in list_all_lists(storage_dir):
667
+ try:
668
+ path = list_file_path(storage_dir, name)
669
+ except TaskliError:
670
+ # e.g. a legacy file nested too deep to be a valid list name;
671
+ # report it and keep walking rather than aborting the run.
672
+ results.append((name, "unreadable"))
673
+ continue
674
+
675
+ results.append(
676
+ (
677
+ name,
678
+ _migrate_file(
679
+ path,
680
+ migrations.list_needs_migration,
681
+ migrations.migrate_list,
682
+ TaskliList.model_validate,
683
+ ),
684
+ )
685
+ )
686
+
687
+ return results
@@ -0,0 +1,34 @@
1
+ # Shell completion scripts
2
+
3
+ Pre-generated [`argcomplete`](https://github.com/kislyuk/argcomplete) shims for
4
+ `tk` / `taskli` tab-completion. Both entry points are wired by both files.
5
+
6
+ | File | Shells |
7
+ |---|---|
8
+ | `taskli.sh` | bash, zsh |
9
+ | `taskli.ps1` | PowerShell |
10
+
11
+ They are checked in so a new terminal pays no generation cost and nothing needs
12
+ to be on `PATH`. End users `source` (bash/zsh) or dot-source (PowerShell) one
13
+ file — see the `## Shell completion` section of the top-level `README.md`.
14
+
15
+ Packaging (`pyproject.toml`) ships this directory in the sdist and maps it into
16
+ the wheel at `<prefix>/share/taskli/completions/` (for a `uv tool install`, that
17
+ is `$(uv tool dir)/taskli-cli/share/taskli/completions/`).
18
+
19
+ ## Regenerating
20
+
21
+ These are the **verbatim** output of `register-python-argcomplete` — do not
22
+ hand-edit them. The shims are parser-independent (they exec `tk` with
23
+ `_ARGCOMPLETE=1` at TAB time), so regeneration is only needed when `argcomplete`
24
+ itself is upgraded.
25
+
26
+ ```bash
27
+ register-python-argcomplete -s bash tk taskli > completions/taskli.sh
28
+ register-python-argcomplete -s powershell tk taskli > completions/taskli.ps1
29
+ ```
30
+
31
+ Generated with **argcomplete 3.7.2**. When you regenerate, update that version
32
+ here and `EXPECTED_ARGCOMPLETE` in `tests/test_completions.py` — the guard test
33
+ compares the committed files against a fresh generation only when the installed
34
+ `argcomplete` matches that version.