Use import.resources instead of __file__
Potentially fix #257 and allow zip-safe = true in pyproject.toml
Signed-off-by: Arthit Suriyawongkul <arthit@gmail.com>
GitOrigin-RevId: 7636b1b686f5b7541cfa7d67b27461c7b23e0a1e
Change-Id: I23678eb4f684a1634d9db85d212f6e6fd1c5ab8e
diff --git a/src/spdx_tools/spdx3/writer/json_ld/json_ld_writer.py b/src/spdx_tools/spdx3/writer/json_ld/json_ld_writer.py
index 69a4d76..3c3e081 100644
--- a/src/spdx_tools/spdx3/writer/json_ld/json_ld_writer.py
+++ b/src/spdx_tools/spdx3/writer/json_ld/json_ld_writer.py
@@ -2,20 +2,24 @@
#
# SPDX-License-Identifier: Apache-2.0
import json
-import os
+from importlib import resources
from spdx_tools.spdx3.payload import Payload
-from spdx_tools.spdx3.writer.json_ld.json_ld_converter import convert_payload_to_json_ld_list_of_elements
+from spdx_tools.spdx3.writer.json_ld.json_ld_converter import (
+ convert_payload_to_json_ld_list_of_elements,
+)
def write_payload(payload: Payload, file_name: str):
element_list = convert_payload_to_json_ld_list_of_elements(payload)
# this will be obsolete as soon as the context is publicly available under some URI
- with open(os.path.join(os.path.dirname(__file__), "context.json"), "r") as infile:
+ # Note: 3.0.1 context is now available at
+ # https://spdx.org/rdf/3.0.1/spdx-context.jsonld
+ with resources.files("spdx_tools.spdx3.writer.json_ld").joinpath("context.json").open("r") as infile:
context = json.load(infile)
complete_dict = {"@context": context, "@graph": element_list}
- with open(file_name + ".jsonld", "w") as out:
+ with open(file_name + ".jsonld", "w", encoding="utf-8") as out:
json.dump(complete_dict, out, indent=2)
diff --git a/src/spdx_tools/spdx3/writer/json_ld/owl_to_context.py b/src/spdx_tools/spdx3/writer/json_ld/owl_to_context.py
index f6bc7c3..cdeb314 100644
--- a/src/spdx_tools/spdx3/writer/json_ld/owl_to_context.py
+++ b/src/spdx_tools/spdx3/writer/json_ld/owl_to_context.py
@@ -2,7 +2,7 @@
#
# SPDX-License-Identifier: Apache-2.0
import json
-import os.path
+from importlib import resources
# current workflow: markdown files + spec_parser -> model.ttl -> convert to json_ld: SPDX_OWL.json ->
# use the function below to generate context.json
@@ -108,8 +108,11 @@
else:
print(f"unknown node_type: {node_type}")
- with open(os.path.join(os.path.dirname(__file__), "context.json"), "w") as infile:
- json.dump(context_dict, infile)
+ with resources.as_file(
+ resources.files("spdx_tools.spdx3.writer.json_ld").joinpath("context.json")
+ ) as context_path:
+ with open(context_path, "w", encoding="utf-8") as outfile:
+ json.dump(context_dict, outfile)
if __name__ == "__main__":