pathlib cleanups

This commit is contained in:
Philip Ridout 2019-03-10 21:01:39 +00:00
parent 1fe56bc089
commit 50598e9058
23 changed files with 49 additions and 52 deletions

View File

@ -39,8 +39,8 @@ def deploy_zipfile(app_root_path, zip_name):
:return: None
"""
zip_path = app_root_path / zip_name
web_zip = ZipFile(str(zip_path))
web_zip.extractall(str(app_root_path))
web_zip = ZipFile(zip_path)
web_zip.extractall(app_root_path)
def download_sha256():

View File

@ -317,8 +317,7 @@ def set_up_logging(log_path):
"""
create_paths(log_path, do_not_log=True)
file_path = log_path / 'openlp.log'
# TODO: FileHandler accepts a Path object in Py3.6
logfile = logging.FileHandler(str(file_path), 'w', encoding='UTF-8')
logfile = logging.FileHandler(file_path, 'w', encoding='UTF-8')
logfile.setFormatter(logging.Formatter('%(asctime)s %(threadName)s %(name)-55s %(levelname)-8s %(message)s'))
log.addHandler(logfile)
if log.isEnabledFor(logging.DEBUG):
@ -364,7 +363,7 @@ def main(args=None):
portable_settings_path = data_path / 'OpenLP.ini'
# Make this our settings file
log.info('INI file: {name}'.format(name=portable_settings_path))
Settings.set_filename(str(portable_settings_path))
Settings.set_filename(portable_settings_path)
portable_settings = Settings()
# Set our data path
log.info('Data path: {name}'.format(name=data_path))

View File

@ -78,7 +78,7 @@ class Path(PathVariant):
:param onerror: Handler function to handle any errors
:rtype: None
"""
shutil.rmtree(str(self), ignore_errors, onerror)
shutil.rmtree(self, ignore_errors, onerror)
def replace_params(args, kwargs, params):

View File

@ -144,7 +144,7 @@ def get_db_path(plugin_name, db_file_name=None):
return 'sqlite:///{path}/{name}'.format(path=AppLocation.get_section_data_path(plugin_name), name=db_file_name)
def handle_db_error(plugin_name, db_file_name):
def handle_db_error(plugin_name, db_file_name): # TODO: To pathlib
"""
Log and report to the user that a database cannot be loaded
@ -159,7 +159,7 @@ def handle_db_error(plugin_name, db_file_name):
'OpenLP cannot load your database.\n\nDatabase: {db}').format(db=db_path))
def init_url(plugin_name, db_file_name=None):
def init_url(plugin_name, db_file_name=None): # TODO: Pathlib
"""
Return the database URL.

View File

@ -263,7 +263,7 @@ class ServiceItem(RegistryProperties):
file_location = os.path.join(path, file_name)
file_location_hash = md5_hash(file_location.encode('utf-8'))
image = os.path.join(str(AppLocation.get_section_data_path(self.name)), 'thumbnails',
file_location_hash, ntpath.basename(image))
file_location_hash, ntpath.basename(image)) #TODO: Pathlib
self.slides.append({'title': file_name, 'image': image, 'path': path, 'display_title': display_title,
'notes': notes, 'thumbnail': image})
# if self.is_capable(ItemCapabilities.HasThumbnails):
@ -361,7 +361,7 @@ class ServiceItem(RegistryProperties):
if isinstance(file_path, str):
# Handle service files prior to OpenLP 3.0
# Windows can handle both forward and backward slashes, so we use ntpath to get the basename
file_path = Path(path, ntpath.basename(file_path))
file_path = path / ntpath.basename(file_path)
self.background_audio.append(file_path)
self.theme_overwritten = header.get('theme_overwritten', False)
if self.service_item_type == ServiceItemType.Text:
@ -374,7 +374,7 @@ class ServiceItem(RegistryProperties):
if path:
self.has_original_files = False
for text_image in service_item['serviceitem']['data']:
file_path = os.path.join(path, text_image)
file_path = path / text_image
self.add_from_image(file_path, text_image, background)
else:
for text_image in service_item['serviceitem']['data']:

View File

@ -478,7 +478,7 @@ class AdvancedTab(SettingsTab):
minute=self.service_name_time.time().minute()
)
try:
service_name_example = format_time(str(self.service_name_edit.text()), local_time)
service_name_example = format_time(self.service_name_edit.text(), local_time)
except ValueError:
preset_is_valid = False
service_name_example = translate('OpenLP.AdvancedTab', 'Syntax error.')

View File

@ -1334,7 +1334,7 @@ class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow, LogMixin, RegistryPropert
self.show_status_message(
translate('OpenLP.MainWindow', 'Copying OpenLP data to new data directory location - {path} '
'- Please wait for copy to finish').format(path=self.new_data_path))
dir_util.copy_tree(str(old_data_path), str(self.new_data_path))
dir_util.copy_tree(old_data_path, self.new_data_path)
self.log_info('Copy successful')
except (OSError, DistutilsFileError) as why:
self.application.set_normal_cursor()

View File

@ -54,7 +54,7 @@ class ItemMediaInfo(object):
"""
This class hold the media related info
"""
file_info = None
file_info = None # TODO: Ptahlib?
volume = 100
is_background = False
can_loop_playback = False

View File

@ -197,7 +197,7 @@ class VlcPlayer(MediaPlayer):
"""
return get_vlc() is not None
def load(self, display, file):
def load(self, display, file): # TODO: pathlib
"""
Load a video into VLC

View File

@ -234,7 +234,7 @@ class Ui_ServiceManager(object):
self.service_manager_list.itemExpanded.connect(self.expanded)
# Last little bits of setting up
self.service_theme = Settings().value(self.main_window.service_manager_settings_section + '/service theme')
self.service_path = str(AppLocation.get_section_data_path('servicemanager'))
self.service_path = AppLocation.get_section_data_path('servicemanager')
# build the drag and drop context menu
self.dnd_menu = QtWidgets.QMenu()
self.new_action = self.dnd_menu.addAction(translate('OpenLP.ServiceManager', '&Add New Item'))
@ -590,11 +590,11 @@ class ServiceManager(QtWidgets.QWidget, RegistryBase, Ui_ServiceManager, LogMixi
self.main_window.increment_progress_bar(service_content_size)
# Finally add all the listed media files.
for write_path in write_list:
zip_file.write(str(write_path), str(write_path))
zip_file.write(write_path, write_path)
self.main_window.increment_progress_bar(write_path.stat().st_size)
with suppress(FileNotFoundError):
file_path.unlink()
os.link(temp_file.name, str(file_path))
os.link(temp_file.name, file_path)
Settings().setValue(self.main_window.service_manager_settings_section + '/last directory', file_path.parent)
except (PermissionError, OSError) as error:
self.log_exception('Failed to save service to disk: {name}'.format(name=file_path))
@ -679,7 +679,7 @@ class ServiceManager(QtWidgets.QWidget, RegistryBase, Ui_ServiceManager, LogMixi
service_data = None
self.application.set_busy_cursor()
try:
with zipfile.ZipFile(str(file_path)) as zip_file:
with zipfile.ZipFile(file_path) as zip_file:
compressed_size = 0
for zip_info in zip_file.infolist():
compressed_size += zip_info.compress_size
@ -692,7 +692,7 @@ class ServiceManager(QtWidgets.QWidget, RegistryBase, Ui_ServiceManager, LogMixi
service_data = json_file.read()
else:
zip_info.filename = os.path.basename(zip_info.filename)
zip_file.extract(zip_info, str(self.service_path))
zip_file.extract(zip_info, self.service_path)
self.main_window.increment_progress_bar(zip_info.compress_size)
if service_data:
items = json.loads(service_data, cls=OpenLPJsonDecoder)
@ -1239,11 +1239,11 @@ class ServiceManager(QtWidgets.QWidget, RegistryBase, Ui_ServiceManager, LogMixi
"""
Empties the service_path of temporary files on system exit.
"""
for file_name in os.listdir(self.service_path):
file_path = Path(self.service_path, file_name)
for file_path in self.service_path.iterdir():
delete_file(file_path)
if os.path.exists(os.path.join(self.service_path, 'audio')):
shutil.rmtree(os.path.join(self.service_path, 'audio'), True)
audio_path = self.service_path / 'audio'
if audio_path.exists():
audio_path.rmtree(True)
def on_theme_combo_box_selected(self, current_index):
"""

View File

@ -422,10 +422,10 @@ class ThemeManager(QtWidgets.QWidget, RegistryBase, Ui_ThemeManager, LogMixin, R
:rtype: bool
"""
try:
with zipfile.ZipFile(str(theme_path), 'w') as theme_zip:
with zipfile.ZipFile(theme_path, 'w') as theme_zip:
source_path = self.theme_path / theme_name
for file_path in source_path.iterdir():
theme_zip.write(str(file_path), os.path.join(theme_name, file_path.name))
theme_zip.write(file_path, Path(theme_name, file_path.name))
return True
except OSError as ose:
self.log_exception('Export Theme Failed')
@ -567,7 +567,7 @@ class ThemeManager(QtWidgets.QWidget, RegistryBase, Ui_ThemeManager, LogMixin, R
json_theme = False
theme_name = ""
try:
with zipfile.ZipFile(str(file_path)) as theme_zip:
with zipfile.ZipFile(file_path) as theme_zip:
json_file = [name for name in theme_zip.namelist() if os.path.splitext(name)[1].lower() == '.json']
if len(json_file) != 1:
# TODO: remove XML handling after once the upgrade path from 2.4 is no longer required

View File

@ -352,7 +352,7 @@ class PathEdit(QtWidgets.QWidget):
:rtype: None
"""
if self._path != path:
self._path = path
self.path = path
self.pathChanged.emit(path)

View File

@ -300,7 +300,7 @@ class OpenLPWizard(QtWidgets.QWizard, RegistryProperties):
file_path, filter_used = FileDialog.getOpenFileName(
self, title, Settings().value(self.plugin.settings_section + '/' + setting_name), filters)
if file_path:
editbox.setText(str(file_path))
editbox.setText(str(file_path)) # TODO: to pathdedit
Settings().setValue(self.plugin.settings_section + '/' + setting_name, file_path.parent)
def get_folder(self, title, editbox, setting_name):
@ -316,5 +316,5 @@ class OpenLPWizard(QtWidgets.QWizard, RegistryProperties):
self, title, Settings().value(self.plugin.settings_section + '/' + setting_name),
FileDialog.ShowDirsOnly)
if folder_path:
editbox.setText(str(folder_path))
editbox.setText(str(folder_path)) # TODO: to pathedit
Settings().setValue(self.plugin.settings_section + '/' + setting_name, folder_path)

View File

@ -48,9 +48,9 @@ class BibleImport(BibleDB, LogMixin, RegistryProperties):
"""
Check if the supplied file is compressed
:param file_path: A path to the file to check
:param openlp.core.common.path.Path file_path: A path to the file to check
"""
if is_zipfile(str(file_path)):
if is_zipfile(file_path):
critical_error_message_box(
message=translate('BiblesPlugin.BibleImport',
'The file "{file}" you supplied is compressed. You must decompress it before import.'

View File

@ -51,7 +51,7 @@ class WordProjectBible(BibleImport):
Unzip the file to a temporary directory
"""
self.tmp = TemporaryDirectory()
with ZipFile(str(self.file_path)) as zip_file:
with ZipFile(self.file_path) as zip_file:
zip_file.extractall(self.tmp.name)
self.base_path = Path(self.tmp.name, self.file_path.stem)

View File

@ -229,8 +229,8 @@ class MediaMediaItem(MediaManagerItem, RegistryProperties):
Initialize media item.
"""
self.list_view.clear()
self.service_path = str(AppLocation.get_section_data_path(self.settings_section) / 'thumbnails')
create_paths(Path(self.service_path))
self.service_path = AppLocation.get_section_data_path(self.settings_section) / 'thumbnails'
create_paths(self.service_path)
self.load_list([path_to_str(file) for file in Settings().value(self.settings_section + '/media files')])
self.rebuild_players()
@ -264,7 +264,7 @@ class MediaMediaItem(MediaManagerItem, RegistryProperties):
:param media: The media
:param target_group:
"""
media.sort(key=lambda file_name: get_natural_key(os.path.split(str(file_name))[1]))
media.sort(key=lambda file_path: get_natural_key(file_path.name))
for track in media:
track_info = QtCore.QFileInfo(track)
item_name = None

View File

@ -67,7 +67,7 @@ class CCLIFileImport(SongImport):
details = {'confidence': 1, 'encoding': 'utf-8'}
except UnicodeDecodeError:
details = chardet.detect(detect_content)
in_file = codecs.open(str(file_path), 'r', details['encoding'])
in_file = codecs.open(file_path, 'r', details['encoding'])
if not in_file.read(1) == '\ufeff':
# not UTF or no BOM was found
in_file.seek(0)

View File

@ -63,8 +63,8 @@ class TestRemoteDeploy(TestCase):
deploy_zipfile(root_path, 'site.zip')
# THEN: the zip file should have been extracted to the right location
MockZipFile.assert_called_once_with('/tmp/remotes/site.zip')
mocked_zipfile.extractall.assert_called_once_with('/tmp/remotes')
MockZipFile.assert_called_once_with(Path('/tmp/remotes/site.zip'))
mocked_zipfile.extractall.assert_called_once_with(Path('/tmp/remotes'))
@patch('openlp.core.api.deploy.Registry')
@patch('openlp.core.api.deploy.get_web_page')

View File

@ -179,9 +179,8 @@ class TestShutil(TestCase):
# WHEN: Calling :func:`openlp.core.common.path.rmtree` with the path parameter as Path object type
path.rmtree()
# THEN: :func:`shutil.rmtree` should have been called with the str equivalents of the Path object.
mocked_shutil_rmtree.assert_called_once_with(
os.path.join('test', 'path'), False, None)
# THEN: :func:`shutil.rmtree` should have been called with the the Path object.
mocked_shutil_rmtree.assert_called_once_with(Path('test', 'path'), False, None)
def test_rmtree_optional_params(self):
"""
@ -198,8 +197,7 @@ class TestShutil(TestCase):
# THEN: :func:`shutil.rmtree` should have been called with the optional parameters, with out any of the
# values being modified
mocked_shutil_rmtree.assert_called_once_with(
os.path.join('test', 'path'), True, mocked_on_error)
mocked_shutil_rmtree.assert_called_once_with(path, True, mocked_on_error)
def test_which_no_command(self):
"""

View File

@ -141,7 +141,7 @@ class TestServiceItem(TestCase, TestMixin):
"""
# GIVEN: A new service item and a mocked add icon function
image_name = 'image_1.jpg'
test_file = os.path.join(str(TEST_PATH), image_name)
test_file = TEST_PATH / image_name
frame_array = {'path': test_file, 'title': image_name}
service_item = ServiceItem(None)
@ -154,7 +154,7 @@ class TestServiceItem(TestCase, TestMixin):
mocked_get_section_data_path:
mocked_exists.return_value = True
mocked_get_section_data_path.return_value = Path('/path/')
service_item.set_from_service(line, str(TEST_PATH))
service_item.set_from_service(line, TEST_PATHb)
# THEN: We should get back a valid service item
assert service_item.is_valid is True, 'The new service item should be valid'

View File

@ -66,9 +66,9 @@ class TestThemeManager(TestCase):
theme_manager._export_theme(Path('some', 'path', 'Default.otz'), 'Default')
# THEN: The zipfile should be created at the given path
mocked_zipfile_init.assert_called_with(os.path.join('some', 'path', 'Default.otz'), 'w')
mocked_zipfile_write.assert_called_with(str(RESOURCE_PATH / 'themes' / 'Default' / 'Default.xml'),
os.path.join('Default', 'Default.xml'))
mocked_zipfile_init.assert_called_with(Path('some', 'path', 'Default.otz'), 'w')
mocked_zipfile_write.assert_called_with(RESOURCE_PATH / 'themes' / 'Default' / 'Default.xml',
Path('Default', 'Default.xml'))
def test_initial_theme_manager(self):
"""

View File

@ -70,7 +70,7 @@ class FakeIP4InterfaceEntry(QObject):
"""
Return a QFlags enum with IsUp and IsRunning
"""
return (QNetworkInterface.IsUp | QNetworkInterface.IsRunning)
return QNetworkInterface.IsUp | QNetworkInterface.IsRunning
def name(self):
return self.my_name

View File

@ -83,8 +83,8 @@ class ProjectorSourceFormTest(TestCase, TestMixin):
Delete all C++ objects at end so we don't segfault.
"""
self.projectordb.session.close()
del(self.projectordb)
del(self.projector)
del self.projectordb
del self.projector
retries = 0
while retries < 5:
try: