|
| 1 | +# fetchcode is a free software tool from nexB Inc. and others. |
| 2 | +# Visit https://github.com/aboutcode-org/fetchcode for support and download. |
| 3 | +# |
| 4 | +# Copyright (c) nexB Inc. and others. All rights reserved. |
| 5 | +# http://nexb.com and http://aboutcode.org |
| 6 | +# |
| 7 | +# This software is licensed under the Apache License version 2.0. |
| 8 | +# |
| 9 | +# You may not use this software except in compliance with the License. |
| 10 | +# You may obtain a copy of the License at: |
| 11 | +# http://apache.org/licenses/LICENSE-2.0 |
| 12 | +# Unless required by applicable law or agreed to in writing, software distributed |
| 13 | +# under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR |
| 14 | +# CONDITIONS OF ANY KIND, either express or implied. See the License for the |
| 15 | +# specific language governing permissions and limitations under the License. |
| 16 | + |
| 17 | +from packageurl import PackageURL |
| 18 | + |
| 19 | +from fetchcode import fetch_json_response |
| 20 | +from fetchcode.utils import _http_exists |
| 21 | + |
| 22 | + |
| 23 | +class CPAN: |
| 24 | + purl_pattern = "pkg:cpan/.*" |
| 25 | + base_url = "https://cpan.metacpan.org/" |
| 26 | + |
| 27 | + def get_download_url(purl: str): |
| 28 | + """ |
| 29 | + Resolve a CPAN PURL to a verified, downloadable archive URL. |
| 30 | + Strategy: MetaCPAN API -> verified URL; fallback to author-based path if available. |
| 31 | + """ |
| 32 | + p = PackageURL.from_string(purl) |
| 33 | + if not p.name or not p.version: |
| 34 | + return None |
| 35 | + |
| 36 | + try: |
| 37 | + api = f"https://fastapi.metacpan.org/v1/release/{urllib.parse.quote(p.name)}/{urllib.parse.quote(p.version)}" |
| 38 | + data = fetch_json_response(api, stream=False, timeout=20) |
| 39 | + url = data.get("download_url") or data.get("archive") |
| 40 | + if url and _http_exists(url): |
| 41 | + return url |
| 42 | + except Exception: |
| 43 | + pass |
| 44 | + |
| 45 | + author = p.namespace |
| 46 | + if author: |
| 47 | + auth = author.upper() |
| 48 | + a = auth[0] |
| 49 | + ab = auth[:2] if len(auth) >= 2 else auth |
| 50 | + for ext in (".tar.gz", ".zip"): |
| 51 | + url = f"https://cpan.metacpan.org/authors/id/{a}/{ab}/{auth}/{p.name}-{p.version}{ext}" |
| 52 | + if _http_exists(url): |
| 53 | + return url |
0 commit comments