Skip to content
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

chore(models-project): remove all project update code #802

Merged
merged 17 commits into from
Feb 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
79 changes: 13 additions & 66 deletions src/dsp_tools/commands/project/create/project_create.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@
def _create_project_on_server(
project_definition: ProjectDefinition,
con: Connection,
verbose: bool,
) -> tuple[Project, bool]:
"""
Create the project on the DSP server.
Expand All @@ -41,7 +40,6 @@ def _create_project_on_server(
Args:
project_definition: object with information about the project
con: connection to the DSP server
verbose: verbose switch

Raises:
UserError: if the project cannot be created on the DSP server
Expand All @@ -51,23 +49,13 @@ def _create_project_on_server(
"""
all_projects = Project.getAllProjects(con=con)
if project_definition.shortcode in [proj.shortcode for proj in all_projects]:
project_local = Project(con=con, shortcode=project_definition.shortcode)
project_remote: Project = project_local.read()
msg = (
f"A project with shortcode {project_definition.shortcode} already exists on the DSP server. Updating it..."
Nora-Olivia-Ammann marked this conversation as resolved.
Show resolved Hide resolved
f"The project with the shortcode '{project_definition.shortcode}' already exists on the server.\n"
f"No changes were made to the project metadata.\n"
f"Continue with the upload of lists and ontologies ..."
)
print(f" WARNING: {msg}")
print(f"WARNING: {msg}")
logger.warning(msg)
# try to update the basic info
project_remote, _ = _update_basic_info_of_project(
project=project_remote,
project_definition=project_definition,
verbose=verbose,
)
# It doesn't matter if the update is successful or not: continue anyway, because success is anyways false.
# There are other things from this file that can be created on the server,
# e.g. the groups and users, so the process must continue.
return project_remote, False

success = True
project_local = Project(
Expand All @@ -94,46 +82,6 @@ def _create_project_on_server(
return project_remote, success


def _update_basic_info_of_project(
project: Project,
project_definition: ProjectDefinition,
verbose: bool,
) -> tuple[Project, bool]:
"""
Updates the longname, description and keywords of a project on a DSP server.
Returns the updated project (or the unchanged project if not successful)
and a boolean saying if the update was successful or not.
If the update was not successful, an error message is printed to stdout.

Args:
project: the project to be updated (must exist on the DSP server)
project_definition: object with project info
verbose: verbose switch

Returns:
tuple of (updated project, success status)
"""

# update the local "project" object
project.longname = project_definition.longname
project.description = LangString(project_definition.descriptions) # type: ignore[arg-type]
project.keywords = set(project_definition.keywords) if project_definition.keywords else set()

# make the call to DSP-API
try:
project_remote: Project = project.update()
info_str = f" Updated project '{project_definition.shortname}' ({project_definition.shortcode})."
if verbose:
print(info_str)
logger.info(info_str)
return project_remote, True
except BaseError:
msg = f"WARNING: Could not update project '{project_definition.shortname}' ({project_definition.shortcode})."
print(msg)
logger.warning(msg, exc_info=True)
return project, False


def _create_groups(
con: Connection,
groups: list[dict[str, str]],
Expand Down Expand Up @@ -167,7 +115,7 @@ def _create_groups(
"not possible to retrieve the remote groups from the DSP server."
)
print(f"WARNING: {err_msg}")
logger.warning(err_msg, exc_info=True)
logger.warning(err_msg)
remote_groups = []
overall_success = False

Expand Down Expand Up @@ -195,7 +143,7 @@ def _create_groups(
group_remote: Group = group_local.create()
except BaseError:
print(f" WARNING: Unable to create group '{group_name}'.")
logger.warning(f"Unable to create group '{group_name}'.", exc_info=True)
logger.warning(f"Unable to create group '{group_name}'.")
overall_success = False
continue

Expand Down Expand Up @@ -276,7 +224,7 @@ def _get_group_iris_for_user(
f"exists on the DSP server, but no groups could be retrieved from the DSP server."
)
print(f" WARNING: {err_msg}")
logger.warning(err_msg, exc_info=True)
logger.warning(err_msg)
success = False
continue
existing_group = [g for g in remote_groups if g.project == current_project.iri and g.name == group_name]
Expand Down Expand Up @@ -344,7 +292,7 @@ def _get_projects_where_user_is_admin(
f"because the projects cannot be retrieved from the DSP server."
)
print(f" WARNING: {err_msg}")
logger.warning(err_msg, exc_info=True)
logger.warning(err_msg)
success = False
continue
in_project_list = [p for p in remote_projects if p.shortname == project_name]
Expand Down Expand Up @@ -437,7 +385,7 @@ def _create_users(
user_local.create()
except BaseError:
print(f" WARNING: Unable to create user '{username}'.")
logger.warning(f"Unable to create user '{username}'.", exc_info=True)
logger.warning(f"Unable to create user '{username}'.")
overall_success = False
continue
print(f" Created user '{username}'.")
Expand Down Expand Up @@ -628,7 +576,7 @@ def _create_ontologies(
except BaseError:
err_msg = "Unable to retrieve remote ontologies. Cannot check if your ontology already exists."
print("WARNING: {err_msg}")
logger.warning(err_msg, exc_info=True)
logger.warning(err_msg)
project_ontologies = []

for ontology_definition in ontology_definitions:
Expand Down Expand Up @@ -742,7 +690,7 @@ def _add_resource_classes_to_remote_ontology(
logger.info(f"Created resource class '{res_class['name']}'")
except BaseError:
print(f"WARNING: Unable to create resource class '{res_class['name']}'.")
logger.warning(f"Unable to create resource class '{res_class['name']}'.", exc_info=True)
logger.warning(f"Unable to create resource class '{res_class['name']}'.")
overall_success = False

return last_modification_date, new_res_classes, overall_success
Expand Down Expand Up @@ -837,7 +785,7 @@ def _add_property_classes_to_remote_ontology(
logger.info(f"Created property class '{prop_class['name']}'")
except BaseError:
print(f"WARNING: Unable to create property class '{prop_class['name']}'.")
logger.warning(f"Unable to create property class '{prop_class['name']}'.", exc_info=True)
logger.warning(f"Unable to create property class '{prop_class['name']}'.")
overall_success = False

return last_modification_date, overall_success
Expand Down Expand Up @@ -908,7 +856,7 @@ def _add_cardinalities_to_resource_classes(
except BaseError:
err_msg = f"Unable to add cardinality '{qualified_propname}' to resource class {res_class['name']}."
print(f"WARNING: {err_msg}")
logger.warning(err_msg, exc_info=True)
logger.warning(err_msg)
overall_success = False

ontology_remote.lastModificationDate = last_modification_date
Expand Down Expand Up @@ -1032,7 +980,6 @@ def create_project(
project_remote, success = _create_project_on_server(
project_definition=project_definition,
con=con,
verbose=verbose,
)
if not success:
overall_success = False
Expand Down
37 changes: 0 additions & 37 deletions src/dsp_tools/commands/project/models/project.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,6 @@
* Call the ``read``-method on the instance
* Access the information that has been provided to the instance

UPDATE:
* You need an instance of an existing Project by reading an instance
* Change the attributes by assigning the new values
* Call the ``update`` method on the instance

In addition there is a static methods ``getAllProjects`` which returns a list of all projects
"""

from __future__ import annotations
Expand Down Expand Up @@ -73,9 +67,6 @@ class Project(Model):
read : DSP project information object
Read project data from an existing project

update : DSP project information object
Updates the changed attributes and returns the updated information from the project as it is in DSP

getAllprojects [static]: List of all projects
Returns a list of all projects available

Expand Down Expand Up @@ -351,34 +342,6 @@ def read(self) -> Project:
f"from DSP server."
)

def update(self) -> Project:
"""
Update the project information on the DSP with the modified data in this project instance

Returns: JSON object returned as response from DSP reflecting the update
"""
jsonobj = self._toJsonObj_update()
result = self._con.put(Project.IRI + quote_plus(self.iri), jsonobj)
return Project.fromJsonObj(self._con, result["project"])

def _toJsonObj_update(self) -> dict[str, str]:
tmp = {}
if self._shortcode is not None and "shortcode" in self._changed:
tmp["shortcode"] = self._shortcode
if self._shortname is not None and "shortname" in self._changed:
tmp["shortname"] = self._shortname
if self._longname is not None and "longname" in self._changed:
tmp["longname"] = self._longname
if not self._description.isEmpty() and "description" in self._changed:
tmp["description"] = self._description.toJsonObj()
if len(self._keywords) > 0 and "keywords" in self._changed:
tmp["keywords"] = self._keywords
if self._selfjoin is not None and "selfjoin" in self._changed:
tmp["selfjoin"] = self._selfjoin
if self._status is not None and "status" in self._changed:
tmp["status"] = self._status
return tmp

@staticmethod
def getAllProjects(con: Connection) -> list[Project]:
"""
Expand Down
3 changes: 2 additions & 1 deletion src/dsp_tools/utils/shared.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,8 +237,9 @@ def parse_json_input(project_file_as_path_or_parsed: Union[str, Path, dict[str,
Returns:
the parsed JSON object
"""
project_definition: dict[str, Any] = {}
if isinstance(project_file_as_path_or_parsed, dict):
project_definition: dict[str, Any] = project_file_as_path_or_parsed
project_definition = project_file_as_path_or_parsed
elif isinstance(project_file_as_path_or_parsed, (str, Path)) and Path(project_file_as_path_or_parsed).exists():
with open(project_file_as_path_or_parsed, encoding="utf-8") as f:
try:
Expand Down
121 changes: 0 additions & 121 deletions test/e2e/commands/project/test_project.py

This file was deleted.

2 changes: 0 additions & 2 deletions test/unittests/commands/project/test_create_project.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
"""unit tests for ontology creation"""

import json
from typing import Any

Expand Down