fpm-cli 0.3.0__tar.gz → 0.4.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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fpm-cli
3
- Version: 0.3.0
3
+ Version: 0.4.0
4
4
  Summary: Fast Package Manager for Python — binary distribution
5
5
  Author: Kartikey Yadav
6
6
  License: MIT
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fpm-cli
3
- Version: 0.3.0
3
+ Version: 0.4.0
4
4
  Summary: Fast Package Manager for Python — binary distribution
5
5
  Author: Kartikey Yadav
6
6
  License: MIT
@@ -5,4 +5,5 @@ fpm_cli.egg-info/SOURCES.txt
5
5
  fpm_cli.egg-info/dependency_links.txt
6
6
  fpm_cli.egg-info/entry_points.txt
7
7
  fpm_cli.egg-info/top_level.txt
8
- fpm_pkg/__init__.py
8
+ fpm_pkg/__init__.py
9
+ tests/test_wrapper.py
@@ -0,0 +1,156 @@
1
+ """fpm-cli: Fast Package Manager for Python — binary wrapper.
2
+
3
+ On first run this downloads the fpm release that matches this package's version,
4
+ verifies its SHA256 against the release's checksums.txt, and caches the native
5
+ binary. All arguments are then passed through to it.
6
+
7
+ Environment:
8
+ FPM_RELEASE_BASE_URL mirror of <base>/v<version>/<asset> (default: GitHub releases)
9
+ """
10
+
11
+ import hashlib
12
+ import io
13
+ import os
14
+ import platform
15
+ import stat
16
+ import sys
17
+ import tarfile
18
+ import tempfile
19
+ import urllib.request
20
+ import zipfile
21
+
22
+ __version__ = "0.4.0" # stamped from the git tag at publish time
23
+
24
+ REPO = "Kartikey2011yadav/fpm"
25
+ GUARD_ENV = "FPM_PIP_WRAPPER_ACTIVE"
26
+
27
+
28
+ def get_platform():
29
+ system = platform.system().lower()
30
+ machine = platform.machine().lower()
31
+ if system not in ("darwin", "linux", "windows"):
32
+ raise RuntimeError(f"Unsupported OS: {system}")
33
+ if machine in ("x86_64", "amd64"):
34
+ arch = "amd64"
35
+ elif machine in ("aarch64", "arm64"):
36
+ arch = "arm64"
37
+ else:
38
+ raise RuntimeError(f"Unsupported architecture: {machine}")
39
+ return system, arch
40
+
41
+
42
+ def asset_name(version, os_name, arch):
43
+ ext = "zip" if os_name == "windows" else "tar.gz"
44
+ return f"fpm-{version}-{os_name}-{arch}.{ext}"
45
+
46
+
47
+ def base_url():
48
+ return os.environ.get("FPM_RELEASE_BASE_URL", f"https://github.com/{REPO}/releases/download").rstrip("/")
49
+
50
+
51
+ def binary_dirs():
52
+ """Candidate cache dirs, most preferred first. Never the scripts dir: the
53
+ console script is also called `fpm`, so using it would recurse forever."""
54
+ dirs = [os.path.join(os.path.dirname(os.path.abspath(__file__)), "bin")]
55
+ if platform.system() == "Windows":
56
+ root = os.environ.get("LOCALAPPDATA") or os.path.expanduser("~")
57
+ elif platform.system() == "Darwin":
58
+ root = os.path.expanduser("~/Library/Caches")
59
+ else:
60
+ root = os.environ.get("XDG_CACHE_HOME") or os.path.expanduser("~/.cache")
61
+ dirs.append(os.path.join(root, "fpm-cli", __version__))
62
+ return dirs
63
+
64
+
65
+ def binary_name():
66
+ return "fpm.exe" if platform.system() == "Windows" else "fpm"
67
+
68
+
69
+ def _http_get(url):
70
+ req = urllib.request.Request(url, headers={"User-Agent": "fpm-cli"})
71
+ with urllib.request.urlopen(req, timeout=120) as resp:
72
+ return resp.read()
73
+
74
+
75
+ def parse_checksum(text, asset):
76
+ for line in text.splitlines():
77
+ parts = line.split()
78
+ if len(parts) == 2 and parts[1].lstrip("*") == asset:
79
+ return parts[0].lower()
80
+ raise RuntimeError(f"no checksum listed for {asset}")
81
+
82
+
83
+ def extract_binary(data, asset, name):
84
+ """Return the bytes of `name` from the archive (matched by base name only)."""
85
+ if asset.endswith(".zip"):
86
+ with zipfile.ZipFile(io.BytesIO(data)) as zf:
87
+ for member in zf.namelist():
88
+ if os.path.basename(member) == name:
89
+ return zf.read(member)
90
+ else:
91
+ with tarfile.open(fileobj=io.BytesIO(data), mode="r:gz") as tf:
92
+ for member in tf.getmembers():
93
+ if member.isfile() and os.path.basename(member.name) == name:
94
+ return tf.extractfile(member).read()
95
+ raise RuntimeError(f"{name} not found in {asset}")
96
+
97
+
98
+ def download_binary(version=None):
99
+ version = version or __version__
100
+ os_name, arch = get_platform()
101
+ asset = asset_name(version, os_name, arch)
102
+ base = f"{base_url()}/v{version}"
103
+ print(f"Downloading fpm {version} ({asset})...", file=sys.stderr)
104
+
105
+ data = _http_get(f"{base}/{asset}")
106
+ want = parse_checksum(_http_get(f"{base}/checksums.txt").decode(), asset)
107
+ got = hashlib.sha256(data).hexdigest()
108
+ if got != want:
109
+ raise RuntimeError(f"checksum mismatch for {asset}: expected {want}, got {got}")
110
+ binary = extract_binary(data, asset, binary_name())
111
+
112
+ last_err = None
113
+ for d in binary_dirs():
114
+ try:
115
+ os.makedirs(d, exist_ok=True)
116
+ fd, tmp = tempfile.mkstemp(dir=d, prefix=".fpm-")
117
+ with os.fdopen(fd, "wb") as f:
118
+ f.write(binary)
119
+ os.chmod(tmp, os.stat(tmp).st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
120
+ dest = os.path.join(d, binary_name())
121
+ os.replace(tmp, dest)
122
+ return dest
123
+ except OSError as e:
124
+ last_err = e
125
+ raise RuntimeError(f"cannot store the fpm binary: {last_err}")
126
+
127
+
128
+ def find_binary():
129
+ for d in binary_dirs():
130
+ p = os.path.join(d, binary_name())
131
+ if os.path.isfile(p) and os.access(p, os.X_OK):
132
+ return p
133
+ return download_binary()
134
+
135
+
136
+ def main():
137
+ if os.environ.get(GUARD_ENV):
138
+ print("fpm-cli: refusing to start recursively (wrapper re-entered itself)", file=sys.stderr)
139
+ sys.exit(1)
140
+ try:
141
+ binary = find_binary()
142
+ except Exception as e: # network, checksum, unsupported platform
143
+ print(f"fpm-cli: could not obtain the fpm binary: {e}", file=sys.stderr)
144
+ print(f"Install manually: https://github.com/{REPO}#installation", file=sys.stderr)
145
+ sys.exit(1)
146
+
147
+ os.environ[GUARD_ENV] = "1"
148
+ if platform.system() == "Windows":
149
+ import subprocess
150
+
151
+ sys.exit(subprocess.run([binary] + sys.argv[1:]).returncode)
152
+ os.execv(binary, [binary] + sys.argv[1:])
153
+
154
+
155
+ if __name__ == "__main__":
156
+ main()
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "fpm-cli"
7
- version = "0.3.0"
7
+ version = "0.4.0"
8
8
  description = "Fast Package Manager for Python — binary distribution"
9
9
  readme = "README.md"
10
10
  license = {text = "MIT"}
@@ -0,0 +1,135 @@
1
+ import hashlib
2
+ import http.server
3
+ import io
4
+ import os
5
+ import subprocess
6
+ import sys
7
+ import tarfile
8
+ import tempfile
9
+ import threading
10
+ import unittest
11
+
12
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
13
+ import fpm_pkg # noqa: E402
14
+
15
+ VERSION = "9.9.9"
16
+
17
+
18
+ def fake_release(binary_body: bytes, bad_checksum=False):
19
+ os_name, arch = fpm_pkg.get_platform()
20
+ asset = fpm_pkg.asset_name(VERSION, os_name, arch)
21
+ buf = io.BytesIO()
22
+ with tarfile.open(fileobj=buf, mode="w:gz") as tf:
23
+ info = tarfile.TarInfo("fpm")
24
+ info.size = len(binary_body)
25
+ info.mode = 0o755
26
+ tf.addfile(info, io.BytesIO(binary_body))
27
+ archive = buf.getvalue()
28
+ digest = "0" * 64 if bad_checksum else hashlib.sha256(archive).hexdigest()
29
+ return {
30
+ f"/v{VERSION}/{asset}": archive,
31
+ f"/v{VERSION}/checksums.txt": f"{digest} {asset}\n".encode(),
32
+ }
33
+
34
+
35
+ class Server:
36
+ def __init__(self, files):
37
+ class H(http.server.BaseHTTPRequestHandler):
38
+ def do_GET(self):
39
+ body = files.get(self.path)
40
+ if body is None:
41
+ self.send_response(404); self.end_headers(); return
42
+ self.send_response(200); self.end_headers(); self.wfile.write(body)
43
+
44
+ def log_message(self, *a):
45
+ pass
46
+
47
+ self.httpd = http.server.HTTPServer(("127.0.0.1", 0), H)
48
+ self.url = f"http://127.0.0.1:{self.httpd.server_port}"
49
+ threading.Thread(target=self.httpd.serve_forever, daemon=True).start()
50
+
51
+ def close(self):
52
+ self.httpd.shutdown()
53
+ self.httpd.server_close()
54
+
55
+
56
+ @unittest.skipIf(sys.platform == "win32", "shell-script fake binary")
57
+ class WrapperTest(unittest.TestCase):
58
+ def setUp(self):
59
+ self.tmp = tempfile.mkdtemp()
60
+ self.cache = os.path.join(self.tmp, "cache")
61
+ self.env = dict(os.environ, XDG_CACHE_HOME=self.cache, HOME=self.tmp)
62
+ self.env.pop(fpm_pkg.GUARD_ENV, None)
63
+
64
+ def run_wrapper(self, base_url, *args):
65
+ code = (
66
+ "import sys, fpm_pkg; fpm_pkg.__version__ = %r; "
67
+ "fpm_pkg.binary_dirs = lambda: [%r]; sys.argv = ['fpm'] + %r; fpm_pkg.main()"
68
+ % (VERSION, os.path.join(self.cache, "bin"), list(args))
69
+ )
70
+ env = dict(self.env, FPM_RELEASE_BASE_URL=base_url, PYTHONPATH=os.path.join(os.path.dirname(__file__), ".."))
71
+ return subprocess.run([sys.executable, "-c", code], env=env, capture_output=True, text=True, timeout=30)
72
+
73
+ def test_downloads_verifies_and_execs_without_recursion(self):
74
+ srv = Server(fake_release(b"#!/bin/sh\necho fake-fpm \"$@\"\n"))
75
+ try:
76
+ r = self.run_wrapper(srv.url, "version", "--x")
77
+ finally:
78
+ srv.close()
79
+ self.assertEqual(r.returncode, 0, r.stderr)
80
+ self.assertEqual(r.stdout.strip(), "fake-fpm version --x")
81
+
82
+ def test_second_run_uses_cache_without_network(self):
83
+ srv = Server(fake_release(b"#!/bin/sh\necho cached\n"))
84
+ try:
85
+ self.assertEqual(self.run_wrapper(srv.url).returncode, 0)
86
+ finally:
87
+ srv.close()
88
+ r = self.run_wrapper("http://127.0.0.1:1") # server gone
89
+ self.assertEqual(r.returncode, 0, r.stderr)
90
+ self.assertEqual(r.stdout.strip(), "cached")
91
+
92
+ def test_checksum_mismatch_refuses(self):
93
+ srv = Server(fake_release(b"#!/bin/sh\necho evil\n", bad_checksum=True))
94
+ try:
95
+ r = self.run_wrapper(srv.url)
96
+ finally:
97
+ srv.close()
98
+ self.assertNotEqual(r.returncode, 0)
99
+ self.assertIn("checksum mismatch", r.stderr)
100
+ self.assertNotIn("evil", r.stdout)
101
+ self.assertFalse(os.path.exists(os.path.join(self.cache, "bin", "fpm")))
102
+
103
+ def test_reentry_guard(self):
104
+ self.env[fpm_pkg.GUARD_ENV] = "1"
105
+ r = self.run_wrapper("http://127.0.0.1:1")
106
+ self.assertNotEqual(r.returncode, 0)
107
+ self.assertIn("recursively", r.stderr)
108
+
109
+ def test_download_failure_is_clean(self):
110
+ srv = Server({})
111
+ try:
112
+ r = self.run_wrapper(srv.url)
113
+ finally:
114
+ srv.close()
115
+ self.assertEqual(r.returncode, 1)
116
+ self.assertIn("could not obtain the fpm binary", r.stderr)
117
+
118
+ def test_binary_dirs_never_include_scripts_dir(self):
119
+ scripts = os.path.dirname(sys.executable)
120
+ self.assertNotIn(scripts, fpm_pkg.binary_dirs())
121
+
122
+
123
+ class UnitTest(unittest.TestCase):
124
+ def test_asset_name(self):
125
+ self.assertEqual(fpm_pkg.asset_name("1.2.3", "linux", "amd64"), "fpm-1.2.3-linux-amd64.tar.gz")
126
+ self.assertEqual(fpm_pkg.asset_name("1.2.3", "windows", "arm64"), "fpm-1.2.3-windows-arm64.zip")
127
+
128
+ def test_parse_checksum(self):
129
+ self.assertEqual(fpm_pkg.parse_checksum("AB a.tar.gz\ncd b.zip\n", "b.zip"), "cd")
130
+ with self.assertRaises(RuntimeError):
131
+ fpm_pkg.parse_checksum("ab a.tar.gz\n", "missing")
132
+
133
+
134
+ if __name__ == "__main__":
135
+ unittest.main()
@@ -1,129 +0,0 @@
1
- """fpm-cli: Fast Package Manager for Python — binary wrapper.
2
-
3
- This package downloads and installs the fpm binary for your platform.
4
- After installation, the `fpm` command is available in your PATH.
5
- """
6
-
7
- import os
8
- import platform
9
- import shutil
10
- import stat
11
- import subprocess
12
- import sys
13
- import tempfile
14
- import urllib.request
15
-
16
- __version__ = "0.3.0"
17
-
18
- REPO = "Kartikey2011yadav/fpm"
19
- GITHUB_API = f"https://api.github.com/repos/{REPO}/releases/latest"
20
-
21
-
22
- def get_platform():
23
- """Detect OS and architecture."""
24
- system = platform.system().lower()
25
- machine = platform.machine().lower()
26
-
27
- if system == "darwin":
28
- os_name = "darwin"
29
- elif system == "linux":
30
- os_name = "linux"
31
- elif system == "windows":
32
- os_name = "windows"
33
- else:
34
- raise RuntimeError(f"Unsupported OS: {system}")
35
-
36
- if machine in ("x86_64", "amd64"):
37
- arch = "amd64"
38
- elif machine in ("aarch64", "arm64"):
39
- arch = "arm64"
40
- else:
41
- raise RuntimeError(f"Unsupported architecture: {machine}")
42
-
43
- return os_name, arch
44
-
45
-
46
- def get_binary_path():
47
- """Get the path where the fpm binary should be installed."""
48
- # Install next to this Python package's scripts
49
- scripts_dir = os.path.dirname(sys.executable)
50
-
51
- # On Unix, use the bin dir alongside python
52
- if platform.system() != "Windows":
53
- return os.path.join(scripts_dir, "fpm")
54
- else:
55
- return os.path.join(scripts_dir, "fpm.exe")
56
-
57
-
58
- def get_download_url(version=None):
59
- """Construct the download URL for the platform binary."""
60
- os_name, arch = get_platform()
61
-
62
- if version is None:
63
- # Try to get latest from GitHub API
64
- try:
65
- import json
66
- with urllib.request.urlopen(GITHUB_API, timeout=10) as resp:
67
- data = json.loads(resp.read())
68
- version = data["tag_name"].lstrip("v")
69
- except Exception:
70
- version = __version__
71
-
72
- ext = ".exe" if os_name == "windows" else ""
73
- filename = f"fpm-{version}-{os_name}-{arch}{ext}"
74
- url = f"https://github.com/{REPO}/releases/download/v{version}/{filename}"
75
- return url, filename
76
-
77
-
78
- def download_binary():
79
- """Download the fpm binary for this platform."""
80
- url, filename = get_download_url()
81
- binary_path = get_binary_path()
82
-
83
- print(f"Downloading fpm from {url}...")
84
-
85
- try:
86
- tmp = tempfile.NamedTemporaryFile(delete=False, suffix=filename)
87
- urllib.request.urlretrieve(url, tmp.name)
88
-
89
- # Make executable
90
- os.chmod(tmp.name, os.stat(tmp.name).st_mode | stat.S_IEXEC | stat.S_IXGRP | stat.S_IXOTH)
91
-
92
- # Move to final location
93
- os.makedirs(os.path.dirname(binary_path), exist_ok=True)
94
- shutil.move(tmp.name, binary_path)
95
-
96
- print(f"Installed fpm to {binary_path}")
97
- return binary_path
98
-
99
- except Exception as e:
100
- print(f"Failed to download fpm: {e}", file=sys.stderr)
101
- print("Try installing manually: https://github.com/Kartikey2011yadav/fpm#installation", file=sys.stderr)
102
- sys.exit(1)
103
-
104
-
105
- def find_binary():
106
- """Find the fpm binary, downloading if necessary."""
107
- # Check if already installed alongside this package
108
- binary_path = get_binary_path()
109
- if os.path.isfile(binary_path) and os.access(binary_path, os.X_OK):
110
- return binary_path
111
-
112
- # Check PATH
113
- which = shutil.which("fpm")
114
- if which:
115
- return which
116
-
117
- # Download it
118
- return download_binary()
119
-
120
-
121
- def main():
122
- """Entry point: proxy all arguments to the fpm binary."""
123
- binary = find_binary()
124
- result = subprocess.run([binary] + sys.argv[1:])
125
- sys.exit(result.returncode)
126
-
127
-
128
- if __name__ == "__main__":
129
- main()
File without changes
File without changes