tempit-manager 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.
@@ -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,76 @@
1
+ Metadata-Version: 2.3
2
+ Name: tempit-manager
3
+ Version: 0.1.0
4
+ Summary: Manage and jump into temporary working directories
5
+ Author: Idir Oura
6
+ Author-email: idir.oura@protonmail.com
7
+ Requires-Python: >=3.10,<3.14
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Programming Language :: Python :: 3.10
10
+ Classifier: Programming Language :: Python :: 3.11
11
+ Classifier: Programming Language :: Python :: 3.12
12
+ Classifier: Programming Language :: Python :: 3.13
13
+ Requires-Dist: flake8 (>=7.3.0,<8.0.0)
14
+ Requires-Dist: humanize
15
+ Requires-Dist: mypy (>=1.18.1,<2.0.0)
16
+ Requires-Dist: pylint (>=3.3.8,<4.0.0)
17
+ Requires-Dist: pytest (>=8.4.2,<9.0.0)
18
+ Requires-Dist: ruff (>=0.13.0,<0.14.0)
19
+ Requires-Dist: tabulate
20
+ Requires-Dist: termcolor
21
+ Description-Content-Type: text/markdown
22
+
23
+ # Tempit - Temporary Directory Manager
24
+
25
+ Tempit is a command-line utility and shell helper that lets you create, track, and jump to temporary directories without losing them.
26
+ ## Features
27
+
28
+ - Create temporary directories with optional prefixes.
29
+ - List tracked directories with size, creation time, age, and file counts.
30
+ - Jump to a directory by its number.
31
+ - Remove individual directories or clean them all.
32
+ - Works via shell integration.
33
+
34
+ ## Installation
35
+
36
+ ### Using pip
37
+
38
+ ```bash
39
+ pip install tempit
40
+ ```
41
+
42
+ ### Shell integration
43
+
44
+ Add the following line to your shell startup file (`~/.bashrc` or `~/.zshrc`):
45
+
46
+ ```bash
47
+ # Bash
48
+ eval "$(tempit --init bash)"
49
+
50
+ # Zsh
51
+ eval "$(tempit --init zsh)"
52
+ ```
53
+
54
+ ## Usage
55
+
56
+ ### CLI commands
57
+
58
+ ```bash
59
+ tempit --create [prefix]
60
+ tempit --list
61
+ tempit --remove <number>
62
+ tempit --clean-all
63
+ ```
64
+
65
+ ### Aliases (after shell init)
66
+
67
+ | Alias | Description |
68
+ |-------|-------------|
69
+ | `tempc [prefix]` | Create a new temporary directory and cd into it |
70
+ | `tempg <number>` | Change into the directory by its number |
71
+ | `templ` | List tracked temporary directories |
72
+
73
+ ## License
74
+
75
+ [MIT](LICENSE)
76
+
@@ -0,0 +1,53 @@
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
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
+ ```
42
+
43
+ ### Aliases (after shell init)
44
+
45
+ | Alias | Description |
46
+ |-------|-------------|
47
+ | `tempc [prefix]` | Create a new temporary directory and cd into it |
48
+ | `tempg <number>` | Change into the directory by its number |
49
+ | `templ` | List tracked temporary directories |
50
+
51
+ ## License
52
+
53
+ [MIT](LICENSE)
@@ -0,0 +1,30 @@
1
+ [build-system]
2
+ requires = ["poetry-core>=2.0.0"]
3
+ build-backend = "poetry.core.masonry.api"
4
+
5
+ [project]
6
+ name = "tempit-manager"
7
+ version = "0.1.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
+ "tabulate",
15
+ "termcolor",
16
+ "pytest (>=8.4.2,<9.0.0)",
17
+ "flake8 (>=7.3.0,<8.0.0)",
18
+ "ruff (>=0.13.0,<0.14.0)",
19
+ "mypy (>=1.18.1,<2.0.0)",
20
+ "pylint (>=3.3.8,<4.0.0)"
21
+ ]
22
+
23
+ [project.scripts]
24
+ tempit = "tempit.cli:main"
25
+
26
+ [tool.poetry]
27
+ packages = [{ include = "tempit" }]
28
+ include = [
29
+ { path = "tempit/shell/init.sh" }
30
+ ]
File without changes
@@ -0,0 +1,60 @@
1
+ #!/usr/bin/env python3
2
+
3
+ """CLI module for the tempit application."""
4
+
5
+ import argparse
6
+ import logging
7
+ import sys
8
+
9
+ from tempit.core import TempitManager
10
+
11
+
12
+ def main() -> int:
13
+ """Main CLI entry point for the Tempit application."""
14
+ # Set up basic logging
15
+ logging.basicConfig(level=logging.WARNING, format="%(levelname)s: %(message)s")
16
+
17
+ parser = argparse.ArgumentParser(description="Manage temporary directories.")
18
+ parser.add_argument("-c", "--create", nargs="?", const="tempit",
19
+ help="Create a new temporary directory.")
20
+ parser.add_argument("-init", "--init", type=str,
21
+ help="Initialize Tempit in the current shell.")
22
+ parser.add_argument("-l", "--list", action="store_true",
23
+ help="List all tracked temporary directories.")
24
+ parser.add_argument("-rm", "--remove", type=int,
25
+ help="Remove a tracked temporary directory by its number.")
26
+ parser.add_argument("--clean-all", action="store_true",
27
+ help="Remove all tracked temporary directories.")
28
+ parser.add_argument("-v", "--verbose", action="store_true",
29
+ help="Enable verbose logging.")
30
+ args = parser.parse_args()
31
+
32
+ # Adjust logging level if verbose
33
+ if args.verbose:
34
+ logging.getLogger().setLevel(logging.INFO)
35
+
36
+ try:
37
+ manager = TempitManager()
38
+
39
+ if args.init:
40
+ manager.init_shell(args.init)
41
+ elif args.create:
42
+ print(manager.create(args.create))
43
+ elif args.list:
44
+ manager.print_directories()
45
+ elif args.remove:
46
+ success = manager.remove(args.remove)
47
+ if not success:
48
+ return 1
49
+ elif args.clean_all:
50
+ manager.clean_all_directories()
51
+ else:
52
+ parser.print_help()
53
+ except (IOError, OSError) as e:
54
+ logging.error("An error occurred: %s", e)
55
+ return 1
56
+ return 0
57
+
58
+
59
+ if __name__ == "__main__":
60
+ sys.exit(main())
@@ -0,0 +1,89 @@
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.storage import DirectoryStorage
9
+
10
+
11
+ class TempitManager:
12
+ """Main manager class for temporary directory operations."""
13
+
14
+ def __init__(self, storage_file: Path = Path("/tmp/tempit_dirs.json")):
15
+ """Initialize the TempitManager with dependency injection."""
16
+ self.logger = logging.getLogger(__name__)
17
+
18
+ self.storage = DirectoryStorage(storage_file)
19
+ self.service = DirectoryService(storage_file.parent)
20
+ self.renderer = DirectoryRenderer(self.storage, self.service)
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
+
40
+ self.logger.info("Created temporary directory: %s", dir_info.path)
41
+ return dir_info.path
42
+
43
+ except (IOError, OSError) as e:
44
+ self.logger.error("Error creating temporary directory: %s", e)
45
+ raise
46
+
47
+ def remove(self, number: int) -> bool:
48
+ """Remove a tracked temporary directory by its number."""
49
+
50
+ try:
51
+ dir_path = self.storage.get_path_by_number(number)
52
+ if dir_path is None:
53
+ return False
54
+
55
+ success = self.service.remove_directory(dir_path)
56
+
57
+ if success:
58
+ self.storage.remove_directory(dir_path)
59
+ self.logger.info("Removed temporary directory: %s", dir_path)
60
+ return True
61
+ return False
62
+
63
+ except (IOError, OSError) as e:
64
+ self.logger.error("Error removing temporary directory: %s", e)
65
+ return False
66
+
67
+ def print_directories(self) -> None:
68
+ """Print a formatted table of tracked temporary directories."""
69
+ directories = self.storage.get_existing_directories()
70
+ self.renderer.render_directory_list(directories)
71
+
72
+ def clean_all_directories(self) -> None:
73
+ """Remove all tracked temporary directories."""
74
+ directories = self.storage.get_existing_directories()
75
+
76
+ if not directories:
77
+ self.logger.warning("No temporary directories found.")
78
+ return
79
+
80
+ removed_count = 0
81
+ for dir_info in directories:
82
+ try:
83
+ if self.service.remove_directory(dir_info.path):
84
+ removed_count += 1
85
+ except (IOError, OSError) as e:
86
+ self.logger.error("Error removing directory %s: %s", dir_info.path, e)
87
+
88
+ self.storage.clear_all()
89
+ 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,188 @@
1
+ """Render directory information from JSON storage."""
2
+
3
+ # mypy: disable-error-code="arg-type"
4
+ import datetime
5
+ from typing import List, Optional
6
+
7
+ import humanize
8
+ from tabulate import tabulate # type: ignore[import-untyped]
9
+ from termcolor import colored
10
+
11
+ from tempit.models import DirectoryInfo, DirectoryStats
12
+ from tempit.services import DirectoryService
13
+ from tempit.storage import DirectoryStorage
14
+
15
+
16
+ class DirectoryRenderer:
17
+ """Handles rendering of directory information from JSON storage."""
18
+
19
+ def __init__(self, storage: DirectoryStorage, service: DirectoryService):
20
+ """Initialize the renderer with storage and service dependencies."""
21
+ self.storage = storage
22
+ self.service = service
23
+
24
+ def get_headers(self) -> List[str]:
25
+ """Return formatted table headers for directory listings."""
26
+ return [
27
+ colored("#", "white", attrs=["bold"]),
28
+ colored("Name", "white", attrs=["bold"]),
29
+ colored("Path", "white", attrs=["bold"]),
30
+ colored("Size", "white", attrs=["bold"]),
31
+ colored("Created", "white", attrs=["bold"]),
32
+ colored("Age", "white", attrs=["bold"]),
33
+ colored("Contents", "white", attrs=["bold"]),
34
+ ]
35
+
36
+ def render_directory_list(
37
+ self, directories: List[DirectoryInfo], title: str = "Temporary Directories"
38
+ ) -> None:
39
+ """Render all directories from JSON storage."""
40
+
41
+ if not directories:
42
+ print(colored("No temporary directories found.", "yellow"))
43
+ return
44
+
45
+ table_data = []
46
+ for i, dir_info in enumerate(directories):
47
+ stats = self.service.calculate_directory_stats(dir_info)
48
+ if not stats:
49
+ continue
50
+ friendly_name = dir_info.prefix
51
+ row = self._create_table_row(dir_info, stats, i, friendly_name)
52
+ table_data.append(row)
53
+
54
+ self._print_table(table_data, self.get_headers(), title)
55
+
56
+ def _create_table_row(
57
+ self,
58
+ dir_info: DirectoryInfo,
59
+ stats: DirectoryStats,
60
+ index: int,
61
+ friendly_name: str,
62
+ ) -> List[str]:
63
+ """Create a formatted table row from directory info and stats."""
64
+ # Format creation date
65
+ created_str = dir_info.created.strftime("%Y-%m-%d %H:%M")
66
+
67
+ # Name column with color
68
+ name = colored(friendly_name, "cyan", attrs=["bold"])
69
+
70
+ # Size with color thresholds
71
+ size_color = "green"
72
+ if stats.size_bytes > 10 * 1024 * 1024: # > 10MB
73
+ size_color = "yellow"
74
+ if stats.size_bytes > 100 * 1024 * 1024: # > 100MB
75
+ size_color = "red"
76
+ human_size = colored(stats.human_size, size_color)
77
+
78
+ # Age with color
79
+ age_color = "green"
80
+ if "day" in stats.age or "month" in stats.age or "year" in stats.age:
81
+ age_color = "yellow"
82
+ colored_age = colored(stats.age, age_color)
83
+
84
+ # Contents info
85
+ contents_info = (
86
+ f"{colored(stats.file_count, 'blue')} files, "
87
+ f"{colored(stats.dir_count, 'blue')} dirs"
88
+ )
89
+
90
+ return [
91
+ colored(str(index + 1), "white", attrs=["bold"]),
92
+ name,
93
+ str(dir_info.path),
94
+ human_size,
95
+ created_str,
96
+ colored_age,
97
+ contents_info,
98
+ ]
99
+
100
+ def _print_table(
101
+ self, rows: List[List[str]], hdrs: List[str], title: Optional[str] = None
102
+ ) -> None:
103
+ """Print a nicely formatted table."""
104
+ if title:
105
+ print()
106
+ print(colored(title, "white", attrs=["bold"]))
107
+ print(
108
+ tabulate(
109
+ rows,
110
+ headers=hdrs,
111
+ tablefmt="rounded_grid",
112
+ numalign="center",
113
+ )
114
+ )
115
+ print()
116
+
117
+
118
+ # Legacy functions for backward compatibility
119
+ def headers() -> List[str]:
120
+ """Return formatted table headers for directory listings."""
121
+ return [
122
+ colored("#", "white", attrs=["bold"]),
123
+ colored("Name", "white", attrs=["bold"]),
124
+ colored("Path", "white", attrs=["bold"]),
125
+ colored("Size", "white", attrs=["bold"]),
126
+ colored("Created", "white", attrs=["bold"]),
127
+ colored("Age", "white", attrs=["bold"]),
128
+ colored("Contents", "white", attrs=["bold"]),
129
+ ]
130
+
131
+
132
+ def row_from_info(info: dict, index: int, friendly_name: str) -> List[str]:
133
+ """Create a formatted row from directory info (legacy function).
134
+
135
+ Expected keys in info: path, human_size, created (datetime), file_count, dir_count, size
136
+ """
137
+ created: datetime.datetime = info["created"]
138
+ created_str = created.strftime("%Y-%m-%d %H:%M")
139
+
140
+ # Name column
141
+ name = colored(friendly_name, "cyan", attrs=["bold"])
142
+
143
+ # Size with color thresholds
144
+ size_color = "green"
145
+ if info["size"] > 10 * 1024 * 1024: # > 10MB
146
+ size_color = "yellow"
147
+ if info["size"] > 100 * 1024 * 1024: # > 100MB
148
+ size_color = "red"
149
+ human_size = colored(info["human_size"], size_color) # type: ignore[arg-type]
150
+
151
+ # Age
152
+ age = humanize.naturaltime(datetime.datetime.now() - created)
153
+ age_color = "green"
154
+ if "day" in age or "month" in age or "year" in age:
155
+ age_color = "yellow"
156
+ colored_age = colored(age, age_color) # type: ignore[arg-type]
157
+
158
+ # Contents
159
+ contents_info = (
160
+ f"{colored(info['file_count'], 'blue')} files, "
161
+ f"{colored(info['dir_count'], 'blue')} dirs"
162
+ )
163
+
164
+ return [
165
+ colored(str(index + 1), "white", attrs=["bold"]),
166
+ name,
167
+ info["path"],
168
+ human_size,
169
+ created_str,
170
+ colored_age,
171
+ contents_info,
172
+ ]
173
+
174
+
175
+ def print_table(rows: List[List[str]], hdrs: List[str], title: Optional[str] = None) -> None:
176
+ """Print a nicely formatted table of directories."""
177
+ if title:
178
+ print()
179
+ print(colored(title, "white", attrs=["bold"]))
180
+ print(
181
+ tabulate(
182
+ rows,
183
+ headers=hdrs,
184
+ tablefmt="rounded_grid",
185
+ numalign="center",
186
+ )
187
+ )
188
+ print()
@@ -0,0 +1,84 @@
1
+ """Service layer for directory operations and statistics."""
2
+
3
+ import logging
4
+ import shutil
5
+ import tempfile
6
+ from datetime import datetime
7
+ from pathlib import Path
8
+ from typing import Tuple
9
+
10
+ import humanize
11
+
12
+ from tempit.models import DirectoryInfo, DirectoryStats
13
+
14
+
15
+ class DirectoryService:
16
+ """Service for directory operations and statistics calculation."""
17
+
18
+ def __init__(self, temp_base_dir: Path = Path("/tmp")):
19
+ """Initialize the directory service."""
20
+ self.temp_base_dir = temp_base_dir
21
+ self.logger = logging.getLogger(__name__)
22
+
23
+ def create_temp_directory(self, prefix: str = "tempit") -> DirectoryInfo:
24
+ """Create a new temporary directory and return its info."""
25
+ try:
26
+ temp_dir = tempfile.mkdtemp(prefix=f"{prefix}_", dir=self.temp_base_dir)
27
+
28
+ return DirectoryInfo(
29
+ path=Path(temp_dir), created=datetime.now(), prefix=prefix
30
+ )
31
+ except (IOError, OSError) as e:
32
+ self.logger.error("Error creating temporary directory: %s", e)
33
+ raise
34
+
35
+ def remove_directory(self, path: Path) -> bool:
36
+ """Remove a directory from the filesystem."""
37
+ try:
38
+ if path.exists():
39
+ shutil.rmtree(path)
40
+ self.logger.info("Removed directory: %s", path)
41
+ return True
42
+ self.logger.warning("Directory does not exist: %s", path)
43
+ return False
44
+ except (IOError, OSError) as e:
45
+ self.logger.error("Error removing directory %s: %s", path, e)
46
+ return False
47
+
48
+ def calculate_directory_stats(self, directory_info: DirectoryInfo) -> DirectoryStats | None:
49
+ """Calculate runtime statistics for a directory."""
50
+ dir_path: Path = directory_info.path
51
+ if not dir_path.exists():
52
+ self.logger.warning("Directory does not exist: %s", dir_path)
53
+ return None
54
+
55
+ # Calculate size
56
+ total_size = self._get_directory_size(dir_path)
57
+ human_size = humanize.naturalsize(total_size, binary=True)
58
+
59
+ # Count files and directories
60
+ file_count, dir_count = self._count_directory_contents(dir_path)
61
+
62
+ # Calculate age
63
+ creation_time = directory_info.created
64
+ age = humanize.naturaltime(datetime.now() - creation_time)
65
+
66
+ return DirectoryStats(
67
+ size_bytes=total_size,
68
+ human_size=human_size,
69
+ file_count=file_count,
70
+ dir_count=dir_count,
71
+ age=age,
72
+ )
73
+
74
+ @staticmethod
75
+ def _get_directory_size(directory: Path) -> int:
76
+ """Get the total size of a directory in bytes."""
77
+ return sum(f.stat().st_size for f in directory.rglob("*") if f.is_file())
78
+
79
+ @staticmethod
80
+ def _count_directory_contents(directory: Path) -> Tuple[int, int]:
81
+ """Count files and subdirectories in a directory."""
82
+ files = sum(1 for f in directory.rglob("*") if f.is_file())
83
+ dirs = sum(1 for d in directory.rglob("*") if d.is_dir())
84
+ return files, dirs
@@ -0,0 +1,40 @@
1
+ __TEMPIT_EXE="$(command -v tempit)"
2
+
3
+ if [[ -z "$__TEMPIT_EXE" ]]; then
4
+ echo "tempit: executable not found in PATH" >&2
5
+ else
6
+ _tempit() {
7
+ # Allow `tempit init zsh` to work even after the function is defined.
8
+ if [[ "$1" == "init" ]]; then
9
+ command "$__TEMPIT_EXE" "$@"
10
+ return $?
11
+ fi
12
+ case "$1" in
13
+ create|-c)
14
+ shift
15
+ local __path
16
+ __path="$(command "$__TEMPIT_EXE" --create "$@")" || return $?
17
+ if [[ -n "$__path" && -d "$__path" ]]; then
18
+ cd "$__path"
19
+ fi
20
+ ;;
21
+ go|-g)
22
+ shift
23
+ local __path
24
+ __path="$(command "$__TEMPIT_EXE" --get "$@")" || return $?
25
+ if [[ -n "$__path" && -d "$__path" ]]; then
26
+ cd "$__path"
27
+ fi
28
+ ;;
29
+ *)
30
+ command "$__TEMPIT_EXE" "$@"
31
+ ;;
32
+ esac
33
+ }
34
+
35
+ # Aliases
36
+ alias tempc="_tempit create"
37
+ alias tempg="_tempit go"
38
+ alias templ="$__TEMPIT_EXE --list"
39
+
40
+ fi
@@ -0,0 +1,89 @@
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_existing_directories(self) -> List[DirectoryInfo]:
53
+ """Get only directories that still exist on the filesystem."""
54
+ all_dirs = self._read_directories()
55
+ existing_dirs = [d for d in all_dirs if d.path.exists()]
56
+
57
+ # Update storage if some directories no longer exist
58
+ if len(existing_dirs) != len(all_dirs):
59
+ self._write_directories(existing_dirs)
60
+ self.logger.info("Refreshed directories list.")
61
+
62
+ return existing_dirs
63
+
64
+ def get_path_by_number(self, number: int) -> Path | None:
65
+ """Get the path of a tracked temporary directory by its number."""
66
+ directories = self.get_existing_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) -> bool:
73
+ """Remove a directory from storage by path."""
74
+ directories = self._read_directories()
75
+ directories = [d for d in directories if d.path != path]
76
+ self._write_directories(directories)
77
+ return True
78
+
79
+ def find_directory_by_path(self, path: Path) -> DirectoryInfo | None:
80
+ """Find a directory by its path."""
81
+ directories = self._read_directories()
82
+ for directory in directories:
83
+ if directory.path == path:
84
+ return directory
85
+ return None
86
+
87
+ def clear_all(self) -> None:
88
+ """Remove all directories from storage."""
89
+ self._write_directories([])