tempit-manager 0.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.
- tempit_manager-0.0/LICENSE +21 -0
- tempit_manager-0.0/PKG-INFO +75 -0
- tempit_manager-0.0/README.md +56 -0
- tempit_manager-0.0/pyproject.toml +36 -0
- tempit_manager-0.0/tempit/__init__.py +0 -0
- tempit_manager-0.0/tempit/cli.py +65 -0
- tempit_manager-0.0/tempit/core.py +93 -0
- tempit_manager-0.0/tempit/models.py +40 -0
- tempit_manager-0.0/tempit/render.py +73 -0
- tempit_manager-0.0/tempit/services.py +43 -0
- tempit_manager-0.0/tempit/shell/init.sh +38 -0
- tempit_manager-0.0/tempit/stats.py +29 -0
- tempit_manager-0.0/tempit/storage.py +75 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 idirxv
|
|
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.
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: tempit-manager
|
|
3
|
+
Version: 0.0
|
|
4
|
+
Summary: Manage and jump into temporary working directories
|
|
5
|
+
License-File: LICENSE
|
|
6
|
+
Author: Idir Oura
|
|
7
|
+
Author-email: idir.oura@protonmail.com
|
|
8
|
+
Requires-Python: >=3.10,<3.14
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
14
|
+
Requires-Dist: humanize
|
|
15
|
+
Requires-Dist: rich
|
|
16
|
+
Requires-Dist: typer
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
|
|
19
|
+
# Tempit - Temporary Directory Manager
|
|
20
|
+
|
|
21
|
+
Tempit is a command-line utility and shell helper that lets you create, track, and jump to temporary directories without losing them.
|
|
22
|
+
## Features
|
|
23
|
+
|
|
24
|
+
- Create temporary directories with optional prefixes.
|
|
25
|
+
- List tracked directories with size, creation time, age, and file counts.
|
|
26
|
+
- Jump to a directory by its number.
|
|
27
|
+
- Remove individual directories or clean them all.
|
|
28
|
+
- Works via shell integration.
|
|
29
|
+
|
|
30
|
+
## Installation
|
|
31
|
+
|
|
32
|
+
### Using pip
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
pip install tempit-manager
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
### Shell integration
|
|
39
|
+
|
|
40
|
+
Add the following line to your shell startup file (`~/.bashrc` or `~/.zshrc`):
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
# Bash
|
|
44
|
+
eval "$(tempit init bash)"
|
|
45
|
+
|
|
46
|
+
# Zsh
|
|
47
|
+
eval "$(tempit init zsh)"
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Usage
|
|
51
|
+
|
|
52
|
+
### CLI commands
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
tempit create [prefix]
|
|
56
|
+
tempit list
|
|
57
|
+
tempit remove <number>
|
|
58
|
+
tempit clean-all
|
|
59
|
+
tempit init <shell>
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
### Aliases (after shell init)
|
|
63
|
+
|
|
64
|
+
| Alias | Description |
|
|
65
|
+
|-------|-------------|
|
|
66
|
+
| `tempc [prefix]` | Create a new temporary directory and cd into it |
|
|
67
|
+
| `tempg <number>` | Jump to a directory by its number |
|
|
68
|
+
| `templ` | List tracked temporary directories |
|
|
69
|
+
| `temprm <number>` | Remove a tracked temporary directory by its number |
|
|
70
|
+
| `tempclean` | Remove all tracked temporary directories |
|
|
71
|
+
|
|
72
|
+
## License
|
|
73
|
+
|
|
74
|
+
[MIT](LICENSE)
|
|
75
|
+
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
# Tempit - Temporary Directory Manager
|
|
2
|
+
|
|
3
|
+
Tempit is a command-line utility and shell helper that lets you create, track, and jump to temporary directories without losing them.
|
|
4
|
+
## Features
|
|
5
|
+
|
|
6
|
+
- Create temporary directories with optional prefixes.
|
|
7
|
+
- List tracked directories with size, creation time, age, and file counts.
|
|
8
|
+
- Jump to a directory by its number.
|
|
9
|
+
- Remove individual directories or clean them all.
|
|
10
|
+
- Works via shell integration.
|
|
11
|
+
|
|
12
|
+
## Installation
|
|
13
|
+
|
|
14
|
+
### Using pip
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
pip install tempit-manager
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
### Shell integration
|
|
21
|
+
|
|
22
|
+
Add the following line to your shell startup file (`~/.bashrc` or `~/.zshrc`):
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
# Bash
|
|
26
|
+
eval "$(tempit init bash)"
|
|
27
|
+
|
|
28
|
+
# Zsh
|
|
29
|
+
eval "$(tempit init zsh)"
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Usage
|
|
33
|
+
|
|
34
|
+
### CLI commands
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
tempit create [prefix]
|
|
38
|
+
tempit list
|
|
39
|
+
tempit remove <number>
|
|
40
|
+
tempit clean-all
|
|
41
|
+
tempit init <shell>
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
### Aliases (after shell init)
|
|
45
|
+
|
|
46
|
+
| Alias | Description |
|
|
47
|
+
|-------|-------------|
|
|
48
|
+
| `tempc [prefix]` | Create a new temporary directory and cd into it |
|
|
49
|
+
| `tempg <number>` | Jump to a directory by its number |
|
|
50
|
+
| `templ` | List tracked temporary directories |
|
|
51
|
+
| `temprm <number>` | Remove a tracked temporary directory by its number |
|
|
52
|
+
| `tempclean` | Remove all tracked temporary directories |
|
|
53
|
+
|
|
54
|
+
## License
|
|
55
|
+
|
|
56
|
+
[MIT](LICENSE)
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["poetry-core>=2.0.0", "poetry-dynamic-versioning>=1.0.0,<2.0.0"]
|
|
3
|
+
build-backend = "poetry_dynamic_versioning.backend"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "tempit-manager"
|
|
7
|
+
version = "0.0"
|
|
8
|
+
description = "Manage and jump into temporary working directories"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10,<3.14"
|
|
11
|
+
authors = [{ name = "Idir Oura", email = "idir.oura@protonmail.com" }]
|
|
12
|
+
dependencies = [
|
|
13
|
+
"humanize",
|
|
14
|
+
"rich",
|
|
15
|
+
"typer",
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
[project.scripts]
|
|
19
|
+
tempit = "tempit.cli:main"
|
|
20
|
+
|
|
21
|
+
[tool.poetry]
|
|
22
|
+
packages = [{ include = "tempit" }]
|
|
23
|
+
include = [
|
|
24
|
+
{ path = "tempit/shell/init.sh" }
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
[tool.poetry-dynamic-versioning]
|
|
28
|
+
enable = true
|
|
29
|
+
vcs = "git"
|
|
30
|
+
|
|
31
|
+
[tool.poetry.group.dev.dependencies]
|
|
32
|
+
pytest = ">=8.4.2,<9.0.0"
|
|
33
|
+
flake8 = ">=7.3.0,<8.0.0"
|
|
34
|
+
ruff = ">=0.13.0,<0.14.0"
|
|
35
|
+
mypy = ">=1.18.1,<2.0.0"
|
|
36
|
+
pylint = ">=3.3.8,<4.0.0"
|
|
File without changes
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""CLI entry point for the tempit application."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
|
|
5
|
+
import typer
|
|
6
|
+
|
|
7
|
+
from tempit.core import TempitManager
|
|
8
|
+
|
|
9
|
+
app = typer.Typer(add_completion=False, help="CLI for the tempit application.")
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def get_manager() -> TempitManager:
|
|
13
|
+
"""Helper pour initialiser le manager et gérer les erreurs globales."""
|
|
14
|
+
try:
|
|
15
|
+
return TempitManager()
|
|
16
|
+
except (IOError, OSError) as e:
|
|
17
|
+
logging.error("An error occurred: %s", e)
|
|
18
|
+
raise typer.Exit(code=1)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@app.command("create")
|
|
22
|
+
def create_dir(name: str = typer.Argument(..., help="Name of the temporary directory.")):
|
|
23
|
+
"""Create a new temporary directory."""
|
|
24
|
+
typer.echo(get_manager().create(name))
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@app.command("init")
|
|
28
|
+
def init_shell(shell: str = typer.Argument(..., help="Shell name (e.g., bash, zsh).")):
|
|
29
|
+
"""Initialize Tempit in the current shell."""
|
|
30
|
+
get_manager().init_shell(shell)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@app.command("list")
|
|
34
|
+
def list_dirs():
|
|
35
|
+
"""List all tracked temporary directories."""
|
|
36
|
+
get_manager().print_directories()
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@app.command("remove")
|
|
40
|
+
def remove_dir(number: int = typer.Argument(..., help="Number of the directory to remove.")):
|
|
41
|
+
"""Remove a tracked temporary directory by its number."""
|
|
42
|
+
if not get_manager().remove(number):
|
|
43
|
+
raise typer.Exit(code=1)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@app.command("clean-all")
|
|
47
|
+
def clean_all():
|
|
48
|
+
"""Remove all tracked temporary directories."""
|
|
49
|
+
get_manager().clean_all_directories()
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@app.command("path", hidden=True)
|
|
53
|
+
def get_path(number: int):
|
|
54
|
+
"""Get directory path by number."""
|
|
55
|
+
typer.echo(get_manager().get_path_by_number(number))
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def main():
|
|
59
|
+
"""Run the tempit CLI application."""
|
|
60
|
+
logging.basicConfig(level=logging.WARNING, format="%(levelname)s: %(message)s")
|
|
61
|
+
app()
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
if __name__ == "__main__":
|
|
65
|
+
main()
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""Core module for the tempit application."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
from tempit.render import DirectoryRenderer
|
|
7
|
+
from tempit.services import DirectoryService
|
|
8
|
+
from tempit.stats import calculate_stats
|
|
9
|
+
from tempit.storage import DirectoryStorage
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class TempitManager:
|
|
13
|
+
"""Main manager class for temporary directory operations."""
|
|
14
|
+
|
|
15
|
+
def __init__(self, storage_file: Path = Path("/tmp/tempit_dirs.json")):
|
|
16
|
+
"""Initialize the TempitManager with dependency injection."""
|
|
17
|
+
self.logger = logging.getLogger(__name__)
|
|
18
|
+
self.storage = DirectoryStorage(storage_file)
|
|
19
|
+
self.service = DirectoryService()
|
|
20
|
+
self.renderer = DirectoryRenderer()
|
|
21
|
+
|
|
22
|
+
def init_shell(self, shell: str) -> None:
|
|
23
|
+
"""Initialize Tempit in the current shell."""
|
|
24
|
+
if shell in ["bash", "zsh"]:
|
|
25
|
+
init_script_path = Path(__file__).parent / "shell" / "init.sh"
|
|
26
|
+
try:
|
|
27
|
+
with init_script_path.open("r", encoding="utf-8") as f:
|
|
28
|
+
print(f.read())
|
|
29
|
+
except FileNotFoundError:
|
|
30
|
+
self.logger.error("Error reading initialization script: %s", init_script_path)
|
|
31
|
+
else:
|
|
32
|
+
self.logger.error("Unsupported shell: %s", shell)
|
|
33
|
+
|
|
34
|
+
def create(self, prefix: str = "tempit") -> Path:
|
|
35
|
+
"""Create a new temporary directory and track it."""
|
|
36
|
+
try:
|
|
37
|
+
dir_info = self.service.create_temp_directory(prefix)
|
|
38
|
+
self.storage.add_directory(dir_info)
|
|
39
|
+
self.logger.info("Created temporary directory: %s", dir_info.path)
|
|
40
|
+
return dir_info.path
|
|
41
|
+
except (IOError, OSError) as e:
|
|
42
|
+
self.logger.error("Error creating temporary directory: %s", e)
|
|
43
|
+
raise
|
|
44
|
+
|
|
45
|
+
def remove(self, number: int) -> bool:
|
|
46
|
+
"""Remove a tracked temporary directory by its number."""
|
|
47
|
+
try:
|
|
48
|
+
self.storage.prune_stale()
|
|
49
|
+
dir_path = self.storage.get_path_by_number(number)
|
|
50
|
+
if dir_path is None:
|
|
51
|
+
return False
|
|
52
|
+
success = self.service.remove_directory(dir_path)
|
|
53
|
+
if success:
|
|
54
|
+
self.storage.remove_directory(dir_path)
|
|
55
|
+
self.logger.info("Removed temporary directory: %s", dir_path)
|
|
56
|
+
return True
|
|
57
|
+
return False
|
|
58
|
+
except (IOError, OSError) as e:
|
|
59
|
+
self.logger.error("Error removing temporary directory: %s", e)
|
|
60
|
+
return False
|
|
61
|
+
|
|
62
|
+
def print_directories(self) -> None:
|
|
63
|
+
"""Print a formatted table of tracked temporary directories."""
|
|
64
|
+
self.storage.prune_stale()
|
|
65
|
+
directories = self.storage.get_all_directories()
|
|
66
|
+
all_entries = [(d, calculate_stats(d)) for d in directories]
|
|
67
|
+
entries = [(d, s) for d, s in all_entries if s is not None]
|
|
68
|
+
self.renderer.render_directory_list(entries)
|
|
69
|
+
|
|
70
|
+
def get_path_by_number(self, number: int) -> Path | None:
|
|
71
|
+
"""Return the path for a tracked directory by its number."""
|
|
72
|
+
self.storage.prune_stale()
|
|
73
|
+
return self.storage.get_path_by_number(number)
|
|
74
|
+
|
|
75
|
+
def clean_all_directories(self) -> None:
|
|
76
|
+
"""Remove all tracked temporary directories."""
|
|
77
|
+
self.storage.prune_stale()
|
|
78
|
+
directories = self.storage.get_all_directories()
|
|
79
|
+
|
|
80
|
+
if not directories:
|
|
81
|
+
self.logger.warning("No temporary directories found.")
|
|
82
|
+
return
|
|
83
|
+
|
|
84
|
+
removed_count = 0
|
|
85
|
+
for dir_info in directories:
|
|
86
|
+
try:
|
|
87
|
+
if self.service.remove_directory(dir_info.path):
|
|
88
|
+
self.storage.remove_directory(dir_info.path)
|
|
89
|
+
removed_count += 1
|
|
90
|
+
except (IOError, OSError) as e:
|
|
91
|
+
self.logger.error("Error removing directory %s: %s", dir_info.path, e)
|
|
92
|
+
|
|
93
|
+
self.logger.info("Removed %s temporary directories.", removed_count)
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Data models for the tempit application."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import asdict, dataclass
|
|
4
|
+
from datetime import datetime
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any, Dict
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass
|
|
10
|
+
class DirectoryInfo:
|
|
11
|
+
"""Data model for temporary directory information."""
|
|
12
|
+
|
|
13
|
+
path: Path
|
|
14
|
+
created: datetime
|
|
15
|
+
prefix: str = "tempit"
|
|
16
|
+
|
|
17
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
18
|
+
"""Convert to dictionary for JSON serialization."""
|
|
19
|
+
data = asdict(self)
|
|
20
|
+
data["created"] = self.created.isoformat()
|
|
21
|
+
return data
|
|
22
|
+
|
|
23
|
+
@classmethod
|
|
24
|
+
def from_dict(cls, data: Dict[str, Any]) -> "DirectoryInfo":
|
|
25
|
+
"""Create instance from dictionary (JSON deserialization)."""
|
|
26
|
+
data = data.copy()
|
|
27
|
+
data["created"] = datetime.fromisoformat(data["created"])
|
|
28
|
+
data["path"] = Path(data["path"])
|
|
29
|
+
return cls(**data)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass
|
|
33
|
+
class DirectoryStats:
|
|
34
|
+
"""Runtime statistics for a directory (not stored in JSON)."""
|
|
35
|
+
|
|
36
|
+
size_bytes: int
|
|
37
|
+
human_size: str
|
|
38
|
+
file_count: int
|
|
39
|
+
dir_count: int
|
|
40
|
+
age: str
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""Render directory information as a rich table."""
|
|
2
|
+
|
|
3
|
+
import sys
|
|
4
|
+
from typing import List, Tuple
|
|
5
|
+
|
|
6
|
+
from rich.console import Console
|
|
7
|
+
from rich.table import Table
|
|
8
|
+
|
|
9
|
+
from tempit.models import DirectoryInfo, DirectoryStats
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class DirectoryRenderer: # pylint: disable=too-few-public-methods
|
|
13
|
+
"""Renders (DirectoryInfo, DirectoryStats) pairs as a rich table. No external dependencies."""
|
|
14
|
+
|
|
15
|
+
def render_directory_list(
|
|
16
|
+
self,
|
|
17
|
+
entries: List[Tuple[DirectoryInfo, DirectoryStats]],
|
|
18
|
+
title: str = "Temporary Directories",
|
|
19
|
+
) -> None:
|
|
20
|
+
"""Render a list of (info, stats) pairs as a rich table."""
|
|
21
|
+
console = Console(file=sys.stdout, width=None if sys.stdout.isatty() else 220)
|
|
22
|
+
|
|
23
|
+
if not entries:
|
|
24
|
+
console.print("[yellow]No temporary directories found.[/yellow]")
|
|
25
|
+
return
|
|
26
|
+
|
|
27
|
+
table = Table(title=title, show_header=True, header_style="bold white")
|
|
28
|
+
table.add_column("#", justify="center", style="bold white")
|
|
29
|
+
table.add_column("Name", style="bold cyan", no_wrap=True)
|
|
30
|
+
table.add_column("Path")
|
|
31
|
+
table.add_column("Size")
|
|
32
|
+
table.add_column("Created")
|
|
33
|
+
table.add_column("Age")
|
|
34
|
+
table.add_column("Contents")
|
|
35
|
+
|
|
36
|
+
for i, (dir_info, stats) in enumerate(entries):
|
|
37
|
+
table.add_row(*self._create_table_row(dir_info, stats, i))
|
|
38
|
+
|
|
39
|
+
console.print()
|
|
40
|
+
console.print(table)
|
|
41
|
+
console.print()
|
|
42
|
+
|
|
43
|
+
def _create_table_row(
|
|
44
|
+
self,
|
|
45
|
+
dir_info: DirectoryInfo,
|
|
46
|
+
stats: DirectoryStats,
|
|
47
|
+
index: int,
|
|
48
|
+
) -> List[str]:
|
|
49
|
+
created_str = dir_info.created.strftime("%Y-%m-%d %H:%M")
|
|
50
|
+
|
|
51
|
+
if stats.size_bytes > 100 * 1024 * 1024:
|
|
52
|
+
size_markup = f"[red]{stats.human_size}[/red]"
|
|
53
|
+
elif stats.size_bytes > 10 * 1024 * 1024:
|
|
54
|
+
size_markup = f"[yellow]{stats.human_size}[/yellow]"
|
|
55
|
+
else:
|
|
56
|
+
size_markup = f"[green]{stats.human_size}[/green]"
|
|
57
|
+
|
|
58
|
+
if "day" in stats.age or "month" in stats.age or "year" in stats.age:
|
|
59
|
+
age_markup = f"[yellow]{stats.age}[/yellow]"
|
|
60
|
+
else:
|
|
61
|
+
age_markup = f"[green]{stats.age}[/green]"
|
|
62
|
+
|
|
63
|
+
contents = f"[blue]{stats.file_count}[/blue] files, [blue]{stats.dir_count}[/blue] dirs"
|
|
64
|
+
|
|
65
|
+
return [
|
|
66
|
+
str(index + 1),
|
|
67
|
+
dir_info.prefix,
|
|
68
|
+
str(dir_info.path),
|
|
69
|
+
size_markup,
|
|
70
|
+
created_str,
|
|
71
|
+
age_markup,
|
|
72
|
+
contents,
|
|
73
|
+
]
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Service layer for directory operations."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
import shutil
|
|
5
|
+
import tempfile
|
|
6
|
+
from datetime import datetime
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from tempit.models import DirectoryInfo
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class DirectoryService:
|
|
13
|
+
"""Service for directory operations."""
|
|
14
|
+
|
|
15
|
+
def __init__(self, temp_base_dir: Path = Path("/tmp")):
|
|
16
|
+
"""Initialize the directory service."""
|
|
17
|
+
self.temp_base_dir = temp_base_dir
|
|
18
|
+
self.logger = logging.getLogger(__name__)
|
|
19
|
+
|
|
20
|
+
def create_temp_directory(self, prefix: str = "tempit") -> DirectoryInfo:
|
|
21
|
+
"""Create a new temporary directory and return its info."""
|
|
22
|
+
try:
|
|
23
|
+
temp_dir = tempfile.mkdtemp(prefix=f"{prefix}_", dir=self.temp_base_dir)
|
|
24
|
+
|
|
25
|
+
return DirectoryInfo(
|
|
26
|
+
path=Path(temp_dir), created=datetime.now(), prefix=prefix
|
|
27
|
+
)
|
|
28
|
+
except (IOError, OSError) as e:
|
|
29
|
+
self.logger.error("Error creating temporary directory: %s", e)
|
|
30
|
+
raise
|
|
31
|
+
|
|
32
|
+
def remove_directory(self, path: Path) -> bool:
|
|
33
|
+
"""Remove a directory from the filesystem."""
|
|
34
|
+
try:
|
|
35
|
+
if path.exists():
|
|
36
|
+
shutil.rmtree(path)
|
|
37
|
+
self.logger.info("Removed directory: %s", path)
|
|
38
|
+
return True
|
|
39
|
+
self.logger.warning("Directory does not exist: %s", path)
|
|
40
|
+
return False
|
|
41
|
+
except (IOError, OSError) as e:
|
|
42
|
+
self.logger.error("Error removing directory %s: %s", path, e)
|
|
43
|
+
return False
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# shellcheck shell=bash
|
|
2
|
+
__TEMPIT_EXE="$(command -v tempit)"
|
|
3
|
+
|
|
4
|
+
if [[ -z "$__TEMPIT_EXE" ]]; then
|
|
5
|
+
echo "tempit: executable not found in PATH" >&2
|
|
6
|
+
else
|
|
7
|
+
_tempit() {
|
|
8
|
+
case "$1" in
|
|
9
|
+
create|-c)
|
|
10
|
+
shift
|
|
11
|
+
local __path
|
|
12
|
+
__path="$(command "$__TEMPIT_EXE" create "$@")" || return $?
|
|
13
|
+
if [[ -n "$__path" && -d "$__path" ]]; then
|
|
14
|
+
cd "$__path" || return $?
|
|
15
|
+
fi
|
|
16
|
+
;;
|
|
17
|
+
go|-g)
|
|
18
|
+
shift
|
|
19
|
+
local __path
|
|
20
|
+
__path="$(command "$__TEMPIT_EXE" path "$@")" || return $?
|
|
21
|
+
if [[ -n "$__path" && -d "$__path" ]]; then
|
|
22
|
+
cd "$__path" || return $?
|
|
23
|
+
fi
|
|
24
|
+
;;
|
|
25
|
+
*)
|
|
26
|
+
command "$__TEMPIT_EXE" "$@"
|
|
27
|
+
;;
|
|
28
|
+
esac
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
# Aliases
|
|
32
|
+
alias tempc="_tempit create"
|
|
33
|
+
alias tempg="_tempit go"
|
|
34
|
+
alias templ="_tempit list"
|
|
35
|
+
alias temprm="_tempit remove"
|
|
36
|
+
alias tempclean="_tempit clean-all"
|
|
37
|
+
|
|
38
|
+
fi
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Pure stats calculation for directory information."""
|
|
2
|
+
|
|
3
|
+
from datetime import datetime
|
|
4
|
+
|
|
5
|
+
import humanize
|
|
6
|
+
|
|
7
|
+
from tempit.models import DirectoryInfo, DirectoryStats
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def calculate_stats(dir_info: DirectoryInfo) -> DirectoryStats | None:
|
|
11
|
+
"""Calculate stats for a directory. Returns None if the path doesn't exist."""
|
|
12
|
+
dir_path = dir_info.path
|
|
13
|
+
if not dir_path.exists():
|
|
14
|
+
return None
|
|
15
|
+
|
|
16
|
+
all_entries = list(dir_path.rglob("*"))
|
|
17
|
+
files = [f for f in all_entries if f.is_file()]
|
|
18
|
+
dirs = [d for d in all_entries if d.is_dir()]
|
|
19
|
+
total_size = sum(f.stat().st_size for f in files)
|
|
20
|
+
file_count = len(files)
|
|
21
|
+
dir_count = len(dirs)
|
|
22
|
+
|
|
23
|
+
return DirectoryStats(
|
|
24
|
+
size_bytes=total_size,
|
|
25
|
+
human_size=humanize.naturalsize(total_size, binary=True),
|
|
26
|
+
file_count=file_count,
|
|
27
|
+
dir_count=dir_count,
|
|
28
|
+
age=humanize.naturaltime(datetime.now() - dir_info.created),
|
|
29
|
+
)
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Storage layer for persisting directory information in JSON format."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import logging
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import List
|
|
7
|
+
|
|
8
|
+
from tempit.models import DirectoryInfo
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class DirectoryStorage:
|
|
12
|
+
"""Handles JSON-based persistence of directory information."""
|
|
13
|
+
|
|
14
|
+
def __init__(self, storage_file: Path = Path("/tmp/tempit_dirs.json")):
|
|
15
|
+
"""Initialize the storage with a JSON file path."""
|
|
16
|
+
self.storage_file = storage_file
|
|
17
|
+
self.logger = logging.getLogger(__name__)
|
|
18
|
+
self._ensure_storage_file()
|
|
19
|
+
|
|
20
|
+
def _ensure_storage_file(self) -> None:
|
|
21
|
+
"""Ensure the storage file and its parent directory exist."""
|
|
22
|
+
self.storage_file.parent.mkdir(parents=True, exist_ok=True)
|
|
23
|
+
if not self.storage_file.exists():
|
|
24
|
+
self._write_directories([])
|
|
25
|
+
|
|
26
|
+
def _read_directories(self) -> List[DirectoryInfo]:
|
|
27
|
+
"""Read all directories from the JSON storage file."""
|
|
28
|
+
try:
|
|
29
|
+
with open(self.storage_file, "r", encoding="utf-8") as f:
|
|
30
|
+
data = json.load(f)
|
|
31
|
+
return [DirectoryInfo.from_dict(item) for item in data]
|
|
32
|
+
except (FileNotFoundError, json.JSONDecodeError) as e:
|
|
33
|
+
self.logger.warning("Error reading storage file: %s", e)
|
|
34
|
+
return []
|
|
35
|
+
|
|
36
|
+
def _write_directories(self, directories: List[DirectoryInfo]) -> None:
|
|
37
|
+
"""Write all directories to the JSON storage file."""
|
|
38
|
+
try:
|
|
39
|
+
data = [dir_info.to_dict() for dir_info in directories]
|
|
40
|
+
with open(self.storage_file, "w", encoding="utf-8") as f:
|
|
41
|
+
json.dump(data, f, indent=2, default=str)
|
|
42
|
+
except (IOError, TypeError) as e:
|
|
43
|
+
self.logger.error("Error writing to storage file: %s", e)
|
|
44
|
+
raise
|
|
45
|
+
|
|
46
|
+
def add_directory(self, directory_info: DirectoryInfo) -> None:
|
|
47
|
+
"""Add a new directory to storage."""
|
|
48
|
+
directories = self._read_directories()
|
|
49
|
+
directories.append(directory_info)
|
|
50
|
+
self._write_directories(directories)
|
|
51
|
+
|
|
52
|
+
def get_all_directories(self) -> List[DirectoryInfo]:
|
|
53
|
+
"""Read all stored directory entries. Pure read — no side effects."""
|
|
54
|
+
return self._read_directories()
|
|
55
|
+
|
|
56
|
+
def prune_stale(self) -> None:
|
|
57
|
+
"""Remove entries for directories that no longer exist on the filesystem."""
|
|
58
|
+
all_dirs = self._read_directories()
|
|
59
|
+
existing = [d for d in all_dirs if d.path.exists()]
|
|
60
|
+
if len(existing) != len(all_dirs):
|
|
61
|
+
self._write_directories(existing)
|
|
62
|
+
self.logger.info("Pruned %d stale entries.", len(all_dirs) - len(existing))
|
|
63
|
+
|
|
64
|
+
def get_path_by_number(self, number: int) -> Path | None:
|
|
65
|
+
"""Get the path of a tracked directory by its 1-based index."""
|
|
66
|
+
directories = self.get_all_directories()
|
|
67
|
+
if not directories or not 1 <= number <= len(directories):
|
|
68
|
+
self.logger.error("Invalid directory number: %s", number)
|
|
69
|
+
return None
|
|
70
|
+
return directories[number - 1].path
|
|
71
|
+
|
|
72
|
+
def remove_directory(self, path: Path) -> None:
|
|
73
|
+
"""Remove a directory entry from storage by path. Raises on write failure."""
|
|
74
|
+
directories = self._read_directories()
|
|
75
|
+
self._write_directories([d for d in directories if d.path != path])
|