lyutil 0.1.0__tar.gz

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.
lyutil-0.1.0/LICENCE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Leyton Addison-Roach
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
lyutil-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,65 @@
1
+ Metadata-Version: 2.4
2
+ Name: lyutil
3
+ Version: 0.1.0
4
+ Summary: A lightweight collection of everyday Python utilities.
5
+ Keywords: utilities,timestamps,filenames
6
+ Author: Leyton Addison-Roach
7
+ Author-email: Leyton Addison-Roach <git@laddisonroach.com>
8
+ License-Expression: MIT
9
+ License-File: LICENCE
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.14
15
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
16
+ Classifier: Typing :: Typed
17
+ Requires-Python: >=3.14
18
+ Project-URL: Repository, https://github.com/leyts/lyutil
19
+ Project-URL: Issues, https://github.com/leyts/lyutil/issues
20
+ Description-Content-Type: text/markdown
21
+
22
+ # lyutil
23
+
24
+ A lightweight collection of everyday Python utilities.
25
+
26
+ ## Modules
27
+
28
+ ### Timestamps
29
+
30
+ Embed and extract timestamps in filenames.
31
+
32
+ ```python
33
+ from pathlib import Path
34
+ from lyutil import FileTimestamp
35
+ ```
36
+
37
+ **Add a timestamp to a filename:**
38
+
39
+ ```python
40
+ >>> result = FileTimestamp.add(Path("backup.tar.gz"))
41
+ >>> print(result.file)
42
+ backup_2026-02-25_14-30-00.tar.gz
43
+ >>> print(result.timestamp)
44
+ 2026-02-25 14:30:00
45
+ ```
46
+
47
+ **Read the timestamp back:**
48
+
49
+ ```python
50
+ >>> parsed = FileTimestamp.read(result.file)
51
+ >>> print(parsed.file)
52
+ backup.tar.gz
53
+ >>> print(parsed.timestamp)
54
+ 2026-02-25 14:30:00
55
+ >>> print(parsed.age)
56
+ 0:00:12.345678
57
+ ```
58
+
59
+ ## Requirements
60
+
61
+ Python 3.14+
62
+
63
+ ## Licence
64
+
65
+ [MIT](LICENCE)
lyutil-0.1.0/README.md ADDED
@@ -0,0 +1,44 @@
1
+ # lyutil
2
+
3
+ A lightweight collection of everyday Python utilities.
4
+
5
+ ## Modules
6
+
7
+ ### Timestamps
8
+
9
+ Embed and extract timestamps in filenames.
10
+
11
+ ```python
12
+ from pathlib import Path
13
+ from lyutil import FileTimestamp
14
+ ```
15
+
16
+ **Add a timestamp to a filename:**
17
+
18
+ ```python
19
+ >>> result = FileTimestamp.add(Path("backup.tar.gz"))
20
+ >>> print(result.file)
21
+ backup_2026-02-25_14-30-00.tar.gz
22
+ >>> print(result.timestamp)
23
+ 2026-02-25 14:30:00
24
+ ```
25
+
26
+ **Read the timestamp back:**
27
+
28
+ ```python
29
+ >>> parsed = FileTimestamp.read(result.file)
30
+ >>> print(parsed.file)
31
+ backup.tar.gz
32
+ >>> print(parsed.timestamp)
33
+ 2026-02-25 14:30:00
34
+ >>> print(parsed.age)
35
+ 0:00:12.345678
36
+ ```
37
+
38
+ ## Requirements
39
+
40
+ Python 3.14+
41
+
42
+ ## Licence
43
+
44
+ [MIT](LICENCE)
@@ -0,0 +1,73 @@
1
+ [project]
2
+ name = "lyutil"
3
+ version = "0.1.0"
4
+ description = "A lightweight collection of everyday Python utilities."
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENCE"]
8
+ authors = [
9
+ { name = "Leyton Addison-Roach", email = "git@laddisonroach.com" },
10
+ ]
11
+ requires-python = ">=3.14"
12
+ keywords = ["utilities", "timestamps", "filenames"]
13
+ classifiers = [
14
+ "Development Status :: 3 - Alpha",
15
+ "Intended Audience :: Developers",
16
+ "License :: OSI Approved :: MIT License",
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3.14",
19
+ "Topic :: Software Development :: Libraries :: Python Modules",
20
+ "Typing :: Typed",
21
+ ]
22
+ dependencies = []
23
+
24
+ [project.urls]
25
+ Repository = "https://github.com/leyts/lyutil"
26
+ Issues = "https://github.com/leyts/lyutil/issues"
27
+
28
+ [dependency-groups]
29
+ dev = [
30
+ "pytest>=9.0.2",
31
+ "ruff>=0.15.2",
32
+ "time-machine>=3.2.0",
33
+ "ty>=0.0.18",
34
+ ]
35
+
36
+ [build-system]
37
+ requires = ["uv_build>=0.10.4,<0.11.0"]
38
+ build-backend = "uv_build"
39
+
40
+ [tool.ruff]
41
+ line-length = 79
42
+
43
+ [tool.ruff.format]
44
+ docstring-code-format = true
45
+ docstring-code-line-length = 20
46
+
47
+ [tool.ruff.lint]
48
+ select = ["ALL"]
49
+ ignore = [
50
+ "W191",
51
+ "E111",
52
+ "E114",
53
+ "E117",
54
+ "D206",
55
+ "D300",
56
+ "Q000",
57
+ "Q001",
58
+ "Q002",
59
+ "Q003",
60
+ "COM812",
61
+ "COM819",
62
+ "TD",
63
+ ]
64
+
65
+ [tool.ruff.lint.per-file-ignores]
66
+ "tests/*.py" = [
67
+ "ANN201",
68
+ "D104",
69
+ "S101",
70
+ ]
71
+
72
+ [tool.ruff.lint.pydocstyle]
73
+ convention = "google"
@@ -0,0 +1,11 @@
1
+ """lyutil — lightweight utility functions."""
2
+
3
+ from lyutil.exceptions import InvalidPathError, TimestampParseError
4
+ from lyutil.timestamps import FileTimestamp, TimestampedFile
5
+
6
+ __all__ = [
7
+ "FileTimestamp",
8
+ "InvalidPathError",
9
+ "TimestampParseError",
10
+ "TimestampedFile",
11
+ ]
@@ -0,0 +1,9 @@
1
+ """Custom exceptions for lyutil."""
2
+
3
+
4
+ class InvalidPathError(ValueError):
5
+ """Raised when a path has no usable stem."""
6
+
7
+
8
+ class TimestampParseError(ValueError):
9
+ """Raised when a filename does not contain a valid timestamp."""
File without changes
@@ -0,0 +1,118 @@
1
+ """Utilities for embedding timestamps in filenames."""
2
+
3
+ from datetime import datetime, timedelta
4
+ from typing import TYPE_CHECKING, ClassVar, NamedTuple
5
+
6
+ from lyutil.exceptions import InvalidPathError, TimestampParseError
7
+
8
+ if TYPE_CHECKING:
9
+ from pathlib import Path
10
+
11
+
12
+ class TimestampedFile(NamedTuple):
13
+ """A path paired with the timestamp extracted from its filename."""
14
+
15
+ file: Path
16
+ timestamp: datetime
17
+
18
+ @property
19
+ def age(self) -> timedelta:
20
+ """Time elapsed since the embedded timestamp."""
21
+ return datetime.now() - self.timestamp # noqa: DTZ005
22
+
23
+
24
+ class FileTimestamp:
25
+ """Add and read timestamps in filenames."""
26
+
27
+ _DT_FORMAT: ClassVar[str] = "%Y-%m-%d_%H-%M-%S"
28
+ _SEPARATOR: ClassVar[str] = "_"
29
+
30
+ @staticmethod
31
+ def _validate_file(file: Path) -> None:
32
+ """Raise ``InvalidPathError`` if *file* has no usable stem."""
33
+ if not file.stem or file.stem.isspace():
34
+ msg = "Path has no usable stem"
35
+ raise InvalidPathError(msg)
36
+
37
+ @staticmethod
38
+ def _split_stem(stem: str) -> tuple[str, str]:
39
+ """Split a stem into the original stem and raw timestamp.
40
+
41
+ Args:
42
+ stem: The filename stem to split.
43
+
44
+ Returns:
45
+ A ``(original_stem, raw_timestamp)`` tuple.
46
+
47
+ Raises:
48
+ TimestampParseError: If the stem is too short or the
49
+ separator is missing.
50
+ """
51
+ sep: str = FileTimestamp._SEPARATOR
52
+ min_length: int = len(
53
+ datetime.min.strftime(format=FileTimestamp._DT_FORMAT) + sep # noqa: DTZ901
54
+ )
55
+
56
+ if len(stem) <= min_length:
57
+ msg = f"Stem too short to contain a timestamp: {stem}"
58
+ raise TimestampParseError(msg)
59
+
60
+ if stem[-min_length] != sep:
61
+ msg = f"Expected {sep!r} before timestamp in: {stem}"
62
+ raise TimestampParseError(msg)
63
+
64
+ return stem[:-min_length], stem[-min_length + len(sep) :]
65
+
66
+ @staticmethod
67
+ def add(file: Path, timestamp: datetime | None = None) -> TimestampedFile:
68
+ """Return a new path with a timestamp appended to the stem.
69
+
70
+ Args:
71
+ file: The original file path.
72
+ timestamp: The datetime to embed.
73
+ Defaults to ``datetime.now()``.
74
+
75
+ Returns:
76
+ A :class:`TimestampedFile` containing the timestamped
77
+ path and the datetime used.
78
+ """
79
+ FileTimestamp._validate_file(file)
80
+
81
+ if timestamp is None:
82
+ timestamp = datetime.now() # noqa: DTZ005
83
+
84
+ formatted: str = timestamp.strftime(format=FileTimestamp._DT_FORMAT)
85
+ stamped: Path = file.with_stem(
86
+ stem=f"{file.stem}{FileTimestamp._SEPARATOR}{formatted}"
87
+ )
88
+ return TimestampedFile(file=stamped, timestamp=timestamp)
89
+
90
+ @staticmethod
91
+ def read(file: Path) -> TimestampedFile:
92
+ """Extract a timestamp previously added by :meth:`add`.
93
+
94
+ Args:
95
+ file: A path whose stem ends with
96
+ ``_YYYY-MM-DD_HH-MM-SS``.
97
+
98
+ Returns:
99
+ A :class:`TimestampedFile` containing the original path
100
+ (without the timestamp) and the parsed ``datetime``.
101
+
102
+ Raises:
103
+ TimestampParseError: If *file* does not contain a valid
104
+ timestamp suffix.
105
+ """
106
+ FileTimestamp._validate_file(file)
107
+ org_stem, raw_ts = FileTimestamp._split_stem(file.stem)
108
+
109
+ try:
110
+ ts: datetime = datetime.strptime( # noqa: DTZ007
111
+ raw_ts, FileTimestamp._DT_FORMAT
112
+ )
113
+ except ValueError:
114
+ msg = f"Could not parse timestamp: {raw_ts!r}"
115
+ raise TimestampParseError(msg) from None
116
+
117
+ org_file: Path = file.with_stem(stem=org_stem)
118
+ return TimestampedFile(file=org_file, timestamp=ts)