Skip to content

Commit

Permalink
Merge pull request #3506 from GNS3/fix/3505
Browse files Browse the repository at this point in the history
Use importlib instead of pkg_resources
  • Loading branch information
grossmj authored Aug 12, 2023
2 parents 01deb01 + e2168a3 commit 3a8b3e5
Show file tree
Hide file tree
Showing 5 changed files with 22 additions and 45 deletions.
10 changes: 0 additions & 10 deletions gns3/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,16 +30,6 @@
except Exception as e:
print("Fail update installation: {}".format(str(e)))


# WARNING
# Due to buggy user machines we choose to put this as the first loading modules
# otherwise the egg cache is initialized in his standard location and
# if is not writetable the application crash. It's the user fault
# because one day the user as used sudo to run an egg and break his
# filesystem permissions, but it's a common mistake.
from gns3.utils.get_resource import get_resource


import datetime
import traceback
import time
Expand Down
1 change: 1 addition & 0 deletions gns3/modules/iou/pages/iou_device_configuration_page.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ def __init__(self):
self.uiPrivateConfigToolButton.hide()

# location of the base config templates
# FIXME: this does not work
self._base_iou_l2_config_template = get_resource(os.path.join("configs", "iou_l2_base_startup-config.txt"))
self._base_iou_l3_config_template = get_resource(os.path.join("configs", "iou_l3_base_startup-config.txt"))
self._default_configs_dir = LocalServer.instance().localServerSettings()["configs_path"]
Expand Down
2 changes: 1 addition & 1 deletion gns3/registry/appliance.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def _check_config(self):
if self._appliance["registry_version"] > 7:
raise ApplianceError("Please update GNS3 in order to install this appliance")

with open(get_resource(os.path.join("schemas", "appliance.json"))) as f:
with open(get_resource("schemas/appliance.json")) as f:
schema = json.load(f)
v = jsonschema.Draft4Validator(schema)
try:
Expand Down
53 changes: 19 additions & 34 deletions gns3/utils/get_resource.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
# Copyright (C) 2014 GNS3 Technologies Inc.
# Copyright (C) 2023 GNS3 Technologies Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
Expand All @@ -15,50 +15,35 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

import sys
import os
import tempfile
import pkg_resources
import atexit
import logging

log = logging.getLogger(__name__)
import os
import sys

try:
egg_cache_dir = tempfile.mkdtemp()
pkg_resources.set_extraction_path(egg_cache_dir)
except ValueError:
# If the path is already set the module throw an error
pass
import importlib_resources
except ImportError:
from importlib import resources as importlib_resources


@atexit.register
def clean_egg_cache():
try:
import shutil
shutil.rmtree(egg_cache_dir, ignore_errors=True)
except Exception:
# We don't care if we can not cleanup
pass
from contextlib import ExitStack
resource_manager = ExitStack()
atexit.register(resource_manager.close)

log = logging.getLogger(__name__)


def get_resource(resource_name):
"""
Return a resource in current directory or in frozen package
"""

resource_path = None
if hasattr(sys, "frozen"):
resource_path = os.path.normpath(os.path.join(os.path.dirname(sys.executable), resource_name))
if sys.platform.startswith("darwin") and not os.path.exists(resource_path):
resource_path = os.path.normpath(os.path.join(os.path.dirname(sys.executable), "lib", resource_name))
elif not hasattr(sys, "frozen"):
if pkg_resources.resource_exists("gns3", resource_name):
try:
resource_path = pkg_resources.resource_filename("gns3", resource_name)
except pkg_resources.ExtractionError as e:
log.fatal(e)
sys.stderr.write(e)
sys.exit(1)
resource_path = os.path.normpath(resource_path)
else:
resource_path = os.path.dirname(os.path.realpath(__file__))
resource_path = os.path.join(resource_path, "..", "..", "resources", resource_name)
else:
ref = importlib_resources.files("gns3") / resource_name
path = resource_manager.enter_context(importlib_resources.as_file(ref))
if os.path.exists(path):
resource_path = os.path.normpath(path)
return resource_path
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@ sentry-sdk==1.29.2,<1.30
psutil==5.9.5
distro>=1.8.0
truststore>=0.7.0; python_version >= '3.10'
importlib-resources>=1.3; python_version <= '3.9'
setuptools>=60.8.1; python_version >= '3.7'
setuptools==59.6.0; python_version < '3.7' # v59.6.0 is the last version to support Python 3.6

0 comments on commit 3a8b3e5

Please sign in to comment.