scitex-path 0.1.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.
@@ -0,0 +1,295 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ # Timestamp: "2025-09-16 15:11:33 (ywatanabe)"
4
+ # File: scitex-path/src/scitex_path/_symlink.py
5
+ # ----------------------------------------
6
+ from __future__ import annotations
7
+
8
+ import os
9
+
10
+ __FILE__ = __file__
11
+ __DIR__ = os.path.dirname(__FILE__)
12
+ # ----------------------------------------
13
+
14
+ """Symlink creation and management utilities."""
15
+
16
+ import logging
17
+ from pathlib import Path
18
+ from typing import Optional, Union
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+
23
+ def symlink(
24
+ src: Union[str, Path],
25
+ dst: Union[str, Path],
26
+ overwrite: bool = False,
27
+ target_is_directory: Optional[bool] = None,
28
+ relative: bool = False,
29
+ ) -> Path:
30
+ """
31
+ Create a symbolic link pointing to src named dst.
32
+
33
+ Args:
34
+ src: Source path (target of the symlink)
35
+ dst: Destination path (the symlink to create)
36
+ overwrite: If True, remove existing dst before creating symlink
37
+ target_is_directory: On Windows, specify if target is directory (auto-detected if None)
38
+ relative: If True, create relative symlink instead of absolute
39
+
40
+ Returns:
41
+ Path object of the created symlink
42
+
43
+ Raises:
44
+ FileExistsError: If dst exists and overwrite=False
45
+ FileNotFoundError: If src doesn't exist
46
+ OSError: If symlink creation fails
47
+
48
+ Examples:
49
+ >>> from scitex_path import symlink
50
+ >>> # Create absolute symlink
51
+ >>> symlink("/path/to/source", "/path/to/link")
52
+
53
+ >>> # Create relative symlink
54
+ >>> symlink("../source", "link", relative=True)
55
+
56
+ >>> # Overwrite existing symlink
57
+ >>> symlink("/path/to/new_source", "/path/to/link", overwrite=True)
58
+ """
59
+ src_path = Path(src)
60
+ dst_path = Path(dst)
61
+
62
+ # Note: We allow creating symlinks to non-existent targets
63
+ # This is valid in Unix/Linux and useful for testing
64
+
65
+ # Handle existing destination
66
+ if dst_path.exists() or dst_path.is_symlink():
67
+ if not overwrite:
68
+ raise FileExistsError(f"Destination already exists: {dst_path}")
69
+ else:
70
+ # Remove existing file/symlink
71
+ if dst_path.is_symlink():
72
+ dst_path.unlink()
73
+ elif dst_path.is_file():
74
+ dst_path.unlink()
75
+ elif dst_path.is_dir():
76
+ import shutil
77
+
78
+ shutil.rmtree(dst_path)
79
+
80
+ # Create parent directory if needed
81
+ dst_path.parent.mkdir(parents=True, exist_ok=True)
82
+
83
+ # Determine if target is directory (for Windows)
84
+ if target_is_directory is None and src_path.exists():
85
+ target_is_directory = src_path.is_dir()
86
+
87
+ # Create symlink
88
+ try:
89
+ if relative:
90
+ # Calculate relative path from dst to src
91
+ if src_path.is_absolute():
92
+ # src is absolute, calculate relative from dst
93
+ try:
94
+ rel_path = os.path.relpath(src_path, dst_path.parent)
95
+ src_for_link = Path(rel_path)
96
+ except ValueError:
97
+ # Can't create relative path (e.g., different drives on Windows)
98
+ logger.warning(
99
+ f"Cannot create relative path from {dst_path} to {src_path}, using absolute"
100
+ )
101
+ src_for_link = src_path.absolute()
102
+ else:
103
+ # Both paths are relative, need to resolve them first
104
+ # to calculate the correct relative path
105
+ src_abs = src_path.resolve()
106
+ dst_parent_abs = dst_path.parent.resolve()
107
+ try:
108
+ rel_path = os.path.relpath(src_abs, dst_parent_abs)
109
+ src_for_link = Path(rel_path)
110
+ except ValueError:
111
+ # Can't create relative path
112
+ logger.warning(
113
+ f"Cannot create relative path from {dst_path} to {src_path}"
114
+ )
115
+ src_for_link = src_path
116
+ else:
117
+ src_for_link = src_path.absolute()
118
+
119
+ dst_path.symlink_to(src_for_link, target_is_directory=target_is_directory)
120
+ logger.info(f"Created symlink: {dst_path} -> {src_for_link}")
121
+
122
+ except OSError as e:
123
+ logger.warning(
124
+ f"Failed to create symlink from {dst_path} to {src_for_link}: {str(e)}"
125
+ )
126
+
127
+ return dst_path
128
+
129
+
130
+ def is_symlink(path: Union[str, Path]) -> bool:
131
+ """
132
+ Check if a path is a symbolic link.
133
+
134
+ Args:
135
+ path: Path to check
136
+
137
+ Returns:
138
+ True if path is a symlink, False otherwise
139
+ """
140
+ return Path(path).is_symlink()
141
+
142
+
143
+ def readlink(path: Union[str, Path]) -> Path:
144
+ """
145
+ Return the path to which the symbolic link points.
146
+
147
+ Args:
148
+ path: Symlink path to read
149
+
150
+ Returns:
151
+ Path object pointing to the symlink target
152
+
153
+ Raises:
154
+ OSError: If path is not a symlink
155
+ """
156
+ path = Path(path)
157
+ if not path.is_symlink():
158
+ raise OSError(f"Path is not a symbolic link: {path}")
159
+
160
+ return Path(os.readlink(path))
161
+
162
+
163
+ def resolve_symlinks(path: Union[str, Path]) -> Path:
164
+ """
165
+ Resolve all symbolic links in a path.
166
+
167
+ Args:
168
+ path: Path potentially containing symlinks
169
+
170
+ Returns:
171
+ Fully resolved absolute path
172
+ """
173
+ return Path(path).resolve()
174
+
175
+
176
+ def create_relative_symlink(
177
+ src: Union[str, Path], dst: Union[str, Path], overwrite: bool = False
178
+ ) -> Path:
179
+ """
180
+ Create a relative symbolic link.
181
+
182
+ This is a convenience wrapper around symlink() with relative=True.
183
+
184
+ Args:
185
+ src: Source path (target of the symlink)
186
+ dst: Destination path (the symlink to create)
187
+ overwrite: If True, remove existing dst before creating symlink
188
+
189
+ Returns:
190
+ Path object of the created symlink
191
+ """
192
+ return symlink(src, dst, overwrite=overwrite, relative=True)
193
+
194
+
195
+ def unlink_symlink(path: Union[str, Path], missing_ok: bool = True) -> None:
196
+ """
197
+ Remove a symbolic link.
198
+
199
+ Args:
200
+ path: Symlink to remove
201
+ missing_ok: If True, don't raise error if symlink doesn't exist
202
+
203
+ Raises:
204
+ FileNotFoundError: If symlink doesn't exist and missing_ok=False
205
+ OSError: If path is not a symlink
206
+ """
207
+ path = Path(path)
208
+
209
+ if not path.exists() and not path.is_symlink():
210
+ if missing_ok:
211
+ return
212
+ raise FileNotFoundError(f"Symlink does not exist: {path}")
213
+
214
+ if not path.is_symlink():
215
+ raise OSError(f"Path is not a symbolic link: {path}")
216
+
217
+ path.unlink()
218
+
219
+
220
+ def list_symlinks(directory: Union[str, Path], recursive: bool = False) -> list[Path]:
221
+ """
222
+ List all symbolic links in a directory.
223
+
224
+ Args:
225
+ directory: Directory to search
226
+ recursive: If True, search recursively
227
+
228
+ Returns:
229
+ List of Path objects for all symlinks found
230
+ """
231
+ directory = Path(directory)
232
+ symlinks = []
233
+
234
+ if recursive:
235
+ for path in directory.rglob("*"):
236
+ if path.is_symlink():
237
+ symlinks.append(path)
238
+ else:
239
+ for path in directory.iterdir():
240
+ if path.is_symlink():
241
+ symlinks.append(path)
242
+
243
+ return symlinks
244
+
245
+
246
+ def fix_broken_symlinks(
247
+ directory: Union[str, Path],
248
+ recursive: bool = False,
249
+ remove: bool = False,
250
+ new_target: Optional[Union[str, Path]] = None,
251
+ ) -> dict:
252
+ """
253
+ Find and optionally fix broken symbolic links.
254
+
255
+ Args:
256
+ directory: Directory to search
257
+ recursive: If True, search recursively
258
+ remove: If True, remove broken symlinks
259
+ new_target: If provided, repoint broken symlinks to this target
260
+
261
+ Returns:
262
+ Dictionary with 'found', 'fixed', and 'removed' lists of paths
263
+ """
264
+ directory = Path(directory)
265
+ result = {"found": [], "fixed": [], "removed": []}
266
+
267
+ symlinks = list_symlinks(directory, recursive=recursive)
268
+
269
+ for link in symlinks:
270
+ try:
271
+ # Check if target exists
272
+ target = Path(os.readlink(link))
273
+ if not link.parent.joinpath(target).exists() and not target.is_absolute():
274
+ # Relative link with non-existent target
275
+ result["found"].append(link)
276
+ elif target.is_absolute() and not target.exists():
277
+ # Absolute link with non-existent target
278
+ result["found"].append(link)
279
+ except (OSError, ValueError):
280
+ result["found"].append(link)
281
+
282
+ # Fix or remove broken symlinks
283
+ for link in result["found"]:
284
+ if remove:
285
+ link.unlink()
286
+ result["removed"].append(link)
287
+ elif new_target:
288
+ link.unlink()
289
+ symlink(new_target, link)
290
+ result["fixed"].append(link)
291
+
292
+ return result
293
+
294
+
295
+ # EOF
@@ -0,0 +1,33 @@
1
+ #!/usr/bin/env python3
2
+ # Timestamp: "2026-01-08 02:00:00 (ywatanabe)"
3
+ # File: /home/ywatanabe/proj/scitex-code/src/scitex/path/_this_path.py
4
+
5
+ """Get current file path utilities."""
6
+
7
+ import inspect
8
+ from pathlib import Path
9
+
10
+
11
+ def this_path(ipython_fake_path: str = "/tmp/fake.py") -> Path:
12
+ """Get the path of the calling script.
13
+
14
+ Parameters
15
+ ----------
16
+ ipython_fake_path : str
17
+ Fake path to return when running in IPython.
18
+
19
+ Returns
20
+ -------
21
+ Path
22
+ Path to the calling script.
23
+ """
24
+ caller_file = inspect.stack()[1].filename
25
+ if "ipython" in caller_file.lower():
26
+ return Path(ipython_fake_path)
27
+ return Path(caller_file)
28
+
29
+
30
+ get_this_path = this_path
31
+
32
+
33
+ # EOF
@@ -0,0 +1,108 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ # Time-stamp: "2024-11-02 20:48:24 (ywatanabe)"
4
+ # File: scitex-path/src/scitex_path/_version.py
5
+
6
+ import os
7
+ import re
8
+ from glob import glob
9
+
10
+
11
+ def find_latest(dirname, fname, ext, version_prefix="_v"):
12
+ """Find the latest versioned file in a directory.
13
+
14
+ Parameters
15
+ ----------
16
+ dirname : str
17
+ Directory to search in.
18
+ fname : str
19
+ Base filename without version number or extension.
20
+ ext : str
21
+ File extension including the dot (e.g., '.txt').
22
+ version_prefix : str, optional
23
+ Prefix before the version number. Default is '_v'.
24
+
25
+ Returns
26
+ -------
27
+ str or None
28
+ Path to the latest versioned file, or None if not found.
29
+ """
30
+ version_pattern = re.compile(
31
+ rf"({re.escape(fname)}{re.escape(version_prefix)})(\d+)({re.escape(ext)})$"
32
+ )
33
+
34
+ glob_pattern = os.path.join(dirname, f"{fname}{version_prefix}*{ext}")
35
+ files = glob(glob_pattern)
36
+
37
+ highest_version = 0
38
+ latest_file = None
39
+
40
+ for file in files:
41
+ filename = os.path.basename(file)
42
+ match = version_pattern.search(filename)
43
+ if match:
44
+ version_num = int(match.group(2))
45
+ if version_num > highest_version:
46
+ highest_version = version_num
47
+ latest_file = file
48
+
49
+ return latest_file
50
+
51
+
52
+ def increment_version(dirname, fname, ext, version_prefix="_v"):
53
+ """Generate the next version of a filename based on existing versioned files.
54
+
55
+ Parameters
56
+ ----------
57
+ dirname : str
58
+ Directory to search in.
59
+ fname : str
60
+ Base filename without version number or extension.
61
+ ext : str
62
+ File extension including the dot (e.g., '.txt').
63
+ version_prefix : str, optional
64
+ Prefix before the version number. Default is '_v'.
65
+
66
+ Returns
67
+ -------
68
+ str
69
+ Full path for the next version of the file.
70
+
71
+ Example
72
+ -------
73
+ >>> increment_version('/path/to/dir', 'myfile', '.txt')
74
+ '/path/to/dir/myfile_v001.txt'
75
+ """
76
+ version_pattern = re.compile(
77
+ rf"({re.escape(fname)}{re.escape(version_prefix)})(\d+)({re.escape(ext)})$"
78
+ )
79
+
80
+ glob_pattern = os.path.join(dirname, f"{fname}{version_prefix}*{ext}")
81
+ files = glob(glob_pattern)
82
+
83
+ highest_version = 0
84
+ base, suffix = None, None
85
+
86
+ for file in files:
87
+ filename = os.path.basename(file)
88
+ match = version_pattern.search(filename)
89
+ if match:
90
+ base, version_str, suffix = match.groups()
91
+ version_num = int(version_str)
92
+ if version_num > highest_version:
93
+ highest_version = version_num
94
+
95
+ if base is None or suffix is None:
96
+ base = f"{fname}{version_prefix}"
97
+ suffix = ext
98
+ highest_version = 0
99
+
100
+ next_version_number = highest_version + 1
101
+ next_version_str = f"{base}{next_version_number:03d}{suffix}"
102
+
103
+ next_filepath = os.path.join(dirname, next_version_str)
104
+
105
+ return next_filepath
106
+
107
+
108
+ # EOF
@@ -0,0 +1,83 @@
1
+ Metadata-Version: 2.4
2
+ Name: scitex-path
3
+ Version: 0.1.0
4
+ Summary: Scientific project path utilities (find, split, symlink, versioning)
5
+ Project-URL: Homepage, https://github.com/ywatanabe1989/scitex-path
6
+ Project-URL: Repository, https://github.com/ywatanabe1989/scitex-path
7
+ Project-URL: Issues, https://github.com/ywatanabe1989/scitex-path/issues
8
+ Author: Yusuke Watanabe
9
+ License-Expression: AGPL-3.0-or-later
10
+ License-File: LICENSE
11
+ Keywords: path,science,symlink,utilities,versioning
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
22
+ Requires-Python: >=3.10
23
+ Description-Content-Type: text/markdown
24
+
25
+ # scitex-path
26
+
27
+ Scientific project path utilities for the [SciTeX](https://github.com/ywatanabe1989/scitex-python) ecosystem.
28
+
29
+ Provides file/directory finding, path splitting, symlink management, and version incrementing.
30
+
31
+ ## Installation
32
+
33
+ ```bash
34
+ pip install scitex-path
35
+ ```
36
+
37
+ ## Usage
38
+
39
+ ```python
40
+ import scitex_path as sp
41
+
42
+ # Find files by pattern
43
+ matches = sp.find_file("*.csv", root="/data/project")
44
+
45
+ # Find the nearest git root
46
+ git_root = sp.find_git_root()
47
+
48
+ # Split path into components
49
+ parts = sp.split("/home/user/project/data/results.csv")
50
+
51
+ # Symlink management
52
+ sp.symlink("/data/raw", "/project/data/raw")
53
+ sp.list_symlinks("/project/data")
54
+ sp.fix_broken_symlinks("/project/data")
55
+
56
+ # Version incrementing
57
+ next_ver = sp.increment_version("v1.2.3", part="patch") # "v1.2.4"
58
+ latest = sp.find_latest("/results/experiment_v*")
59
+ ```
60
+
61
+ ## API
62
+
63
+ | Function | Description |
64
+ |---|---|
65
+ | `find_file` | Find files matching a glob pattern |
66
+ | `find_dir` | Find directories matching a glob pattern |
67
+ | `find_git_root` | Locate the nearest `.git` root |
68
+ | `split` | Split a path into structured components |
69
+ | `symlink` | Create a symlink |
70
+ | `create_relative_symlink` | Create a relative symlink |
71
+ | `list_symlinks` | List symlinks under a directory |
72
+ | `fix_broken_symlinks` | Remove or report broken symlinks |
73
+ | `resolve_symlinks` | Resolve all symlinks to real paths |
74
+ | `increment_version` | Bump a version string |
75
+ | `find_latest` | Find the latest versioned path |
76
+ | `clean` | Clean/normalize a path |
77
+ | `getsize` | Get file/directory size |
78
+ | `get_spath` / `mk_spath` | Session path helpers |
79
+ | `this_path` / `get_this_path` | Get the path of the calling script |
80
+
81
+ ## License
82
+
83
+ AGPL-3.0 -- see [LICENSE](LICENSE) for details.
@@ -0,0 +1,18 @@
1
+ scitex_path/__init__.py,sha256=gn97oixag5WpuWBZmNP8x3gj6OIBX4rKO83jCJYuMHM,1189
2
+ scitex_path/_clean.py,sha256=EUnkXWgyqy3k5IUBsB-3vYd4z0m1MpDvVnSZynakFDM,1472
3
+ scitex_path/_find.py,sha256=X8NkBPrhjJOUNyytAvYKZ-pdNF6SjGyPFDkFVz3q198,2164
4
+ scitex_path/_get_module_path.py,sha256=ewiyEsr2ry7U1iKEdSYz8Mna0GP4oU72N0WVZzSIOMc,1393
5
+ scitex_path/_get_spath.py,sha256=5Vj6iRNUxJlwTvyxkFrXZyhaL0ozncqI7pCpWKaoBYw,306
6
+ scitex_path/_getsize.py,sha256=N0YBR-fCt8I0Fhg4HJqzPRxp9mN9dn8Owj2fJKvXBhk,596
7
+ scitex_path/_increment_version.py,sha256=TXTo_UMRBMD_CZIgDcCk5dryemEkw48g8WWJ0GO2xC4,2283
8
+ scitex_path/_mk_spath.py,sha256=gxWT7NVqv0bCd-ERYVux7hpEjeGV8MImQdBnS8EQebA,1170
9
+ scitex_path/_path.py,sha256=q-cuCGZslub_Ra4XtMed3aLrNBmI_2YFBdmZUBkb8sk,299
10
+ scitex_path/_split.py,sha256=Ktc-sqRSPExL0As_zKplH1f_MEx_5Tz5VpY-8URQZ7I,847
11
+ scitex_path/_symlink.py,sha256=muacwuiE3C3zsNpCQA2pYW3UVYUjKahavDuROszBlYQ,8696
12
+ scitex_path/_this_path.py,sha256=zybHwJXVRnMdEP-fDrMDRDXgZsQtA1KrkGcN7Ckxbe8,712
13
+ scitex_path/_version.py,sha256=XCsRZcmIy-kOfYKATVH7DAO_bex0KmICRxhavVW07pI,2976
14
+ scitex_path-0.1.0.dist-info/METADATA,sha256=5AzIBVSVWZF6HNxFGYxeW44TGATKaDsONBitCqQaFrw,2825
15
+ scitex_path-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
16
+ scitex_path-0.1.0.dist-info/entry_points.txt,sha256=wA141ljdBsYbkGIjo7aMxpaFYMiPdKfm2amhMquWJnU,44
17
+ scitex_path-0.1.0.dist-info/licenses/LICENSE,sha256=DZak_2itbUtvHzD3E7GNUYSRK6jdOJ-GqncQ2weavLA,34523
18
+ scitex_path-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [scitex_dev.docs]
2
+ scitex-path = scitex_path