pypathdub 0.2.3__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,24 @@
1
+ This is free and unencumbered software released into the public domain.
2
+
3
+ Anyone is free to copy, modify, publish, use, compile, sell, or
4
+ distribute this software, either in source code form or as a compiled
5
+ binary, for any purpose, commercial or non-commercial, and by any
6
+ means.
7
+
8
+ In jurisdictions that recognize copyright laws, the author or authors
9
+ of this software dedicate any and all copyright interest in the
10
+ software to the public domain. We make this dedication for the benefit
11
+ of the public at large and to the detriment of our heirs and
12
+ successors. We intend this dedication to be an overt act of
13
+ relinquishment in perpetuity of all present and future rights to this
14
+ software under copyright law.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19
+ IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20
+ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22
+ OTHER DEALINGS IN THE SOFTWARE.
23
+
24
+ For more information, please refer to <https://unlicense.org>
@@ -0,0 +1,67 @@
1
+ Metadata-Version: 2.4
2
+ Name: pypathdub
3
+ Version: 0.2.3
4
+ Summary: Project path strings between Windows, WSL, MSYS2/Mingw, and POSIX conventions.
5
+ Author: warrentc3
6
+ License-Expression: Unlicense
7
+ Keywords: path,windows,wsl,msys2,mingw
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Environment :: Console
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3 :: Only
13
+ Classifier: Topic :: Software Development :: Build Tools
14
+ Classifier: Topic :: Utilities
15
+ Requires-Python: >=3.7
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Dynamic: license-file
19
+
20
+ # pypathdub
21
+
22
+ `pypathdub` projects path strings between Windows, WSL, MSYS2/Mingw, and POSIX conventions.
23
+
24
+ It is for the common cross-shell case where the producer shell's path shape is not the shape a consumer binary expects.
25
+
26
+ ```powershell
27
+ pypathdub 'C:\work\project\data.local' --fmt python-wsl
28
+ # /mnt/c/work/project/data.local
29
+
30
+ pypathdub 'C:\work\project\data.local' --fmt python-mingw
31
+ # /c/work/project/data.local
32
+ ```
33
+
34
+ ## Python
35
+
36
+ ```python
37
+ from pypathdub import normalizePathString
38
+
39
+ print(normalizePathString(r"C:\work\project\data.local", "python-mingw"))
40
+ ```
41
+
42
+ `normalize_path_string` is also exported as a Python-style alias.
43
+
44
+ From a source checkout, the compatibility script is:
45
+
46
+ ```powershell
47
+ python .\scripts\normalize_path_string.py 'C:\work\project\data.local' --fmt python-mingw
48
+ ```
49
+
50
+ ## Formats
51
+
52
+ - `python-win`
53
+ - `python-winabsolute`
54
+ - `python-nix`
55
+ - `python-mingw`
56
+ - `python-wsl`
57
+ - `osnative-win`
58
+ - `osnative-winabsolute`
59
+ - `osnative-nix`
60
+ - `osnative-mingw`
61
+ - `osnative-wsl`
62
+
63
+ The `python-*` formats use Python-literal-safe separators. The `osnative-*` formats use the native path style for that convention.
64
+
65
+ Drive-backed Windows paths cannot be projected to plain `nix`; use Mingw or WSL when the drive mount is part of the target convention.
66
+
67
+ The `winabsolute` formats require a Windows drive or UNC authority. Relative paths and plain POSIX absolute paths are rejected instead of resolved against the current working directory.
@@ -0,0 +1,48 @@
1
+ # pypathdub
2
+
3
+ `pypathdub` projects path strings between Windows, WSL, MSYS2/Mingw, and POSIX conventions.
4
+
5
+ It is for the common cross-shell case where the producer shell's path shape is not the shape a consumer binary expects.
6
+
7
+ ```powershell
8
+ pypathdub 'C:\work\project\data.local' --fmt python-wsl
9
+ # /mnt/c/work/project/data.local
10
+
11
+ pypathdub 'C:\work\project\data.local' --fmt python-mingw
12
+ # /c/work/project/data.local
13
+ ```
14
+
15
+ ## Python
16
+
17
+ ```python
18
+ from pypathdub import normalizePathString
19
+
20
+ print(normalizePathString(r"C:\work\project\data.local", "python-mingw"))
21
+ ```
22
+
23
+ `normalize_path_string` is also exported as a Python-style alias.
24
+
25
+ From a source checkout, the compatibility script is:
26
+
27
+ ```powershell
28
+ python .\scripts\normalize_path_string.py 'C:\work\project\data.local' --fmt python-mingw
29
+ ```
30
+
31
+ ## Formats
32
+
33
+ - `python-win`
34
+ - `python-winabsolute`
35
+ - `python-nix`
36
+ - `python-mingw`
37
+ - `python-wsl`
38
+ - `osnative-win`
39
+ - `osnative-winabsolute`
40
+ - `osnative-nix`
41
+ - `osnative-mingw`
42
+ - `osnative-wsl`
43
+
44
+ The `python-*` formats use Python-literal-safe separators. The `osnative-*` formats use the native path style for that convention.
45
+
46
+ Drive-backed Windows paths cannot be projected to plain `nix`; use Mingw or WSL when the drive mount is part of the target convention.
47
+
48
+ The `winabsolute` formats require a Windows drive or UNC authority. Relative paths and plain POSIX absolute paths are rejected instead of resolved against the current working directory.
@@ -0,0 +1,32 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "pypathdub"
7
+ version = "0.2.3"
8
+ description = "Project path strings between Windows, WSL, MSYS2/Mingw, and POSIX conventions."
9
+ readme = "README.md"
10
+ requires-python = ">=3.7"
11
+ license = "Unlicense"
12
+ license-files = ["LICENSE"]
13
+ authors = [
14
+ { name = "warrentc3" }
15
+ ]
16
+ keywords = ["path", "windows", "wsl", "msys2", "mingw"]
17
+ classifiers = [
18
+ "Development Status :: 3 - Alpha",
19
+ "Environment :: Console",
20
+ "Intended Audience :: Developers",
21
+ "Programming Language :: Python :: 3",
22
+ "Programming Language :: Python :: 3 :: Only",
23
+ "Topic :: Software Development :: Build Tools",
24
+ "Topic :: Utilities",
25
+ ]
26
+
27
+ [project.scripts]
28
+ pypathdub = "pypathdub.cli:main"
29
+ normalize-path-string = "pypathdub.cli:main"
30
+
31
+ [tool.setuptools.packages.find]
32
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,10 @@
1
+ import sys
2
+
3
+ if sys.version_info < (3, 7):
4
+ raise RuntimeError(
5
+ f"pypathdub requires Python 3.7+; running {sys.version}"
6
+ )
7
+
8
+ from .core import normalizePathString, normalize_path_string
9
+
10
+ __all__ = ["normalizePathString", "normalize_path_string"]
@@ -0,0 +1,5 @@
1
+ from .cli import main
2
+
3
+
4
+ if __name__ == "__main__":
5
+ raise SystemExit(main())
@@ -0,0 +1,24 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ from typing import List, Optional
5
+
6
+ from .core import FORMATS, normalizePathString
7
+
8
+
9
+ def build_parser() -> argparse.ArgumentParser:
10
+ parser = argparse.ArgumentParser(description="Project a path string into another path convention.")
11
+ parser.add_argument("pathstr", help="path string to project")
12
+ parser.add_argument(
13
+ "--fmt",
14
+ choices=FORMATS,
15
+ default=None,
16
+ help="target format; default is runtime-native and Python-literal-safe",
17
+ )
18
+ return parser
19
+
20
+
21
+ def main(argv: Optional[List[str]] = None) -> int:
22
+ args = build_parser().parse_args(argv)
23
+ print(normalizePathString(args.pathstr, args.fmt))
24
+ return 0
@@ -0,0 +1,168 @@
1
+ from __future__ import annotations
2
+
3
+ import ntpath
4
+ import os
5
+ import platform
6
+ import re
7
+ import shutil
8
+ import subprocess
9
+ from typing import Dict, List, Optional, Tuple
10
+
11
+ __all__ = ["FORMATS", "normalizePathString", "normalize_path_string"]
12
+
13
+ _PYTHON = ("python-win", "python-winabsolute", "python-nix", "python-mingw", "python-wsl")
14
+ _OSNATIVE = ("osnative-win", "osnative-winabsolute", "osnative-nix", "osnative-mingw", "osnative-wsl")
15
+ FORMATS = _PYTHON + _OSNATIVE
16
+ _MINGW_MOUNT_RE = re.compile(r"^/[a-zA-Z]/")
17
+
18
+
19
+ def _split_windows_root(pathstr: str) -> Tuple[str, str, str]:
20
+ drive, tail = ntpath.splitdrive(pathstr)
21
+ root = ""
22
+ if tail.startswith(("\\", "/")):
23
+ root = tail[0]
24
+ tail = tail[1:]
25
+ return drive, root, tail
26
+
27
+
28
+ def _split_posix_root(pathstr: str) -> Tuple[str, str, str]:
29
+ if pathstr.startswith("//") and not pathstr.startswith("///"):
30
+ return "", "//", pathstr[2:]
31
+ if pathstr.startswith("/"):
32
+ return "", "/", pathstr[1:]
33
+ return "", "", pathstr
34
+
35
+
36
+ def _is_wsl() -> bool:
37
+ if platform.system() != "Linux":
38
+ return False
39
+ try:
40
+ with open("/proc/sys/kernel/osrelease", "r", encoding="utf-8") as stream:
41
+ osrelease = stream.read().lower()
42
+ except OSError:
43
+ return False
44
+ return "microsoft" in osrelease or "wsl" in osrelease
45
+
46
+
47
+ def _runtime_convention() -> str:
48
+ if os.environ.get("MSYSTEM"):
49
+ return "mingw"
50
+ if _is_wsl():
51
+ return "wsl"
52
+ return {"Windows": "win", "Linux": "nix", "Darwin": "nix"}.get(platform.system(), "nix")
53
+
54
+
55
+ def _project_unc_to_nix(unc: str, segments: List[str]) -> str:
56
+ anchor = "//" + unc.replace("\\", "/").strip("/")
57
+ if segments:
58
+ return anchor + "/" + "/".join(segments)
59
+ return anchor
60
+
61
+
62
+ def _decompose(pathstr: str, target_convention: Optional[str] = None) -> Dict[str, object]:
63
+ win_drive, _ = ntpath.splitdrive(pathstr)
64
+ if win_drive or "\\" in pathstr:
65
+ drive, root, tail = _split_windows_root(pathstr)
66
+ unc = drive if drive[:2] in ("\\\\", "//") else ""
67
+ segments = [segment for segment in tail.replace("\\", "/").split("/") if segment]
68
+ return {
69
+ "convention": "win",
70
+ "drive": "" if unc else drive.rstrip(":"),
71
+ "unc": unc,
72
+ "absolute": bool(root),
73
+ "segments": segments,
74
+ }
75
+
76
+ _, root, tail = _split_posix_root(pathstr)
77
+ segments = [segment for segment in tail.split("/") if segment]
78
+ if root == "/" and len(segments) >= 2 and segments[0] == "mnt" and len(segments[1]) == 1 and segments[1].isalpha():
79
+ return {
80
+ "convention": "wsl",
81
+ "drive": segments[1],
82
+ "unc": "",
83
+ "absolute": True,
84
+ "segments": segments[2:],
85
+ }
86
+ if (
87
+ root == "/"
88
+ and segments
89
+ and len(segments[0]) == 1
90
+ and segments[0].isalpha()
91
+ and (target_convention in {"win", "winabsolute", "mingw", "wsl"} or _runtime_convention() == "mingw")
92
+ ):
93
+ return {
94
+ "convention": "mingw",
95
+ "drive": segments[0],
96
+ "unc": "",
97
+ "absolute": True,
98
+ "segments": segments[1:],
99
+ }
100
+ return {
101
+ "convention": "nix",
102
+ "drive": "",
103
+ "unc": "",
104
+ "absolute": bool(root),
105
+ "segments": segments,
106
+ }
107
+
108
+
109
+ def _project(parts: Dict[str, object], convention: str, python_safe: bool) -> str:
110
+ segments = parts["segments"]
111
+ assert isinstance(segments, list)
112
+ drive = str(parts["drive"])
113
+ unc = str(parts["unc"])
114
+ absolute = bool(parts["absolute"])
115
+
116
+ if convention in {"win", "winabsolute"}:
117
+ if convention == "winabsolute" and not ((drive and absolute) or unc):
118
+ raise ValueError("cannot project path to winabsolute without a Windows drive or UNC authority")
119
+ separator = "/" if python_safe else "\\"
120
+ if unc:
121
+ anchor = (unc.replace("\\", "/") if python_safe else unc.replace("/", "\\")) + separator
122
+ elif drive:
123
+ anchor = drive + ":" + (separator if absolute else "")
124
+ else:
125
+ anchor = separator if absolute else ""
126
+ return anchor + separator.join(segments)
127
+ if convention == "mingw":
128
+ if unc:
129
+ raise ValueError("cannot project UNC path to mingw convention")
130
+ anchor = ("/" + drive.lower() + "/") if drive else ("/" if absolute else "")
131
+ return anchor + "/".join(segments)
132
+ if convention == "wsl":
133
+ if unc:
134
+ raise ValueError("cannot project UNC path to wsl convention")
135
+ anchor = ("/mnt/" + drive.lower() + "/") if drive else ("/" if absolute else "")
136
+ return anchor + "/".join(segments)
137
+ if drive:
138
+ raise ValueError(
139
+ f"cannot project Windows drive '{drive}:' to nix convention; "
140
+ "use 'python-mingw', 'osnative-mingw', 'python-wsl', or 'osnative-wsl' instead"
141
+ )
142
+ if unc:
143
+ return _project_unc_to_nix(unc, segments)
144
+ return ("/" if absolute else "") + "/".join(segments)
145
+
146
+
147
+ def normalizePathString(pathstr: str, fmt: Optional[str] = None) -> str:
148
+ if fmt is not None and fmt not in FORMATS:
149
+ raise ValueError(f"unknown fmt {fmt!r}; expected None or one of {FORMATS}")
150
+ expanded = os.path.expandvars(os.path.expanduser(pathstr))
151
+ if (
152
+ fmt == "osnative-win"
153
+ and _MINGW_MOUNT_RE.match(expanded)
154
+ and platform.system() == "Windows"
155
+ and shutil.which("cygpath")
156
+ ):
157
+ completed = subprocess.run(["cygpath", "-w", expanded], capture_output=True, text=True)
158
+ if completed.returncode == 0 and completed.stdout.strip():
159
+ return completed.stdout.strip()
160
+ if fmt is None:
161
+ convention, python_safe = _runtime_convention(), True
162
+ else:
163
+ python_safe, convention = fmt.startswith("python-"), fmt.split("-", 1)[1]
164
+ return _project(_decompose(expanded, convention), convention, python_safe)
165
+
166
+
167
+ def normalize_path_string(pathstr: str, fmt: Optional[str] = None) -> str:
168
+ return normalizePathString(pathstr, fmt)
@@ -0,0 +1,67 @@
1
+ Metadata-Version: 2.4
2
+ Name: pypathdub
3
+ Version: 0.2.3
4
+ Summary: Project path strings between Windows, WSL, MSYS2/Mingw, and POSIX conventions.
5
+ Author: warrentc3
6
+ License-Expression: Unlicense
7
+ Keywords: path,windows,wsl,msys2,mingw
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Environment :: Console
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3 :: Only
13
+ Classifier: Topic :: Software Development :: Build Tools
14
+ Classifier: Topic :: Utilities
15
+ Requires-Python: >=3.7
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Dynamic: license-file
19
+
20
+ # pypathdub
21
+
22
+ `pypathdub` projects path strings between Windows, WSL, MSYS2/Mingw, and POSIX conventions.
23
+
24
+ It is for the common cross-shell case where the producer shell's path shape is not the shape a consumer binary expects.
25
+
26
+ ```powershell
27
+ pypathdub 'C:\work\project\data.local' --fmt python-wsl
28
+ # /mnt/c/work/project/data.local
29
+
30
+ pypathdub 'C:\work\project\data.local' --fmt python-mingw
31
+ # /c/work/project/data.local
32
+ ```
33
+
34
+ ## Python
35
+
36
+ ```python
37
+ from pypathdub import normalizePathString
38
+
39
+ print(normalizePathString(r"C:\work\project\data.local", "python-mingw"))
40
+ ```
41
+
42
+ `normalize_path_string` is also exported as a Python-style alias.
43
+
44
+ From a source checkout, the compatibility script is:
45
+
46
+ ```powershell
47
+ python .\scripts\normalize_path_string.py 'C:\work\project\data.local' --fmt python-mingw
48
+ ```
49
+
50
+ ## Formats
51
+
52
+ - `python-win`
53
+ - `python-winabsolute`
54
+ - `python-nix`
55
+ - `python-mingw`
56
+ - `python-wsl`
57
+ - `osnative-win`
58
+ - `osnative-winabsolute`
59
+ - `osnative-nix`
60
+ - `osnative-mingw`
61
+ - `osnative-wsl`
62
+
63
+ The `python-*` formats use Python-literal-safe separators. The `osnative-*` formats use the native path style for that convention.
64
+
65
+ Drive-backed Windows paths cannot be projected to plain `nix`; use Mingw or WSL when the drive mount is part of the target convention.
66
+
67
+ The `winabsolute` formats require a Windows drive or UNC authority. Relative paths and plain POSIX absolute paths are rejected instead of resolved against the current working directory.
@@ -0,0 +1,13 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/pypathdub/__init__.py
5
+ src/pypathdub/__main__.py
6
+ src/pypathdub/cli.py
7
+ src/pypathdub/core.py
8
+ src/pypathdub.egg-info/PKG-INFO
9
+ src/pypathdub.egg-info/SOURCES.txt
10
+ src/pypathdub.egg-info/dependency_links.txt
11
+ src/pypathdub.egg-info/entry_points.txt
12
+ src/pypathdub.egg-info/top_level.txt
13
+ tests/test_normalize_path_string.py
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ normalize-path-string = pypathdub.cli:main
3
+ pypathdub = pypathdub.cli:main
@@ -0,0 +1 @@
1
+ pypathdub
@@ -0,0 +1,88 @@
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+ import unittest
5
+ from importlib.util import module_from_spec, spec_from_file_location
6
+ from pathlib import Path
7
+ from unittest import mock
8
+
9
+
10
+ ROOT = Path(__file__).resolve().parents[1]
11
+ sys.path.insert(0, str(ROOT / "src"))
12
+
13
+ from pypathdub import normalizePathString, normalize_path_string # noqa: E402
14
+
15
+
16
+ class NormalizePathStringTests(unittest.TestCase):
17
+ def test_package_guard_rejects_unsupported_python(self) -> None:
18
+ spec = spec_from_file_location("pypathdub_py36_guard_probe", ROOT / "src" / "pypathdub" / "__init__.py")
19
+ assert spec is not None
20
+ assert spec.loader is not None
21
+ module = module_from_spec(spec)
22
+ with mock.patch.object(sys, "version_info", (3, 6, 0)):
23
+ with self.assertRaisesRegex(RuntimeError, "requires Python 3.7\\+"):
24
+ spec.loader.exec_module(module)
25
+
26
+ def test_windows_drive_projects_to_wsl(self) -> None:
27
+ self.assertEqual(
28
+ "/mnt/c/work/project/data.local",
29
+ normalizePathString(r"C:\work\project\data.local", "python-wsl"),
30
+ )
31
+
32
+ def test_windows_drive_projects_to_lowercase_mingw_drive(self) -> None:
33
+ self.assertEqual(
34
+ "/c/work/project/data.local",
35
+ normalizePathString(r"C:\work\project\data.local", "python-mingw"),
36
+ )
37
+
38
+ def test_mingw_drive_projects_to_python_win(self) -> None:
39
+ self.assertEqual(
40
+ "c:/work/project/data.local",
41
+ normalizePathString("/c/work/project/data.local", "python-win"),
42
+ )
43
+
44
+ def test_wsl_drive_projects_to_osnative_win(self) -> None:
45
+ self.assertEqual(
46
+ r"c:\work\project\data.local",
47
+ normalizePathString("/mnt/c/work/project/data.local", "osnative-win"),
48
+ )
49
+
50
+ def test_wsl_drive_projects_to_python_winabsolute(self) -> None:
51
+ self.assertEqual(
52
+ "c:/work/project/data.local",
53
+ normalizePathString("/mnt/c/work/project/data.local", "python-winabsolute"),
54
+ )
55
+
56
+ def test_unc_share_projects_to_python_nix_authority(self) -> None:
57
+ self.assertEqual(
58
+ "//192.168.1.2/digitalmedia",
59
+ normalizePathString(r"\\192.168.1.2\digitalmedia", "python-nix"),
60
+ )
61
+
62
+ def test_unc_nested_path_projects_to_python_nix_authority(self) -> None:
63
+ self.assertEqual(
64
+ "//192.168.1.2/digitalmedia/movies",
65
+ normalizePathString(r"\\192.168.1.2\digitalmedia\movies", "python-nix"),
66
+ )
67
+
68
+ def test_relative_path_cannot_project_to_winabsolute(self) -> None:
69
+ with self.assertRaises(ValueError):
70
+ normalizePathString(r"work\project\data.local", "python-winabsolute")
71
+
72
+ def test_plain_posix_path_cannot_project_to_winabsolute(self) -> None:
73
+ with self.assertRaises(ValueError):
74
+ normalizePathString("/work/project/data.local", "python-winabsolute")
75
+
76
+ def test_windows_drive_cannot_project_to_nix(self) -> None:
77
+ with self.assertRaises(ValueError):
78
+ normalizePathString(r"C:\work\project\data.local", "python-nix")
79
+
80
+ def test_python_style_alias(self) -> None:
81
+ self.assertEqual(
82
+ "/c/work/project/data.local",
83
+ normalize_path_string(r"C:\work\project\data.local", "python-mingw"),
84
+ )
85
+
86
+
87
+ if __name__ == "__main__":
88
+ unittest.main()