Skip to content

Commit 7d4ef89

Browse files
committed
Add utility and cli to discover PURL on AP server
Signed-off-by: Keshav Priyadarshi <git@keshav.space>
1 parent b68ef5e commit 7d4ef89

File tree

2 files changed

+59
-3
lines changed

2 files changed

+59
-3
lines changed

aboutcode/federatedcode/cli.py

Lines changed: 31 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,19 +10,47 @@
1010

1111
import click
1212

13-
from aboutcode.federatedcode.client import get_package_scan
13+
from aboutcode.federatedcode import client
14+
15+
16+
@click.group()
17+
def handler():
18+
pass
1419

1520

1621
@click.command()
1722
@click.argument("purl")
18-
def handler(purl):
23+
def scan(purl):
1924
"""
2025
Get package scan for PURL from FederatedCode git repository.
2126
2227
PURL: PURL to fetch scan result
2328
"""
24-
click.echo(get_package_scan(purl=purl))
29+
click.echo(client.get_package_scan(purl=purl))
30+
31+
32+
@click.command()
33+
@click.argument("purl")
34+
def discover(purl):
35+
"""
36+
Discover existing Packages in the FederatedCode AP server.
37+
38+
PURL: PURL to find in AP server
39+
"""
40+
if response := client.discover_package_in_ap_server(purl=purl):
41+
click.echo(click.style(response, fg="green", bold=True))
42+
else:
43+
click.echo(
44+
click.style(
45+
f"Error: {purl} not available on {client.FEDERATEDCODE_AP_HOST} AP server.",
46+
fg="red",
47+
bold=True,
48+
)
49+
)
50+
2551

52+
handler.add_command(scan)
53+
handler.add_command(discover)
2654

2755
if __name__ == "__main__":
2856
handler()

aboutcode/federatedcode/client/__init__.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,11 @@
2424
"https://raw.githubusercontent.com/aboutcode-org/",
2525
)
2626

27+
FEDERATEDCODE_AP_HOST = os.getenv(
28+
"FEDERATEDCODE_AP_HOST",
29+
"http://localhost:8000/",
30+
)
31+
2732

2833
class ScanNotAvailableError(Exception):
2934
pass
@@ -68,3 +73,26 @@ def subscribe_package(federatedcode_host, remote_username, purl):
6873

6974
url_path = f"api/v0/users/@{remote_username}/subscribe/?purl={quote(purl)}"
7075
return requests.get(urljoin(federatedcode_host, url_path))
76+
77+
78+
def discover_package_in_ap_server(purl: Union[str, PackageURL]):
79+
"""Return package profile if PURL exists in AP server."""
80+
81+
if not FEDERATEDCODE_AP_HOST:
82+
raise ValueError("Provide ``FEDERATEDCODE_AP_HOST`` in .env file.")
83+
84+
if isinstance(purl, str):
85+
purl = PackageURL.from_string(purl)
86+
87+
if purl.version or purl.subpath or purl.qualifiers:
88+
purl = PackageURL(
89+
type=purl.type,
90+
namespace=purl.name,
91+
name=purl.name,
92+
)
93+
94+
package = quote(str(purl), safe=":/")
95+
url = urljoin(FEDERATEDCODE_AP_HOST, f"/purls/@{package}")
96+
response = requests.head(url, allow_redirects=True)
97+
if response.status_code == 200:
98+
return url

0 commit comments

Comments
 (0)