ast-metrics 0.41.1__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) 2024 Jean-François Lépine
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,142 @@
1
+ Metadata-Version: 2.4
2
+ Name: ast-metrics
3
+ Version: 0.41.1
4
+ Summary: AST Metrics bridge for Python: multi-language maintainability metrics, installable with pip and runnable with pipx
5
+ Author-email: Jean-François Lépine <lepinejeanfrancois@gmail.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://ast-metrics.dev
8
+ Project-URL: Repository, https://github.com/ast-metrics/ast-metrics-bridge-python
9
+ Project-URL: Issues, https://github.com/ast-metrics/ast-metrics-bridge-python/issues
10
+ Project-URL: Analyzer, https://github.com/ast-metrics/ast-metrics
11
+ Keywords: static analysis,metrics,complexity,maintainability,quality,python,code-quality,cyclomatic-complexity,technical-debt,pre-commit
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Operating System :: MacOS
17
+ Classifier: Operating System :: Microsoft :: Windows
18
+ Classifier: Operating System :: POSIX :: Linux
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Programming Language :: Python :: 3 :: Only
21
+ Classifier: Topic :: Software Development :: Quality Assurance
22
+ Requires-Python: >=3.8
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Dynamic: license-file
26
+
27
+ # AST Metrics for Python
28
+
29
+ [AST Metrics](https://github.com/ast-metrics/ast-metrics) is a static analyzer
30
+ that tells you which parts of a codebase are risky to touch. This package
31
+ installs it with pip, like any other dev tool: no compiler, no service. The
32
+ analyzer is a single binary, downloaded once and cached.
33
+
34
+ > **You may not need this package.** It exists for one thing: getting the
35
+ > analyzer through pip, so it lands in `requirements.txt` (or `uv.lock`) with
36
+ > the rest of your tooling and `pipx run ast-metrics` just works. If that is
37
+ > not what you are after, install the analyzer directly:
38
+ >
39
+ > ```bash
40
+ > brew install ast-metrics/tap/ast-metrics # macOS, Linux
41
+ > curl -fsSL https://install.ast-metrics.dev | sh
42
+ > ```
43
+ >
44
+ > And on pull requests, there is a ready-made action:
45
+ > [`ast-metrics/action-ast-metrics@v2`](https://github.com/ast-metrics/action-ast-metrics).
46
+
47
+ ## Usage
48
+
49
+ Without installing anything:
50
+
51
+ ```bash
52
+ pipx run ast-metrics analyze src
53
+ ```
54
+
55
+ Or as a dev dependency, which pins the analyzer version in your lockfile:
56
+
57
+ ```bash
58
+ pip install ast-metrics # add it to requirements-dev.txt yourself
59
+ # or, with uv:
60
+ uv add --dev ast-metrics
61
+
62
+ ast-metrics analyze src
63
+ ast-metrics analyze --report-html=./report src
64
+ ```
65
+
66
+ If the virtualenv's `bin` (or `Scripts`) directory is not on `PATH`, run it as
67
+ a module instead: `python -m ast_metrics analyze src`. It behaves exactly like
68
+ the `ast-metrics` command.
69
+
70
+ Everything else: `ast-metrics --help`, or
71
+ [ast-metrics.dev](https://ast-metrics.dev).
72
+
73
+ ## What gets analyzed
74
+
75
+ Python (`.py`), and, in the same run, `Go`, `PHP`, `TypeScript`, `Rust`,
76
+ `Java` and `C#`. Most codebases are not made of one language, and the metrics
77
+ are comparable across all of them.
78
+
79
+ ## In CI
80
+
81
+ ```yaml
82
+ - run: pipx run ast-metrics analyze --ci src
83
+ ```
84
+
85
+ `--ci` writes the HTML and Markdown reports and keeps the output plain.
86
+ Reports for a quality gate: `--report-sarif=<file>` (read by GitHub code
87
+ scanning and GitLab), `--report-json=<file>`, `--report-openmetrics=<file>`.
88
+
89
+ The binary is downloaded once per version and cached in
90
+ `$AST_METRICS_CACHE_DIR`, which defaults to `$XDG_CACHE_HOME/ast-metrics` or
91
+ `~/.cache/ast-metrics`, so caching that directory between builds removes the
92
+ download entirely.
93
+
94
+ ## Pre-commit hook
95
+
96
+ This repository ships a [`.pre-commit-hooks.yaml`](.pre-commit-hooks.yaml):
97
+
98
+ ```yaml
99
+ repos:
100
+ - repo: https://github.com/ast-metrics/ast-metrics-bridge-python
101
+ rev: v0.41.1
102
+ hooks:
103
+ - id: ast-metrics
104
+ ```
105
+
106
+ Without a `.ast-metrics.yaml` configuration file that sets requirements,
107
+ `ast-metrics lint` has nothing to check and does nothing. Run `ast-metrics
108
+ init` once to create one.
109
+
110
+ ## Configuration
111
+
112
+ All optional.
113
+
114
+ | Variable | Effect |
115
+ | --- | --- |
116
+ | `AST_METRICS_BINARY` | Path to a binary to use as-is, nothing downloaded: air-gapped installs, distribution packages. |
117
+ | `AST_METRICS_VERSION` | Release tag to download, or `latest`. Defaults to the pinned version. |
118
+ | `AST_METRICS_CACHE_DIR` | Where binaries are cached. Defaults to `$XDG_CACHE_HOME/ast-metrics`, or `~/.cache/ast-metrics` if unset (`%LOCALAPPDATA%\ast-metrics` on Windows). |
119
+ | `HTTP_PROXY`, `HTTPS_PROXY`, `NO_PROXY` | Honoured for the download by `urllib`, the standard-library HTTP client this package uses. |
120
+
121
+ The analyzer version is pinned by this package rather than resolved to
122
+ `latest`, so a locked `requirements.txt` (or `uv.lock`) gives a reproducible
123
+ analysis. The package version matches the analyzer version it installs:
124
+ `ast-metrics==0.41.1` runs AST Metrics 0.41.1. To upgrade, `pip install
125
+ --upgrade ast-metrics` or `uv lock --upgrade-package ast-metrics`.
126
+
127
+ Unlike npm, pip has no post-install hook: nothing is downloaded at `pip
128
+ install` time. The binary is fetched on the first run of `ast-metrics` (or
129
+ `python -m ast_metrics`), then cached for every run after that. On an
130
+ air-gapped or hermetic install, where that first run cannot reach the
131
+ network, install the binary yourself and set
132
+ `AST_METRICS_BINARY=/path/to/ast-metrics` before running this package.
133
+
134
+ ## Contributing
135
+
136
+ See [CONTRIBUTING.md](CONTRIBUTING.md). Analyzer bugs go to
137
+ [ast-metrics/ast-metrics](https://github.com/ast-metrics/ast-metrics); this
138
+ repository is the Python bridge.
139
+
140
+ ## License
141
+
142
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,116 @@
1
+ # AST Metrics for Python
2
+
3
+ [AST Metrics](https://github.com/ast-metrics/ast-metrics) is a static analyzer
4
+ that tells you which parts of a codebase are risky to touch. This package
5
+ installs it with pip, like any other dev tool: no compiler, no service. The
6
+ analyzer is a single binary, downloaded once and cached.
7
+
8
+ > **You may not need this package.** It exists for one thing: getting the
9
+ > analyzer through pip, so it lands in `requirements.txt` (or `uv.lock`) with
10
+ > the rest of your tooling and `pipx run ast-metrics` just works. If that is
11
+ > not what you are after, install the analyzer directly:
12
+ >
13
+ > ```bash
14
+ > brew install ast-metrics/tap/ast-metrics # macOS, Linux
15
+ > curl -fsSL https://install.ast-metrics.dev | sh
16
+ > ```
17
+ >
18
+ > And on pull requests, there is a ready-made action:
19
+ > [`ast-metrics/action-ast-metrics@v2`](https://github.com/ast-metrics/action-ast-metrics).
20
+
21
+ ## Usage
22
+
23
+ Without installing anything:
24
+
25
+ ```bash
26
+ pipx run ast-metrics analyze src
27
+ ```
28
+
29
+ Or as a dev dependency, which pins the analyzer version in your lockfile:
30
+
31
+ ```bash
32
+ pip install ast-metrics # add it to requirements-dev.txt yourself
33
+ # or, with uv:
34
+ uv add --dev ast-metrics
35
+
36
+ ast-metrics analyze src
37
+ ast-metrics analyze --report-html=./report src
38
+ ```
39
+
40
+ If the virtualenv's `bin` (or `Scripts`) directory is not on `PATH`, run it as
41
+ a module instead: `python -m ast_metrics analyze src`. It behaves exactly like
42
+ the `ast-metrics` command.
43
+
44
+ Everything else: `ast-metrics --help`, or
45
+ [ast-metrics.dev](https://ast-metrics.dev).
46
+
47
+ ## What gets analyzed
48
+
49
+ Python (`.py`), and, in the same run, `Go`, `PHP`, `TypeScript`, `Rust`,
50
+ `Java` and `C#`. Most codebases are not made of one language, and the metrics
51
+ are comparable across all of them.
52
+
53
+ ## In CI
54
+
55
+ ```yaml
56
+ - run: pipx run ast-metrics analyze --ci src
57
+ ```
58
+
59
+ `--ci` writes the HTML and Markdown reports and keeps the output plain.
60
+ Reports for a quality gate: `--report-sarif=<file>` (read by GitHub code
61
+ scanning and GitLab), `--report-json=<file>`, `--report-openmetrics=<file>`.
62
+
63
+ The binary is downloaded once per version and cached in
64
+ `$AST_METRICS_CACHE_DIR`, which defaults to `$XDG_CACHE_HOME/ast-metrics` or
65
+ `~/.cache/ast-metrics`, so caching that directory between builds removes the
66
+ download entirely.
67
+
68
+ ## Pre-commit hook
69
+
70
+ This repository ships a [`.pre-commit-hooks.yaml`](.pre-commit-hooks.yaml):
71
+
72
+ ```yaml
73
+ repos:
74
+ - repo: https://github.com/ast-metrics/ast-metrics-bridge-python
75
+ rev: v0.41.1
76
+ hooks:
77
+ - id: ast-metrics
78
+ ```
79
+
80
+ Without a `.ast-metrics.yaml` configuration file that sets requirements,
81
+ `ast-metrics lint` has nothing to check and does nothing. Run `ast-metrics
82
+ init` once to create one.
83
+
84
+ ## Configuration
85
+
86
+ All optional.
87
+
88
+ | Variable | Effect |
89
+ | --- | --- |
90
+ | `AST_METRICS_BINARY` | Path to a binary to use as-is, nothing downloaded: air-gapped installs, distribution packages. |
91
+ | `AST_METRICS_VERSION` | Release tag to download, or `latest`. Defaults to the pinned version. |
92
+ | `AST_METRICS_CACHE_DIR` | Where binaries are cached. Defaults to `$XDG_CACHE_HOME/ast-metrics`, or `~/.cache/ast-metrics` if unset (`%LOCALAPPDATA%\ast-metrics` on Windows). |
93
+ | `HTTP_PROXY`, `HTTPS_PROXY`, `NO_PROXY` | Honoured for the download by `urllib`, the standard-library HTTP client this package uses. |
94
+
95
+ The analyzer version is pinned by this package rather than resolved to
96
+ `latest`, so a locked `requirements.txt` (or `uv.lock`) gives a reproducible
97
+ analysis. The package version matches the analyzer version it installs:
98
+ `ast-metrics==0.41.1` runs AST Metrics 0.41.1. To upgrade, `pip install
99
+ --upgrade ast-metrics` or `uv lock --upgrade-package ast-metrics`.
100
+
101
+ Unlike npm, pip has no post-install hook: nothing is downloaded at `pip
102
+ install` time. The binary is fetched on the first run of `ast-metrics` (or
103
+ `python -m ast_metrics`), then cached for every run after that. On an
104
+ air-gapped or hermetic install, where that first run cannot reach the
105
+ network, install the binary yourself and set
106
+ `AST_METRICS_BINARY=/path/to/ast-metrics` before running this package.
107
+
108
+ ## Contributing
109
+
110
+ See [CONTRIBUTING.md](CONTRIBUTING.md). Analyzer bugs go to
111
+ [ast-metrics/ast-metrics](https://github.com/ast-metrics/ast-metrics); this
112
+ repository is the Python bridge.
113
+
114
+ ## License
115
+
116
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,46 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "ast-metrics"
7
+ # The version of this package is the version of the analyzer it downloads,
8
+ # so that `pip install ast-metrics==X.Y.Z` is a promise about the analyzer
9
+ # and not just about the wrapper. The release pipeline of
10
+ # ast-metrics/ast-metrics rewrites this line on every release: keep the shape
11
+ # `version = "X.Y.Z"`.
12
+ version = "0.41.1"
13
+ description = "AST Metrics bridge for Python: multi-language maintainability metrics, installable with pip and runnable with pipx"
14
+ readme = "README.md"
15
+ license = { text = "MIT" }
16
+ authors = [{ name = "Jean-François Lépine", email = "lepinejeanfrancois@gmail.com" }]
17
+ requires-python = ">=3.8"
18
+ dependencies = []
19
+ keywords = [
20
+ "static analysis", "metrics", "complexity", "maintainability", "quality",
21
+ "python", "code-quality", "cyclomatic-complexity", "technical-debt", "pre-commit",
22
+ ]
23
+ classifiers = [
24
+ "Development Status :: 4 - Beta",
25
+ "Environment :: Console",
26
+ "Intended Audience :: Developers",
27
+ "License :: OSI Approved :: MIT License",
28
+ "Operating System :: MacOS",
29
+ "Operating System :: Microsoft :: Windows",
30
+ "Operating System :: POSIX :: Linux",
31
+ "Programming Language :: Python :: 3",
32
+ "Programming Language :: Python :: 3 :: Only",
33
+ "Topic :: Software Development :: Quality Assurance",
34
+ ]
35
+
36
+ [project.urls]
37
+ Homepage = "https://ast-metrics.dev"
38
+ Repository = "https://github.com/ast-metrics/ast-metrics-bridge-python"
39
+ Issues = "https://github.com/ast-metrics/ast-metrics-bridge-python/issues"
40
+ Analyzer = "https://github.com/ast-metrics/ast-metrics"
41
+
42
+ [project.scripts]
43
+ ast-metrics = "ast_metrics.cli:main"
44
+
45
+ [tool.setuptools.packages.find]
46
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,11 @@
1
+ """AST Metrics for Python: installs the analyzer through pip and runs it.
2
+
3
+ The analyzer itself is a single Go binary, released by ast-metrics/ast-metrics.
4
+ This package downloads it once, keeps it in a cache, and passes the command line
5
+ through untouched.
6
+ """
7
+
8
+ from .version import PINNED_VERSION
9
+
10
+ __all__ = ["PINNED_VERSION"]
11
+ __version__ = PINNED_VERSION.lstrip("v")
@@ -0,0 +1,8 @@
1
+ """`python -m ast_metrics` behaves exactly like the `ast-metrics` command."""
2
+
3
+ import sys
4
+
5
+ from .cli import main
6
+
7
+ if __name__ == "__main__":
8
+ sys.exit(main())
@@ -0,0 +1,158 @@
1
+ """Resolving, downloading and caching the analyzer binary."""
2
+
3
+ import os
4
+ import sys
5
+ import tempfile
6
+
7
+ from .download import DownloadError, copy_to_file, open_url, read_json
8
+ from .platforms import Platform
9
+ from .version import PINNED_VERSION
10
+
11
+ REPOSITORY = "ast-metrics/ast-metrics"
12
+
13
+ # A truncated download, an HTML error page or a Git LFS pointer are all far
14
+ # below this. The real binary weighs tens of megabytes.
15
+ MINIMUM_SIZE = 1048576
16
+
17
+
18
+ class BinaryError(Exception):
19
+ pass
20
+
21
+
22
+ class BinaryProvider:
23
+ def __init__(self, platform=None, env=None, output=None):
24
+ self.platform = platform or Platform.current()
25
+ self.env = os.environ if env is None else env
26
+ self.output = sys.stderr if output is None else output
27
+
28
+ def resolve(self):
29
+ """Absolute path to a runnable analyzer, downloading it once if needed."""
30
+ provided = self.env.get("AST_METRICS_BINARY")
31
+ if provided:
32
+ return self.validate_provided_binary(provided)
33
+
34
+ version = self.version()
35
+ destination = self.cached_path(version)
36
+ if self.is_runnable(destination):
37
+ return destination
38
+
39
+ self.download(self.download_url(version), destination, version)
40
+ return destination
41
+
42
+ def validate_provided_binary(self, provided):
43
+ if not os.path.exists(provided):
44
+ raise BinaryError('AST_METRICS_BINARY points to "{}", which does not exist.'.format(provided))
45
+ if not self.is_runnable(provided):
46
+ raise BinaryError(
47
+ 'AST_METRICS_BINARY points to "{}", which is not executable.\n'
48
+ "Try: chmod +x {}".format(provided, provided)
49
+ )
50
+ return provided
51
+
52
+ def is_runnable(self, candidate):
53
+ if not os.path.isfile(candidate):
54
+ return False
55
+ if self.platform.is_windows():
56
+ return True
57
+ return os.access(candidate, os.X_OK)
58
+
59
+ def version(self):
60
+ requested = self.env.get("AST_METRICS_VERSION")
61
+ if not requested:
62
+ return PINNED_VERSION
63
+ if requested == "latest":
64
+ return self.resolve_latest_version()
65
+ return requested
66
+
67
+ def resolve_latest_version(self):
68
+ url = "https://api.github.com/repos/{}/releases/latest".format(REPOSITORY)
69
+ try:
70
+ release = read_json(url)
71
+ except (DownloadError, ValueError) as error:
72
+ raise BinaryError(
73
+ "Could not read the latest AST Metrics release from {}.\n"
74
+ "Pin a version instead, with AST_METRICS_VERSION={}.\n{}".format(url, PINNED_VERSION, error)
75
+ )
76
+ tag = release.get("tag_name") if isinstance(release, dict) else None
77
+ if not tag:
78
+ raise BinaryError(
79
+ "The GitHub API did not return a release tag for {}.\n"
80
+ "Pin a version instead, with AST_METRICS_VERSION={}.".format(REPOSITORY, PINNED_VERSION)
81
+ )
82
+ return tag
83
+
84
+ def download_url(self, version):
85
+ return "https://github.com/{}/releases/download/{}/{}".format(
86
+ REPOSITORY, version, self.platform.asset_name()
87
+ )
88
+
89
+ def cached_path(self, version):
90
+ directory = os.path.join(self.cache_directory(), version)
91
+ os.makedirs(directory, mode=0o700, exist_ok=True)
92
+ return os.path.join(directory, self.platform.asset_name())
93
+
94
+ def cache_directory(self):
95
+ if self.env.get("AST_METRICS_CACHE_DIR"):
96
+ return self.env["AST_METRICS_CACHE_DIR"]
97
+ if self.env.get("XDG_CACHE_HOME"):
98
+ return os.path.join(self.env["XDG_CACHE_HOME"], "ast-metrics")
99
+ if self.env.get("HOME"):
100
+ return os.path.join(self.env["HOME"], ".cache", "ast-metrics")
101
+ if self.env.get("LOCALAPPDATA"):
102
+ return os.path.join(self.env["LOCALAPPDATA"], "ast-metrics")
103
+ return os.path.join(tempfile.gettempdir(), "ast-metrics-" + self.user_identifier())
104
+
105
+ def user_identifier(self):
106
+ if hasattr(os, "getuid"):
107
+ return str(os.getuid())
108
+ user = self.env.get("USER") or self.env.get("USERNAME")
109
+ if not user:
110
+ return "shared"
111
+ return "".join(c if c.isalnum() or c in "_.-" else "_" for c in user)
112
+
113
+ def download(self, url, destination, version):
114
+ """Written to a temporary file next to the destination, then renamed:
115
+ two parallel runs (a matrix build sharing a cache, say) never see a
116
+ half written binary."""
117
+ self.write(
118
+ "Downloading AST Metrics {} for {} {}...".format(version, self.platform.os, self.platform.architecture)
119
+ )
120
+ temporary = "{}.download.{}".format(destination, os.getpid())
121
+ try:
122
+ with open_url(url) as response:
123
+ written = copy_to_file(response, temporary, lambda p: self.write(" {}%".format(p)))
124
+ except DownloadError:
125
+ self.discard(temporary)
126
+ raise
127
+ except OSError as error:
128
+ self.discard(temporary)
129
+ raise BinaryError('Could not write the downloaded binary to "{}": {}'.format(temporary, error))
130
+
131
+ if written < MINIMUM_SIZE:
132
+ self.discard(temporary)
133
+ raise BinaryError(
134
+ "The download from {} returned {} bytes, which is not a valid binary.\n"
135
+ "Check that this version exists, or pin another one with AST_METRICS_VERSION.".format(url, written)
136
+ )
137
+
138
+ try:
139
+ if not self.platform.is_windows():
140
+ os.chmod(temporary, 0o755)
141
+ os.replace(temporary, destination)
142
+ except OSError as error:
143
+ self.discard(temporary)
144
+ raise BinaryError('Could not install the downloaded binary as "{}": {}'.format(destination, error))
145
+
146
+ self.write("Done ({} MB).".format(round(written / 1048576)))
147
+
148
+ @staticmethod
149
+ def discard(temporary):
150
+ try:
151
+ os.unlink(temporary)
152
+ except OSError:
153
+ pass
154
+
155
+ def write(self, message):
156
+ if self.output:
157
+ self.output.write(message + "\n")
158
+ self.output.flush()
@@ -0,0 +1,27 @@
1
+ """The `ast-metrics` command installed by pip.
2
+
3
+ Every argument is passed through untouched: this package is a way to install
4
+ the analyzer, not a wrapper around its command line. `ast-metrics --help`
5
+ documents everything.
6
+ """
7
+
8
+ import sys
9
+
10
+ from .binary import BinaryError, BinaryProvider
11
+ from .download import DownloadError
12
+ from .platforms import UnsupportedPlatform
13
+ from .runner import StartupError, run
14
+
15
+
16
+ def main(argv=None):
17
+ args = sys.argv[1:] if argv is None else list(argv)
18
+ try:
19
+ binary = BinaryProvider().resolve()
20
+ return run(binary, args)
21
+ except (BinaryError, DownloadError, UnsupportedPlatform, StartupError) as error:
22
+ sys.stderr.write(str(error) + "\n")
23
+ return 1
24
+
25
+
26
+ if __name__ == "__main__":
27
+ sys.exit(main())
@@ -0,0 +1,70 @@
1
+ """HTTP on the standard library: redirects, proxies, a timeout, a progress
2
+ callback. urllib honours HTTP_PROXY, HTTPS_PROXY and NO_PROXY on its own, which
3
+ is what most CI runners behind a proxy rely on."""
4
+
5
+ import json
6
+ import urllib.error
7
+ import urllib.request
8
+
9
+ USER_AGENT = "ast-metrics/ast-metrics (pip bridge)"
10
+ TIMEOUT = 120
11
+ CHUNK = 256 * 1024
12
+
13
+
14
+ class DownloadError(Exception):
15
+ pass
16
+
17
+
18
+ def open_url(url):
19
+ """Returns the response of a successful GET, redirects already followed."""
20
+ request = urllib.request.Request(url, headers={"User-Agent": USER_AGENT, "Accept": "*/*"})
21
+ try:
22
+ return urllib.request.urlopen(request, timeout=TIMEOUT)
23
+ except urllib.error.HTTPError as error:
24
+ raise DownloadError(
25
+ "{} responded with HTTP {}.\n"
26
+ "Check that this version exists, or pin another one with AST_METRICS_VERSION.".format(url, error.code)
27
+ )
28
+ except (urllib.error.URLError, OSError) as error:
29
+ raise DownloadError(
30
+ "Could not download from {}: {}.\n"
31
+ "Check your network access and any proxy settings (HTTP_PROXY and HTTPS_PROXY are honoured).\n"
32
+ "On an air-gapped machine, install the binary yourself and set "
33
+ "AST_METRICS_BINARY=/path/to/ast-metrics.".format(url, getattr(error, "reason", error))
34
+ )
35
+
36
+
37
+ def stream_to(response, stream, on_progress=None):
38
+ """Streams the response into `stream`, reporting progress in steps of five
39
+ percent when the server announces a length. Returns the bytes written."""
40
+ total = 0
41
+ try:
42
+ total = int(response.headers.get("Content-Length") or 0)
43
+ except ValueError:
44
+ total = 0
45
+ written = 0
46
+ reported = -1
47
+ while True:
48
+ chunk = response.read(CHUNK)
49
+ if not chunk:
50
+ break
51
+ stream.write(chunk)
52
+ written += len(chunk)
53
+ if on_progress and total > 0:
54
+ percentage = written * 100 // total
55
+ if percentage >= reported + 5:
56
+ reported = percentage - (percentage % 5)
57
+ on_progress(reported)
58
+ return written
59
+
60
+
61
+ def read_json(url):
62
+ with open_url(url) as response:
63
+ return json.loads(response.read().decode("utf-8"))
64
+
65
+
66
+ def copy_to_file(response, path, on_progress=None):
67
+ with open(path, "wb") as stream:
68
+ return stream_to(response, stream, on_progress)
69
+
70
+
@@ -0,0 +1,71 @@
1
+ """Mapping of the running platform to the release assets of the analyzer.
2
+
3
+ Named `platforms`, not `platform`: the standard library owns that name and a
4
+ sibling module would shadow it inside this package.
5
+ """
6
+
7
+ import platform as _platform
8
+ import sys
9
+
10
+ # Names used by the release assets of ast-metrics/ast-metrics:
11
+ # ast-metrics_Linux_x86_64, ast-metrics_Darwin_arm64, ast-metrics_Windows_x86_64.exe
12
+ OPERATING_SYSTEMS = {
13
+ "linux": "Linux",
14
+ "darwin": "Darwin",
15
+ "win32": "Windows",
16
+ "cygwin": "Windows",
17
+ "msys": "Windows",
18
+ }
19
+
20
+ ARCHITECTURES = {
21
+ "x86_64": "x86_64",
22
+ "amd64": "x86_64",
23
+ "arm64": "arm64",
24
+ "aarch64": "arm64",
25
+ }
26
+
27
+ PUBLISHED = {
28
+ "Linux": ["x86_64", "arm64"],
29
+ "Darwin": ["x86_64", "arm64"],
30
+ "Windows": ["x86_64"],
31
+ }
32
+
33
+
34
+ class Platform:
35
+ def __init__(self, system, machine):
36
+ self.os = OPERATING_SYSTEMS.get(system, system)
37
+ self.architecture = ARCHITECTURES.get(machine.lower(), machine)
38
+
39
+ @classmethod
40
+ def current(cls):
41
+ return cls(sys.platform, _platform.machine())
42
+
43
+ def is_windows(self):
44
+ return self.os == "Windows"
45
+
46
+ def is_supported(self):
47
+ return self.architecture in PUBLISHED.get(self.os, [])
48
+
49
+ def asset_name(self):
50
+ """Name of the release asset for this platform, which is also the name
51
+ the binary keeps in the cache."""
52
+ if not self.is_supported():
53
+ raise UnsupportedPlatform(self.unsupported_message())
54
+ suffix = ".exe" if self.is_windows() else ""
55
+ return "ast-metrics_{}_{}{}".format(self.os, self.architecture, suffix)
56
+
57
+ def unsupported_message(self):
58
+ supported = "; ".join(
59
+ "{} ({})".format(os_name, ", ".join(architectures))
60
+ for os_name, architectures in PUBLISHED.items()
61
+ )
62
+ return (
63
+ "No AST Metrics binary is published for {} / {}.\n"
64
+ "Supported platforms: {}.\n"
65
+ "If you build the binary yourself, point the bridge at it with "
66
+ "AST_METRICS_BINARY=/path/to/ast-metrics."
67
+ ).format(self.os, self.architecture, supported)
68
+
69
+
70
+ class UnsupportedPlatform(Exception):
71
+ pass