Debian Codegraph @

jupyter_cache/utils.py

raw
1 """Non-core imports in this module are lazily loaded, in order to improve CLI speed """
2
3 from pathlib import Path
4 import time
5 from typing import TYPE_CHECKING, List, Optional, Union
6
7 from jupyter_cache.readers import NbReadError
8
9 if TYPE_CHECKING:
10 from jupyter_cache.base import JupyterCacheAbstract
11 from jupyter_cache.cache.db import NbCacheRecord, NbProjectRecord
12
13
14 def to_relative_paths(
15 paths: List[Union[str, Path]],
16 folder: Union[str, Path],
17 check_existence: bool = False,
18 ) -> List[Path]:
19 """Make paths relative to a reference folder.
20
21 :param paths: list of paths
22 :param folder: The folder that all paths should be in (or subfolder).
23 :param check_existence: check the paths exist
24 :raises IOError: path is not relative or failed existence check
25
26 """
27 rel_paths = []
28 folder = Path(folder).absolute()
29 for path in paths:
30 path = Path(path).absolute()
31 if check_existence and not path.exists():
32 raise OSError(f"Path does not exist: {path}")
33 if check_existence and not path.is_file():
34 raise OSError(f"Path is not a file: {path}")
35 try:
36 rel_path = path.relative_to(folder)
37 except ValueError:
38 raise OSError(f"Path '{path}' is not in folder '{folder}''")
39 rel_paths.append(rel_path)
40 return rel_paths
41
42
43 class Timer:
44 """Context manager for timing runtime."""
45
46 def __init__(self):
47 self._last_time = time.perf_counter()
48 self._split_time = 0.0
49
50 @property
51 def last_split(self):
52 return self._split_time
53
54 def reset(self):
55 """Reset timer."""
56 self._last_time = time.perf_counter()
57 self._split_time = 0.0
58
59 def split(self):
60 """Record a split time."""
61 self._split_time = time.perf_counter() - self._last_time
62
63 def __enter__(self):
64 """Reset timer."""
65 self.reset()
66 return self
67
68 def __exit__(self, *exc_info):
69 """Record a split time."""
70 self.split()
71
72
73 def shorten_path(file_path: Union[str, Path], length: Optional[int]) -> Path:
74 """Split the path into separate parts,
75 select the last 'length' elements and join them again
76 """
77 if length is None:
78 return Path(file_path)
79 return Path(*Path(file_path).parts[-length:])
80
81
82 def tabulate_cache_records(
83 records: List["NbCacheRecord"], hashkeys=False, path_length=None
84 ) -> str:
85 """Tabulate cache records.
86
87 :param records: list of ``NbCacheRecord``
88 :param hashkeys: include a hashkey column
89 :param path_length: truncate URI paths to x components
90 """
91 import tabulate
92
93 return tabulate.tabulate(
94 [
95 r.format_dict(hashkey=hashkeys, path_length=path_length, show_data=False)
96 for r in sorted(records, key=lambda r: r.accessed, reverse=True)
97 ],
98 headers="keys",
99 )
100
101
102 def tabulate_project_records(
103 records: List["NbProjectRecord"],
104 path_length: Optional[int] = None,
105 cache: Optional["JupyterCacheAbstract"] = None,
106 assets=False,
107 ) -> str:
108 """Tabulate cache records.
109
110 :param records: list of ``NbProjectRecord``
111 :param path_length: truncate URI paths to x components
112 :param cache: If the cache is given,
113 we use it to add a column of matched cached pk (if available)
114 :param assets: Show the number of assets
115 """
116 import tabulate
117
118 rows = []
119 for record in records:
120 cache_record = None
121 read_error = None
122 if cache is not None:
123 try:
124 cache_record = cache.get_cached_project_nb(record.uri)
125 except NbReadError as exc:
126 read_error = f"{exc.__class__.__name__}: {exc}"
127 rows.append(
128 record.format_dict(
129 cache_record=cache_record,
130 path_length=path_length,
131 assets=assets,
132 read_error=read_error,
133 )
134 )
135 return tabulate.tabulate(rows, headers="keys")