Skip to content

Commit 9fb5350

Browse files
authored
Merge pull request #191 from jaimergp/encode-kwarg
Add `encode` kwarg to `.to_string()`
2 parents 9efce47 + 84dcc3b commit 9fb5350

File tree

2 files changed

+24
-4
lines changed

2 files changed

+24
-4
lines changed

src/packageurl/__init__.py

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626

2727
import string
2828
from collections import namedtuple
29+
from collections.abc import Mapping
2930
from typing import TYPE_CHECKING
3031
from typing import Any
3132
from typing import Union
@@ -226,9 +227,12 @@ def normalize_qualifiers(
226227

227228
if not encode:
228229
return qualifiers_map
230+
return _qualifier_map_to_string(qualifiers_map) or None
229231

230-
qualifiers_list = [f"{key}={value}" for key, value in qualifiers_map.items()]
231-
return "&".join(qualifiers_list) or None
232+
233+
def _qualifier_map_to_string(qualifiers: dict[str, str]) -> str:
234+
qualifiers_list = [f"{key}={value}" for key, value in qualifiers.items()]
235+
return "&".join(qualifiers_list)
232236

233237

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

399403
return data
400404

401-
def to_string(self) -> str:
405+
def to_string(self, encode: bool | None = True) -> str:
402406
"""
403407
Return a purl string built from components.
404408
"""
@@ -409,7 +413,7 @@ def to_string(self) -> str:
409413
self.version,
410414
self.qualifiers,
411415
self.subpath,
412-
encode=True,
416+
encode=encode,
413417
)
414418

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

426430
if qualifiers:
427431
purl.append("?")
432+
if isinstance(qualifiers, Mapping):
433+
qualifiers = _qualifier_map_to_string(qualifiers)
428434
purl.append(qualifiers)
429435

430436
if subpath:

tests/test_packageurl.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -374,3 +374,17 @@ def test_encoding_stuff_with_colons_correctly() -> None:
374374
p.to_string()
375375
== "pkg:nuget/an:odd:space/libiconv:%20character%20set%20conversion%20library@1.9?package-id=e11a609df352e292"
376376
)
377+
378+
379+
def test_no_encoding_to_string():
380+
p = PackageURL(
381+
type="nuget",
382+
namespace="an:odd:space",
383+
name="libiconv: character set conversion library",
384+
version="1.9",
385+
qualifiers={"package-id": "e11a609df352e292"},
386+
)
387+
assert (
388+
p.to_string(encode=False)
389+
== "pkg:nuget/an:odd:space/libiconv: character set conversion library@1.9?package-id=e11a609df352e292"
390+
)

0 commit comments

Comments
 (0)