#
- #
+ #
#
diff --git a/src/Mod/AddonManager/addonmanager_metadata.py b/src/Mod/AddonManager/addonmanager_metadata.py
new file mode 100644
index 0000000000..69e58a4a29
--- /dev/null
+++ b/src/Mod/AddonManager/addonmanager_metadata.py
@@ -0,0 +1,415 @@
+# SPDX-License-Identifier: LGPL-2.1-or-later
+# ***************************************************************************
+# * *
+# * Copyright (c) 2023 FreeCAD Project Association *
+# * *
+# * This file is part of FreeCAD. *
+# * *
+# * FreeCAD is free software: you can redistribute it and/or modify it *
+# * under the terms of the GNU Lesser General Public License as *
+# * published by the Free Software Foundation, either version 2.1 of the *
+# * License, or (at your option) any later version. *
+# * *
+# * FreeCAD is distributed in the hope that it will be useful, but *
+# * WITHOUT ANY WARRANTY; without even the implied warranty of *
+# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
+# * Lesser General Public License for more details. *
+# * *
+# * You should have received a copy of the GNU Lesser General Public *
+# * License along with FreeCAD. If not, see *
+# *
. *
+# * *
+# ***************************************************************************
+
+"""Classes for working with Addon metadata, as documented at
+https://wiki.FreeCAD.org/Package_metadata"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from enum import IntEnum, auto
+from typing import Tuple, Dict, List, Optional
+
+try:
+ # If this system provides a secure parser, use that:
+ import defusedxml.ElementTree as ET
+except ImportError:
+ # Otherwise fall back to the Python standard parser
+ import xml.etree.ElementTree as ET
+
+
+@dataclass
+class Contact:
+ name: str
+ email: str = ""
+
+
+@dataclass
+class License:
+ name: str
+ file: str = ""
+
+
+class UrlType(IntEnum):
+ bugtracker = 0
+ discussion = auto()
+ documentation = auto()
+ readme = auto()
+ repository = auto()
+ website = auto()
+
+ def __str__(self):
+ return f"{self.name}"
+
+
+@dataclass
+class Url:
+ location: str
+ type: UrlType
+ branch: str = ""
+
+
+class Version:
+ """Provide a more useful representation of Version information"""
+
+ def __init__(self, from_string: str = None, from_list=None):
+ """If from_string is a string, it is parsed to get the version. If from_list
+ exists (and no string was provided), it is treated as a version list of
+ [major:int, minor:int, patch:int, pre:str]"""
+ self.version_as_list = [0, 0, 0, ""]
+ if from_string is not None:
+ self._init_from_string(from_string)
+ elif from_list is not None:
+ self._init_from_list(from_list)
+
+ def _init_from_string(self, from_string: str):
+ """Find the first digit in the given string, and send that substring off for
+ parsing."""
+ counter = 0
+ for char in from_string:
+ if char.isdigit():
+ break
+ counter += 1
+ self._parse_string_to_tuple(from_string[counter:])
+
+ def _init_from_list(self, from_list):
+ for index, element in enumerate(from_list):
+ if index < 3:
+ self.version_as_list[index] = int(element)
+ elif index == 3:
+ self.version_as_list[index] = str(element)
+ else:
+ break
+
+ def _parse_string_to_tuple(self, from_string: str):
+ """We hand-parse only simple version strings, of the form 1.2.3suffix -- only
+ the first digit is required."""
+ splitter = from_string.split(".", 2)
+ counter = 0
+ for component in splitter:
+ try:
+ self.version_as_list[counter] = int(component)
+ counter += 1
+ except ValueError:
+ if counter == 0:
+ raise ValueError(f"Invalid version string {from_string}")
+ number, text = self._parse_final_entry(component)
+ self.version_as_list[counter] = number
+ self.version_as_list[3] = text
+
+ @staticmethod
+ def _parse_final_entry(final_string: str) -> Tuple[int, str]:
+ """The last value is permitted to contain both a number and a word, and needs
+ to be split"""
+ digits = ""
+ for c in final_string:
+ if c.isdigit():
+ digits += c
+ else:
+ break
+ return int(digits), final_string[len(digits) :]
+
+ def __repr__(self) -> str:
+ v = self.version_as_list
+ return f"{v[0]}.{v[1]}.{v[2]} {v[3]}"
+
+ def __eq__(self, other) -> bool:
+ return self.version_as_list == other.version_as_list
+
+ def __ne__(self, other) -> bool:
+ return not (self == other)
+
+ def __lt__(self, other) -> bool:
+ for a, b in zip(self.version_as_list, other.version_as_list):
+ if a != b:
+ return a < b
+ return False
+
+ def __gt__(self, other) -> bool:
+ if self.version_as_list == other.version_as_list:
+ return False
+ return not (self < other)
+
+ def __ge__(self, other) -> bool:
+ return self > other or self == other
+
+ def __le__(self, other) -> bool:
+ return self < other or self == other
+
+
+class DependencyType(IntEnum):
+ automatic = 0
+ internal = auto()
+ addon = auto()
+ python = auto()
+
+ def __str__(self):
+ return f"{self.name}"
+
+
+@dataclass
+class Dependency:
+ package: str
+ version_lt: str = ""
+ version_lte: str = ""
+ version_eq: str = ""
+ version_gte: str = ""
+ version_gt: str = ""
+ condition: str = ""
+ optional: bool = False
+ dependency_type: DependencyType = DependencyType.automatic
+
+
+@dataclass
+class GenericMetadata:
+ """Used to store unrecognized elements"""
+
+ contents: str = ""
+ attributes: Dict[str, str] = field(default_factory=dict)
+
+
+@dataclass
+class Metadata:
+ """A pure-python implementation of the Addon Manager's Metadata handling class"""
+
+ name: str = ""
+ version: Version = None
+ date: str = ""
+ description: str = ""
+ maintainer: List[Contact] = field(default_factory=list)
+ license: List[License] = field(default_factory=list)
+ url: List[Url] = field(default_factory=list)
+ author: List[Contact] = field(default_factory=list)
+ depend: List[Dependency] = field(default_factory=list)
+ conflict: List[Dependency] = field(default_factory=list)
+ replace: List[Dependency] = field(default_factory=list)
+ tag: List[str] = field(default_factory=list)
+ icon: str = ""
+ classname: str = ""
+ subdirectory: str = ""
+ file: List[str] = field(default_factory=list)
+ freecadmin: Version = None
+ freecadmax: Version = None
+ pythonmin: Version = None
+ content: Dict[str, List[Metadata]] = field(default_factory=dict) # Recursive def.
+
+
+def get_first_supported_freecad_version(metadata: Metadata) -> Optional[Version]:
+ """Look through all content items of this metadata element and determine what the
+ first version of freecad that ANY of the items support is. For example, if it
+ contains several workbenches, some of which require v0.20, and some 0.21, then
+ 0.20 is returned. Returns None if frecadmin is unset by any part of this object."""
+
+ current_earliest = metadata.freecadmin if metadata.freecadmin is not None else None
+ for content_class in metadata.content.values():
+ for content_item in content_class:
+ content_first = get_first_supported_freecad_version(content_item)
+ if content_first is not None:
+ if current_earliest is None:
+ current_earliest = content_first
+ else:
+ current_earliest = min(current_earliest, content_first)
+
+ return current_earliest
+
+
+class MetadataReader:
+ """Read metadata XML data and construct a Metadata object"""
+
+ @staticmethod
+ def from_file(filename: str) -> Metadata:
+ """A convenience function for loading the Metadata from a file"""
+ with open(filename, "rb") as f:
+ data = f.read()
+ return MetadataReader.from_bytes(data)
+
+ @staticmethod
+ def from_bytes(data: bytes) -> Metadata:
+ """Read XML data from bytes and use it to construct Metadata"""
+ element_tree = ET.fromstring(data)
+ return MetadataReader._process_element_tree(element_tree)
+
+ @staticmethod
+ def _process_element_tree(root: ET.Element) -> Metadata:
+ """Parse an element tree and convert it into a Metadata object"""
+ namespace = MetadataReader._determine_namespace(root)
+ return MetadataReader._create_node(namespace, root)
+
+ @staticmethod
+ def _determine_namespace(root: ET.Element) -> str:
+ accepted_namespaces = ["{https://wiki.freecad.org/Package_Metadata}", ""]
+ for ns in accepted_namespaces:
+ if root.tag == f"{ns}package":
+ return ns
+ raise RuntimeError("No 'package' element found in metadata file")
+
+ @staticmethod
+ def _parse_child_element(namespace: str, child: ET.Element, metadata: Metadata):
+ """Figure out what sort of metadata child represents, and add it to the
+ metadata object."""
+
+ tag = child.tag[len(namespace) :]
+ if tag in ["name", "date", "description", "icon", "classname", "subdirectory"]:
+ # Text-only elements
+ metadata.__dict__[tag] = child.text
+ elif tag in ["version", "freecadmin", "freecadmax", "pythonmin"]:
+ metadata.__dict__[tag] = Version(from_string=child.text)
+ elif tag in ["tag", "file"]:
+ # Lists of strings
+ if child.text:
+ metadata.__dict__[tag].append(child.text)
+ elif tag in ["maintainer", "author"]:
+ # Lists of contacts
+ metadata.__dict__[tag].append(MetadataReader._parse_contact(child))
+ elif tag == "license":
+ # List of licenses
+ metadata.license.append(MetadataReader._parse_license(child))
+ elif tag == "url":
+ # List of urls
+ metadata.url.append(MetadataReader._parse_url(child))
+ elif tag in ["depend", "conflict", "replace"]:
+ # Lists of dependencies
+ metadata.__dict__[tag].append(MetadataReader._parse_dependency(child))
+ elif tag == "content":
+ MetadataReader._parse_content(namespace, metadata, child)
+
+ @staticmethod
+ def _parse_contact(child: ET.Element) -> Contact:
+ email = child.attrib["email"] if "email" in child.attrib else ""
+ return Contact(name=child.text, email=email)
+
+ @staticmethod
+ def _parse_license(child: ET.Element) -> License:
+ file = child.attrib["file"] if "file" in child.attrib else ""
+ return License(name=child.text, file=file)
+
+ @staticmethod
+ def _parse_url(child: ET.Element) -> Url:
+ url_type = UrlType.website
+ branch = ""
+ if "type" in child.attrib and child.attrib["type"] in UrlType.__dict__:
+ url_type = UrlType[child.attrib["type"]]
+ if url_type == UrlType.repository:
+ branch = child.attrib["branch"] if "branch" in child.attrib else ""
+ return Url(location=child.text, type=url_type, branch=branch)
+
+ @staticmethod
+ def _parse_dependency(child: ET.Element) -> Dependency:
+ v_lt = child.attrib["version_lt"] if "version_lt" in child.attrib else ""
+ v_lte = child.attrib["version_lte"] if "version_lte" in child.attrib else ""
+ v_eq = child.attrib["version_eq"] if "version_eq" in child.attrib else ""
+ v_gte = child.attrib["version_gte"] if "version_gte" in child.attrib else ""
+ v_gt = child.attrib["version_gt"] if "version_gt" in child.attrib else ""
+ condition = child.attrib["condition"] if "condition" in child.attrib else ""
+ optional = (
+ "optional" in child.attrib and child.attrib["optional"].lower() == "true"
+ )
+ dependency_type = DependencyType.automatic
+ if "type" in child.attrib and child.attrib["type"] in DependencyType.__dict__:
+ dependency_type = DependencyType[child.attrib["type"]]
+ return Dependency(
+ child.text,
+ version_lt=v_lt,
+ version_lte=v_lte,
+ version_eq=v_eq,
+ version_gte=v_gte,
+ version_gt=v_gt,
+ condition=condition,
+ optional=optional,
+ dependency_type=dependency_type,
+ )
+
+ @staticmethod
+ def _parse_content(namespace: str, metadata: Metadata, root: ET.Element):
+ """Given a content node, loop over its children, and if they are a recognized
+ element type, recurse into each one to parse it."""
+ known_content_types = ["workbench", "macro", "preferencepack"]
+ for child in root:
+ content_type = child.tag[len(namespace) :]
+ if content_type in known_content_types:
+ if content_type not in metadata.content:
+ metadata.content[content_type] = []
+ metadata.content[content_type].append(
+ MetadataReader._create_node(namespace, child)
+ )
+
+ @staticmethod
+ def _create_node(namespace, child) -> Metadata:
+ new_content_item = Metadata()
+ for content_child in child:
+ MetadataReader._parse_child_element(
+ namespace, content_child, new_content_item
+ )
+ return new_content_item
+
+
+class MetadataWriter:
+ """Utility class for serializing a Metadata object into the package.xml standard
+ XML file."""
+
+ @staticmethod
+ def write(metadata: Metadata, path: str):
+ """Write the metadata to a file located at path. Overwrites the file if it
+ exists. Raises OSError if writing fails."""
+ tree = MetadataWriter._create_tree_from_metadata(metadata)
+ tree.write(path)
+
+ @staticmethod
+ def _create_tree_from_metadata(metadata: Metadata) -> ET.ElementTree:
+ """Create the XML ElementTree representation of the given Metadata object."""
+ tree = ET.ElementTree()
+ root = tree.getroot()
+ root.attrib["xmlns"] = "https://wiki.freecad.org/Package_Metadata"
+ for key, value in metadata.__dict__.items():
+ if isinstance(value, str):
+ node = ET.SubElement(root, key)
+ node.text = value
+ else:
+ MetadataWriter._create_list_node(metadata, key, root)
+ return tree
+
+ @staticmethod
+ def _create_list_node(metadata: Metadata, key: str, root: ET.Element):
+ for item in metadata.__dict__[key]:
+ node = ET.SubElement(root, key)
+ if key in ["maintainer", "author"]:
+ if item.email:
+ node.attrib["email"] = item.email
+ node.text = item.name
+ elif key == "license":
+ if item.file:
+ node.attrib["file"] = item.file
+ node.text = item.name
+ elif key == "url":
+ if item.branch:
+ node.attrib["branch"] = item.branch
+ node.attrib["type"] = str(item.type)
+ node.text = item.location
+ elif key in ["depend", "conflict", "replace"]:
+ for dep_key, dep_value in item.__dict__.items():
+ if isinstance(dep_value, str) and dep_value:
+ node.attrib[dep_key] = dep_value
+ elif isinstance(dep_value, bool):
+ node.attrib[dep_key] = "True" if dep_value else "False"
+ elif isinstance(dep_value, DependencyType):
+ node.attrib[dep_key] = str(dep_value)
diff --git a/src/Mod/AddonManager/addonmanager_utilities.py b/src/Mod/AddonManager/addonmanager_utilities.py
index f148932419..af959bd7ac 100644
--- a/src/Mod/AddonManager/addonmanager_utilities.py
+++ b/src/Mod/AddonManager/addonmanager_utilities.py
@@ -35,12 +35,15 @@ from typing import Optional, Any
from urllib.parse import urlparse
-from PySide import QtCore, QtWidgets
+try:
+ from PySide import QtCore, QtWidgets
+except ImportError:
+ QtCore = None
+ QtWidgets = None
-import FreeCAD
+import addonmanager_freecad_interface as fci
-if FreeCAD.GuiUp:
- import FreeCADGui
+if fci.FreeCADGui:
# If the GUI is up, we can use the NetworkManager to handle our downloads. If there is no event
# loop running this is not possible, so fall back to requests (if available), or the native
@@ -60,7 +63,7 @@ else:
# @{
-translate = FreeCAD.Qt.translate
+translate = fci.translate
class ProcessInterrupted(RuntimeError):
@@ -116,7 +119,7 @@ def update_macro_details(old_macro, new_macro):
"""
if old_macro.on_git and new_macro.on_git:
- FreeCAD.Console.PrintLog(
+ fci.Console.PrintLog(
f'The macro "{old_macro.name}" is present twice in github, please report'
)
# We don't report macros present twice on the wiki because a link to a
@@ -132,7 +135,7 @@ def remove_directory_if_empty(dir_to_remove):
"""Remove the directory if it is empty, with one exception: the directory returned by
FreeCAD.getUserMacroDir(True) will not be removed even if it is empty."""
- if dir_to_remove == FreeCAD.getUserMacroDir(True):
+ if dir_to_remove == fci.DataPaths().macro_dir:
return
if not os.listdir(dir_to_remove):
os.rmdir(dir_to_remove)
@@ -140,9 +143,12 @@ def remove_directory_if_empty(dir_to_remove):
def restart_freecad():
"""Shuts down and restarts FreeCAD"""
+
+ if not QtCore or not QtWidgets:
+ return
args = QtWidgets.QApplication.arguments()[1:]
- if FreeCADGui.getMainWindow().close():
+ if fci.FreeCADGui.getMainWindow().close():
QtCore.QProcess.startDetached(
QtWidgets.QApplication.applicationFilePath(), args
)
@@ -156,7 +162,7 @@ def get_zip_url(repo):
return f"{repo.url}/archive/{repo.branch}.zip"
if parsed_url.netloc in ["gitlab.com", "framagit.org", "salsa.debian.org"]:
return f"{repo.url}/-/archive/{repo.branch}/{repo.name}-{repo.branch}.zip"
- FreeCAD.Console.PrintLog(
+ fci.Console.PrintLog(
"Debug: addonmanager_utilities.get_zip_url: Unknown git host fetching zip URL:"
+ parsed_url.netloc
+ "\n"
@@ -185,7 +191,7 @@ def construct_git_url(repo, filename):
return f"{repo.url}/raw/{repo.branch}/{filename}"
if parsed_url.netloc in ["gitlab.com", "framagit.org", "salsa.debian.org"]:
return f"{repo.url}/-/raw/{repo.branch}/{filename}"
- FreeCAD.Console.PrintLog(
+ fci.Console.PrintLog(
"Debug: addonmanager_utilities.construct_git_url: Unknown git host:"
+ parsed_url.netloc
+ f" for file {filename}\n"
@@ -215,7 +221,7 @@ def get_desc_regex(repo):
return r'
'
- FreeCAD.Console.PrintLog(
+ fci.Console.PrintLog(
"Debug: addonmanager_utilities.get_desc_regex: Unknown git host:",
repo.url,
"\n",
@@ -231,7 +237,7 @@ def get_readme_html_url(repo):
return f"{repo.url}/blob/{repo.branch}/README.md"
if parsed_url.netloc in ["gitlab.com", "salsa.debian.org", "framagit.org"]:
return f"{repo.url}/-/blob/{repo.branch}/README.md"
- FreeCAD.Console.PrintLog(
+ fci.Console.PrintLog(
"Unrecognized git repo location '' -- guessing it is a GitLab instance..."
)
return f"{repo.url}/-/blob/{repo.branch}/README.md"
@@ -239,7 +245,7 @@ def get_readme_html_url(repo):
def is_darkmode() -> bool:
"""Heuristics to determine if we are in a darkmode stylesheet"""
- pl = FreeCADGui.getMainWindow().palette()
+ pl = fci.FreeCADGui.getMainWindow().palette()
return pl.color(pl.Background).lightness() < 128
@@ -296,7 +302,7 @@ def get_macro_version_from_file(filename: str) -> str:
if date:
return date
# pylint: disable=line-too-long,consider-using-f-string
- FreeCAD.Console.PrintWarning(
+ fci.Console.PrintWarning(
translate(
"AddonsInstaller",
"Macro {} specified '__version__ = __date__' prior to setting a value for __date__".format(
@@ -315,11 +321,11 @@ def update_macro_installation_details(repo) -> None:
"""Determine if a given macro is installed, either in its plain name,
or prefixed with "Macro_" """
if repo is None or not hasattr(repo, "macro") or repo.macro is None:
- FreeCAD.Console.PrintLog("Requested macro details for non-macro object\n")
+ fci.Console.PrintLog("Requested macro details for non-macro object\n")
return
- test_file_one = os.path.join(FreeCAD.getUserMacroDir(True), repo.macro.filename)
+ test_file_one = os.path.join(fci.DataPaths().macro_dir, repo.macro.filename)
test_file_two = os.path.join(
- FreeCAD.getUserMacroDir(True), "Macro_" + repo.macro.filename
+ fci.DataPaths().macro_dir, "Macro_" + repo.macro.filename
)
if os.path.exists(test_file_one):
repo.updated_timestamp = os.path.getmtime(test_file_one)
@@ -341,10 +347,6 @@ def is_float(element: Any) -> bool:
except ValueError:
return False
-
-# @}
-
-
def get_python_exe() -> str:
"""Find Python. In preference order
A) The value of the PythonExecutableForPip user preference
@@ -352,9 +354,9 @@ def get_python_exe() -> str:
C) The executable located in the same bin directory as FreeCAD and called "python"
D) The result of a shutil search for your system's "python3" executable
E) The result of a shutil search for your system's "python" executable"""
- prefs = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Addons")
+ prefs = fci.ParamGet("User parameter:BaseApp/Preferences/Addons")
python_exe = prefs.GetString("PythonExecutableForPip", "Not set")
- fc_dir = FreeCAD.getHomePath()
+ fc_dir = fci.DataPaths().home_dir
if not python_exe or python_exe == "Not set" or not os.path.exists(python_exe):
python_exe = os.path.join(fc_dir, "bin", "python3")
if "Windows" in platform.system():
@@ -383,36 +385,37 @@ def get_pip_target_directory():
# Get the default location to install new pip packages
major, minor, _ = platform.python_version_tuple()
vendor_path = os.path.join(
- FreeCAD.getUserAppDataDir(), "AdditionalPythonPackages", f"py{major}{minor}"
+ fci.DataPaths().mod_dir, "..", "AdditionalPythonPackages", f"py{major}{minor}"
)
return vendor_path
def get_cache_file_name(file: str) -> str:
"""Get the full path to a cache file with a given name."""
- cache_path = FreeCAD.getUserCachePath()
+ cache_path = fci.DataPaths().cache_dir
am_path = os.path.join(cache_path, "AddonManager")
os.makedirs(am_path, exist_ok=True)
return os.path.join(am_path, file)
-def blocking_get(url: str, method=None) -> str:
+def blocking_get(url: str, method=None) -> bytes:
"""Wrapper around three possible ways of accessing data, depending on the current run mode and
Python installation. Blocks until complete, and returns the text results of the call if it
succeeded, or an empty string if it failed, or returned no data. The method argument is
provided mainly for testing purposes."""
- p = ""
- if FreeCAD.GuiUp and method is None or method == "networkmanager":
+ p = b""
+ if fci.FreeCADGui and method is None or method == "networkmanager":
NetworkManager.InitializeNetworkManager()
p = NetworkManager.AM_NETWORK_MANAGER.blocking_get(url)
+ p = p.data()
elif requests and method is None or method == "requests":
response = requests.get(url)
if response.status_code == 200:
- p = response.text
+ p = response.content
else:
ctx = ssl.create_default_context()
with urllib.request.urlopen(url, context=ctx) as f:
- p = f.read().decode("utf-8")
+ p = f.read()
return p
diff --git a/src/Mod/AddonManager/addonmanager_workers_installation.py b/src/Mod/AddonManager/addonmanager_workers_installation.py
index 125c2c21f5..ddc5580f1c 100644
--- a/src/Mod/AddonManager/addonmanager_workers_installation.py
+++ b/src/Mod/AddonManager/addonmanager_workers_installation.py
@@ -40,6 +40,7 @@ from PySide import QtCore
import FreeCAD
import addonmanager_utilities as utils
+from addonmanager_metadata import MetadataReader
from Addon import Addon
import NetworkManager
@@ -166,7 +167,7 @@ class UpdateMetadataCacheWorker(QtCore.QThread):
new_xml_file = os.path.join(package_cache_directory, "package.xml")
with open(new_xml_file, "wb") as f:
f.write(data.data())
- metadata = FreeCAD.Metadata(new_xml_file)
+ metadata = MetadataReader.from_file(new_xml_file)
repo.set_metadata(metadata)
FreeCAD.Console.PrintLog(f"Downloaded package.xml for {repo.name}\n")
self.status_message.emit(
@@ -177,21 +178,21 @@ class UpdateMetadataCacheWorker(QtCore.QThread):
# Grab a new copy of the icon as well: we couldn't enqueue this earlier because
# we didn't know the path to it, which is stored in the package.xml file.
- icon = metadata.Icon
+ icon = metadata.icon
if not icon:
# If there is no icon set for the entire package, see if there are
# any workbenches, which are required to have icons, and grab the first
# one we find:
- content = repo.metadata.Content
+ content = repo.metadata.content
if "workbench" in content:
wb = content["workbench"][0]
- if wb.Icon:
- if wb.Subdirectory:
- subdir = wb.Subdirectory
+ if wb.icon:
+ if wb.subdirectory:
+ subdir = wb.subdirectory
else:
- subdir = wb.Name
- repo.Icon = subdir + wb.Icon
- icon = repo.Icon
+ subdir = wb.name
+ repo.icon = subdir + wb.icon
+ icon = repo.icon
icon_url = utils.construct_git_url(repo, icon)
index = NetworkManager.AM_NETWORK_MANAGER.submit_unmonitored_get(icon_url)
diff --git a/src/Mod/AddonManager/addonmanager_workers_startup.py b/src/Mod/AddonManager/addonmanager_workers_startup.py
index 230787db7c..d7b7cac30b 100644
--- a/src/Mod/AddonManager/addonmanager_workers_startup.py
+++ b/src/Mod/AddonManager/addonmanager_workers_startup.py
@@ -43,6 +43,7 @@ from addonmanager_macro import Macro
from Addon import Addon
import NetworkManager
from addonmanager_git import initialize_git, GitFailed
+from addonmanager_metadata import MetadataReader
translate = FreeCAD.Qt.translate
@@ -195,7 +196,7 @@ class CreateAddonListWorker(QtCore.QThread):
md_file = os.path.join(addondir, "package.xml")
if os.path.isfile(md_file):
repo.load_metadata_file(md_file)
- repo.installed_version = repo.metadata.Version
+ repo.installed_version = repo.metadata.version
repo.updated_timestamp = os.path.getmtime(md_file)
repo.verify_url_and_branch(addon["url"], addon["branch"])
@@ -238,7 +239,7 @@ class CreateAddonListWorker(QtCore.QThread):
md_file = os.path.join(addondir, "package.xml")
if os.path.isfile(md_file):
repo.load_metadata_file(md_file)
- repo.installed_version = repo.metadata.Version
+ repo.installed_version = repo.metadata.version
repo.updated_timestamp = os.path.getmtime(md_file)
repo.verify_url_and_branch(url, branch)
@@ -457,7 +458,7 @@ class LoadPackagesFromCacheWorker(QtCore.QThread):
if os.path.isfile(repo_metadata_cache_path):
try:
repo.load_metadata_file(repo_metadata_cache_path)
- repo.installed_version = repo.metadata.Version
+ repo.installed_version = repo.metadata.version
repo.updated_timestamp = os.path.getmtime(
repo_metadata_cache_path
)
@@ -644,12 +645,12 @@ class UpdateChecker:
return
package.updated_timestamp = os.path.getmtime(installed_metadata_file)
try:
- installed_metadata = FreeCAD.Metadata(installed_metadata_file)
- package.installed_version = installed_metadata.Version
- # Packages are considered up-to-date if the metadata version matches. Authors
- # should update their version string when they want the addon manager to alert
- # users of a new version.
- if package.metadata.Version != installed_metadata.Version:
+ installed_metadata = MetadataReader.from_file(installed_metadata_file)
+ package.installed_version = installed_metadata.version
+ # Packages are considered up-to-date if the metadata version matches.
+ # Authors should update their version string when they want the addon
+ # manager to alert users of a new version.
+ if package.metadata.version != installed_metadata.version:
package.set_status(Addon.Status.UPDATE_AVAILABLE)
else:
package.set_status(Addon.Status.NO_UPDATE_AVAILABLE)
diff --git a/src/Mod/AddonManager/addonmanager_workers_utility.py b/src/Mod/AddonManager/addonmanager_workers_utility.py
index 08a1bbed44..e25912c76f 100644
--- a/src/Mod/AddonManager/addonmanager_workers_utility.py
+++ b/src/Mod/AddonManager/addonmanager_workers_utility.py
@@ -27,7 +27,7 @@ from typing import Optional
import FreeCAD
from PySide import QtCore
-import NetworkManager
+import addonmanager_utilities as utils
translate = FreeCAD.Qt.translate
@@ -67,7 +67,7 @@ class ConnectionChecker(QtCore.QThread):
"""The main work of this object: returns the decoded result of the connection request, or
None if the request failed"""
url = "https://api.github.com/zen"
- result = NetworkManager.AM_NETWORK_MANAGER.blocking_get(url)
+ result = utils.blocking_get(url)
if result:
- return result.data().decode("utf8")
+ return result.decode("utf8")
return None
diff --git a/src/Mod/AddonManager/package_details.py b/src/Mod/AddonManager/package_details.py
index 361ccb4b20..5a7822994d 100644
--- a/src/Mod/AddonManager/package_details.py
+++ b/src/Mod/AddonManager/package_details.py
@@ -31,9 +31,9 @@ from PySide import QtCore, QtGui, QtWidgets
import addonmanager_freecad_interface as fci
import addonmanager_utilities as utils
+from addonmanager_metadata import Version, UrlType, get_first_supported_freecad_version
from addonmanager_workers_startup import GetMacroDetailsWorker, CheckSingleUpdateWorker
from Addon import Addon
-import NetworkManager
from change_branch import ChangeBranchDialog
have_git = False
@@ -210,7 +210,7 @@ class PackageDetails(QtWidgets.QWidget):
).format(repo.branch)
+ " "
)
- installed_version_string += repo.metadata.Version
+ installed_version_string += str(repo.metadata.version)
installed_version_string += "."
elif repo.macro and repo.macro.version:
installed_version_string += (
@@ -385,7 +385,7 @@ class PackageDetails(QtWidgets.QWidget):
else:
self.ui.labelWarningInfo.hide()
- def requires_newer_freecad(self) -> Optional[str]:
+ def requires_newer_freecad(self) -> Optional[Version]:
"""If the current package is not installed, returns the first supported version of
FreeCAD, if one is set, or None if no information is available (or if the package is
already installed)."""
@@ -396,19 +396,13 @@ class PackageDetails(QtWidgets.QWidget):
# it's possible that this package actually provides versions of itself
# for newer and older versions
- first_supported_version = (
- self.repo.metadata.getFirstSupportedFreeCADVersion()
+ first_supported_version = get_first_supported_freecad_version(
+ self.repo.metadata
)
if first_supported_version is not None:
- required_version = first_supported_version.split(".")
- fc_major = int(fci.Version()[0])
- fc_minor = int(fci.Version()[1])
-
- if int(required_version[0]) > fc_major:
+ fc_version = Version(from_list=fci.Version())
+ if first_supported_version > fc_version:
return first_supported_version
- if int(required_version[0]) == fc_major and len(required_version) > 1:
- if int(required_version[1]) > fc_minor:
- return first_supported_version
return None
def set_change_branch_button_state(self):
@@ -463,8 +457,8 @@ class PackageDetails(QtWidgets.QWidget):
self.ui.webView.load(QtCore.QUrl(url))
self.ui.urlBar.setText(url)
else:
- readme_data = NetworkManager.AM_NETWORK_MANAGER.blocking_get(url)
- text = readme_data.data().decode("utf8")
+ readme_data = utils.blocking_get(url)
+ text = readme_data.decode("utf8")
self.ui.textBrowserReadMe.setHtml(text)
def show_package(self, repo: Addon) -> None:
@@ -472,10 +466,9 @@ class PackageDetails(QtWidgets.QWidget):
readme_url = None
if repo.metadata:
- urls = repo.metadata.Urls
- for url in urls:
- if url["type"] == "readme":
- readme_url = url["location"]
+ for url in repo.metadata.url:
+ if url.type == UrlType.readme:
+ readme_url = url.location
break
if not readme_url:
readme_url = utils.get_readme_html_url(repo)
@@ -483,8 +476,8 @@ class PackageDetails(QtWidgets.QWidget):
self.ui.webView.load(QtCore.QUrl(readme_url))
self.ui.urlBar.setText(readme_url)
else:
- readme_data = NetworkManager.AM_NETWORK_MANAGER.blocking_get(readme_url)
- text = readme_data.data().decode("utf8")
+ readme_data = utils.blocking_get(readme_url)
+ text = readme_data.decode("utf8")
self.ui.textBrowserReadMe.setHtml(text)
def show_macro(self, repo: Addon) -> None:
@@ -518,8 +511,8 @@ class PackageDetails(QtWidgets.QWidget):
)
else:
if url:
- readme_data = NetworkManager.AM_NETWORK_MANAGER.blocking_get(url)
- text = readme_data.data().decode("utf8")
+ readme_data = utils.blocking_get(url)
+ text = readme_data.decode("utf8")
self.ui.textBrowserReadMe.setHtml(text)
else:
self.ui.textBrowserReadMe.setHtml(
@@ -606,7 +599,8 @@ class PackageDetails(QtWidgets.QWidget):
):
self.timeout.stop()
if load_succeeded:
- # It says it succeeded, but it might have only succeeded in loading a "Page not found" page!
+ # It says it succeeded, but it might have only succeeded in loading a
+ # "Page not found" page!
title = self.ui.webView.title()
path_components = url.path().split("/")
expected_content = path_components[-1]
@@ -643,7 +637,8 @@ class PackageDetails(QtWidgets.QWidget):
change_branch_dialog.exec()
def enable_clicked(self) -> None:
- """Called by the Enable button, enables this Addon and updates GUI to reflect that status."""
+ """Called by the Enable button, enables this Addon and updates GUI to reflect
+ that status."""
self.repo.enable()
self.repo.set_status(Addon.Status.PENDING_RESTART)
self.set_disable_button_state()
@@ -660,7 +655,8 @@ class PackageDetails(QtWidgets.QWidget):
self.ui.labelWarningInfo.setStyleSheet("color:" + utils.bright_color_string())
def disable_clicked(self) -> None:
- """Called by the Disable button, disables this Addon and updates the GUI to reflect that status."""
+ """Called by the Disable button, disables this Addon and updates the GUI to
+ reflect that status."""
self.repo.disable()
self.repo.set_status(Addon.Status.PENDING_RESTART)
self.set_disable_button_state()
@@ -679,7 +675,8 @@ class PackageDetails(QtWidgets.QWidget):
)
def branch_changed(self, name: str) -> None:
- """Displays a dialog confirming the branch changed, and tries to access the metadata file from that branch."""
+ """Displays a dialog confirming the branch changed, and tries to access the
+ metadata file from that branch."""
QtWidgets.QMessageBox.information(
self,
translate("AddonsInstaller", "Success"),
@@ -693,12 +690,14 @@ class PackageDetails(QtWidgets.QWidget):
path_to_metadata = os.path.join(basedir, "Mod", self.repo.name, "package.xml")
if os.path.isfile(path_to_metadata):
self.repo.load_metadata_file(path_to_metadata)
- self.repo.installed_version = self.repo.metadata.Version
+ self.repo.installed_version = self.repo.metadata.version
else:
self.repo.repo_type = Addon.Kind.WORKBENCH
self.repo.metadata = None
self.repo.installed_version = None
- self.repo.updated_timestamp = QtCore.QDateTime.currentDateTime().toSecsSinceEpoch()
+ self.repo.updated_timestamp = (
+ QtCore.QDateTime.currentDateTime().toSecsSinceEpoch()
+ )
self.repo.branch = name
self.repo.set_status(Addon.Status.PENDING_RESTART)
@@ -717,19 +716,24 @@ class PackageDetails(QtWidgets.QWidget):
if HAS_QTWEBENGINE:
class RestrictedWebPage(QtWebEngineWidgets.QWebEnginePage):
- """A class that follows links to FreeCAD wiki pages, but opens all other clicked links in the system web browser"""
+ """A class that follows links to FreeCAD wiki pages, but opens all other
+ clicked links in the system web browser"""
def __init__(self, parent):
super().__init__(parent)
- self.settings().setAttribute(QtWebEngineWidgets.QWebEngineSettings.ErrorPageEnabled, False)
+ self.settings().setAttribute(
+ QtWebEngineWidgets.QWebEngineSettings.ErrorPageEnabled, False
+ )
self.stored_url = None
def acceptNavigationRequest(self, requested_url, _type, isMainFrame):
- """A callback for navigation requests: this widget will only display navigation requests to the
- FreeCAD Wiki (for translation purposes) -- anything else will open in a new window.
+ """A callback for navigation requests: this widget will only display
+ navigation requests to the FreeCAD Wiki (for translation purposes) --
+ anything else will open in a new window.
"""
if _type == QtWebEngineWidgets.QWebEnginePage.NavigationTypeLinkClicked:
- # See if the link is to a FreeCAD Wiki page -- if so, follow it, otherwise ask the OS to open it
+ # See if the link is to a FreeCAD Wiki page -- if so, follow it,
+ # otherwise ask the OS to open it
if (
requested_url.host() == "wiki.freecad.org"
or requested_url.host() == "wiki.freecadweb.org"
@@ -744,9 +748,9 @@ if HAS_QTWEBENGINE:
return super().acceptNavigationRequest(requested_url, _type, isMainFrame)
def javaScriptConsoleMessage(self, level, message, lineNumber, _):
- """Handle JavaScript console messages by optionally outputting them to the FreeCAD Console. This
- must be manually enabled in this Python file by setting the global show_javascript_console_output
- to true."""
+ """Handle JavaScript console messages by optionally outputting them to
+ the FreeCAD Console. This must be manually enabled in this Python file by
+ setting the global show_javascript_console_output to true."""
global show_javascript_console_output
if show_javascript_console_output:
tag = translate("AddonsInstaller", "Page JavaScript reported")
@@ -834,7 +838,9 @@ class Ui_PackageDetails(object):
self.verticalLayout_2.addWidget(self.labelPackageDetails)
self.labelInstallationLocation = QtWidgets.QLabel(PackageDetails)
- self.labelInstallationLocation.setTextInteractionFlags(QtCore.Qt.TextSelectableByMouse)
+ self.labelInstallationLocation.setTextInteractionFlags(
+ QtCore.Qt.TextSelectableByMouse
+ )
self.labelInstallationLocation.hide()
self.verticalLayout_2.addWidget(self.labelInstallationLocation)
@@ -844,7 +850,9 @@ class Ui_PackageDetails(object):
self.verticalLayout_2.addWidget(self.labelWarningInfo)
- sizePolicy1 = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
+ sizePolicy1 = QtWidgets.QSizePolicy(
+ QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding
+ )
sizePolicy1.setHorizontalStretch(0)
sizePolicy1.setVerticalStretch(0)
@@ -909,7 +917,9 @@ class Ui_PackageDetails(object):
QtCore.QCoreApplication.translate("AddonsInstaller", "Update", None)
)
self.buttonCheckForUpdate.setText(
- QtCore.QCoreApplication.translate("AddonsInstaller", "Check for Update", None)
+ QtCore.QCoreApplication.translate(
+ "AddonsInstaller", "Check for Update", None
+ )
)
self.buttonExecute.setText(
QtCore.QCoreApplication.translate("AddonsInstaller", "Run Macro", None)
@@ -933,7 +943,7 @@ class Ui_PackageDetails(object):
"
"
+ QtCore.QCoreApplication.translate(
"AddonsInstaller",
- "QtWebEngine Python bindings not installed -- using fallback README display. See Report View for details and installation instructions.",
+ "QtWebEngine Python bindings not installed -- using fallback README display.",
None,
)
+ "
"
diff --git a/src/Mod/AddonManager/package_list.py b/src/Mod/AddonManager/package_list.py
index 19a9449ce6..c7615e1e29 100644
--- a/src/Mod/AddonManager/package_list.py
+++ b/src/Mod/AddonManager/package_list.py
@@ -36,12 +36,14 @@ from compact_view import Ui_CompactView
from expanded_view import Ui_ExpandedView
import addonmanager_utilities as utils
+from addonmanager_metadata import get_first_supported_freecad_version
translate = FreeCAD.Qt.translate
# pylint: disable=too-few-public-methods
+
class ListDisplayStyle(IntEnum):
"""The display mode of the list"""
@@ -345,7 +347,8 @@ class PackageListItemDelegate(QtWidgets.QStyledItemDelegate):
self.displayStyle = style
def sizeHint(self, _option, index):
- """Attempt to figure out the correct height for the widget based on its current contents."""
+ """Attempt to figure out the correct height for the widget based on its
+ current contents."""
self.update_content(index)
return self.widget.sizeHint()
@@ -365,8 +368,8 @@ class PackageListItemDelegate(QtWidgets.QStyledItemDelegate):
if self.displayStyle == ListDisplayStyle.EXPANDED:
self.widget.ui.labelTags.setText("")
if repo.metadata:
- self.widget.ui.labelDescription.setText(repo.metadata.Description)
- self.widget.ui.labelVersion.setText(f"
v{repo.metadata.Version}")
+ self.widget.ui.labelDescription.setText(repo.metadata.description)
+ self.widget.ui.labelVersion.setText(f"
v{repo.metadata.version}")
if self.displayStyle == ListDisplayStyle.EXPANDED:
self._setup_expanded_package(repo)
elif repo.macro and repo.macro.parsed:
@@ -387,18 +390,18 @@ class PackageListItemDelegate(QtWidgets.QStyledItemDelegate):
def _setup_expanded_package(self, repo: Addon):
"""Set up the display for a package in expanded view"""
- maintainers = repo.metadata.Maintainer
+ maintainers = repo.metadata.maintainer
maintainers_string = ""
if len(maintainers) == 1:
maintainers_string = (
translate("AddonsInstaller", "Maintainer")
- + f": {maintainers[0]['name']} <{maintainers[0]['email']}>"
+ + f": {maintainers[0].name} <{maintainers[0].email}>"
)
elif len(maintainers) > 1:
n = len(maintainers)
maintainers_string = translate("AddonsInstaller", "Maintainers:", "", n)
for maintainer in maintainers:
- maintainers_string += f"\n{maintainer['name']} <{maintainer['email']}>"
+ maintainers_string += f"\n{maintainer.name} <{maintainer.email}>"
self.widget.ui.labelMaintainer.setText(maintainers_string)
if repo.tags:
self.widget.ui.labelTags.setText(
@@ -435,8 +438,10 @@ class PackageListItemDelegate(QtWidgets.QStyledItemDelegate):
else:
self.widget.ui.labelMaintainer.setText("")
- def get_compact_update_string(self, repo: Addon) -> str:
- """Get a single-line string listing details about the installed version and date"""
+ @staticmethod
+ def get_compact_update_string(repo: Addon) -> str:
+ """Get a single-line string listing details about the installed version and
+ date"""
result = ""
if repo.status() == Addon.Status.UNCHECKED:
@@ -460,8 +465,10 @@ class PackageListItemDelegate(QtWidgets.QStyledItemDelegate):
return result
- def get_expanded_update_string(self, repo: Addon) -> str:
- """Get a multi-line string listing details about the installed version and date"""
+ @staticmethod
+ def get_expanded_update_string(repo: Addon) -> str:
+ """Get a multi-line string listing details about the installed version and
+ date"""
result = ""
@@ -471,7 +478,7 @@ class PackageListItemDelegate(QtWidgets.QStyledItemDelegate):
installed_version_string = (
"
" + translate("AddonsInstaller", "Installed version") + ": "
)
- installed_version_string += repo.installed_version
+ installed_version_string += str(repo.installed_version)
else:
installed_version_string = "
" + translate(
"AddonsInstaller", "Unknown version"
@@ -493,7 +500,7 @@ class PackageListItemDelegate(QtWidgets.QStyledItemDelegate):
available_version_string = (
"
" + translate("AddonsInstaller", "Available version") + ": "
)
- available_version_string += repo.metadata.Version
+ available_version_string += str(repo.metadata.version)
if repo.status() == Addon.Status.UNCHECKED:
result = translate("AddonsInstaller", "Installed")
@@ -529,8 +536,8 @@ class PackageListItemDelegate(QtWidgets.QStyledItemDelegate):
option: QtWidgets.QStyleOptionViewItem,
_: QtCore.QModelIndex,
):
- """Main paint function: renders this widget into a given rectangle, successively drawing
- all of its children."""
+ """Main paint function: renders this widget into a given rectangle,
+ successively drawing all of its children."""
painter.save()
self.widget.resize(option.rect.size())
painter.translate(option.rect.topLeft())
@@ -641,7 +648,7 @@ class PackageListFilter(QtCore.QSortFilterProxyModel):
# it's possible that this package actually provides versions of itself
# for newer and older versions
- first_supported_version = data.metadata.getFirstSupportedFreeCADVersion()
+ first_supported_version = get_first_supported_freecad_version(data.metadata)
if first_supported_version is not None:
required_version = first_supported_version.split(".")
fc_major = int(FreeCAD.Version()[0])
@@ -692,9 +699,11 @@ class PackageListFilter(QtCore.QSortFilterProxyModel):
return True
return False
+
# pylint: disable=attribute-defined-outside-init, missing-function-docstring
-class Ui_PackageList():
+
+class Ui_PackageList:
"""The contents of the PackageList widget"""
def setupUi(self, form):