Skip to content

Add encode kwarg to .to_string() #191

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions src/packageurl/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@

import string
from collections import namedtuple
from collections.abc import Mapping
from typing import TYPE_CHECKING
from typing import Any
from typing import Union
Expand Down Expand Up @@ -226,9 +227,12 @@ def normalize_qualifiers(

if not encode:
return qualifiers_map
return _qualifier_map_to_string(qualifiers_map) or None

qualifiers_list = [f"{key}={value}" for key, value in qualifiers_map.items()]
return "&".join(qualifiers_list) or None

def _qualifier_map_to_string(qualifiers: dict[str, str]) -> str:
qualifiers_list = [f"{key}={value}" for key, value in qualifiers.items()]
return "&".join(qualifiers_list)


def normalize_subpath(subpath: AnyStr | None, encode: bool | None = True) -> str | None:
Expand Down Expand Up @@ -398,7 +402,7 @@ def to_dict(self, encode: bool | None = False, empty: Any = None) -> dict[str, A

return data

def to_string(self) -> str:
def to_string(self, encode: bool | None = True) -> str:
"""
Return a purl string built from components.
"""
Expand All @@ -409,7 +413,7 @@ def to_string(self) -> str:
self.version,
self.qualifiers,
self.subpath,
encode=True,
encode=encode,
)

purl = [self.SCHEME, ":", type, "/"]
Expand All @@ -425,6 +429,8 @@ def to_string(self) -> str:

if qualifiers:
purl.append("?")
if isinstance(qualifiers, Mapping):
qualifiers = _qualifier_map_to_string(qualifiers)
purl.append(qualifiers)

if subpath:
Expand Down
14 changes: 14 additions & 0 deletions tests/test_packageurl.py
Original file line number Diff line number Diff line change
Expand Up @@ -374,3 +374,17 @@ def test_encoding_stuff_with_colons_correctly() -> None:
p.to_string()
== "pkg:nuget/an:odd:space/libiconv:%20character%20set%20conversion%[email protected]?package-id=e11a609df352e292"
)


def test_no_encoding_to_string():
p = PackageURL(
type="nuget",
namespace="an:odd:space",
name="libiconv: character set conversion library",
version="1.9",
qualifiers={"package-id": "e11a609df352e292"},
)
assert (
p.to_string(encode=False)
== "pkg:nuget/an:odd:space/libiconv: character set conversion [email protected]?package-id=e11a609df352e292"
)
Loading