Pathlib changes

This commit is contained in:
Philip Ridout 2017-09-06 22:36:31 +01:00
parent 292861907e
commit 24358337e7
4 changed files with 59 additions and 74 deletions

View File

@ -138,12 +138,9 @@ class Registry(object):
if result: if result:
results.append(result) results.append(result)
except TypeError: except TypeError:
# Who has called me can help in debugging
trace_error_handler(log)
log.exception('Exception for function {function}'.format(function=function)) log.exception('Exception for function {function}'.format(function=function))
else: else:
trace_error_handler(log) log.exception('Event {event} called but not registered'.format(event=event))
log.error("Event {event} called but not registered".format(event=event))
return results return results
def get_flag(self, key): def get_flag(self, key):

View File

@ -88,9 +88,6 @@ class UiStrings(object):
self.Error = translate('OpenLP.Ui', 'Error') self.Error = translate('OpenLP.Ui', 'Error')
self.Export = translate('OpenLP.Ui', 'Export') self.Export = translate('OpenLP.Ui', 'Export')
self.File = translate('OpenLP.Ui', 'File') self.File = translate('OpenLP.Ui', 'File')
self.FileNotFound = translate('OpenLP.Ui', 'File Not Found')
self.FileNotFoundMessage = translate('OpenLP.Ui',
'File {name} not found.\nPlease try selecting it individually.')
self.FontSizePtUnit = translate('OpenLP.Ui', 'pt', 'Abbreviated font pointsize unit') self.FontSizePtUnit = translate('OpenLP.Ui', 'pt', 'Abbreviated font pointsize unit')
self.Help = translate('OpenLP.Ui', 'Help') self.Help = translate('OpenLP.Ui', 'Help')
self.Hours = translate('OpenLP.Ui', 'h', 'The abbreviated unit for hours') self.Hours = translate('OpenLP.Ui', 'h', 'The abbreviated unit for hours')

View File

@ -366,16 +366,17 @@ class ServiceManager(OpenLPMixin, RegistryMixin, QtWidgets.QWidget, Ui_ServiceMa
""" """
return self._modified return self._modified
def set_file_name(self, file_name): def set_file_name(self, file_path):
""" """
Setter for service file. Setter for service file.
:param file_name: The service file name :param openlp.core.common.path.Path file_path: The service file name
:rtype: None
""" """
self._file_name = str(file_name) self._file_name = path_to_str(file_path)
self.main_window.set_service_modified(self.is_modified(), self.short_file_name()) self.main_window.set_service_modified(self.is_modified(), self.short_file_name())
Settings().setValue('servicemanager/last file', Path(file_name)) Settings().setValue('servicemanager/last file', file_path)
self._save_lite = self._file_name.endswith('.oszl') self._save_lite = file_path.suffix() == '.oszl'
def file_name(self): def file_name(self):
""" """
@ -474,7 +475,7 @@ class ServiceManager(OpenLPMixin, RegistryMixin, QtWidgets.QWidget, Ui_ServiceMa
""" """
self.service_manager_list.clear() self.service_manager_list.clear()
self.service_items = [] self.service_items = []
self.set_file_name('') self.set_file_name(None)
self.service_id += 1 self.service_id += 1
self.set_modified(False) self.set_modified(False)
Settings().setValue('servicemanager/last file', None) Settings().setValue('servicemanager/last file', None)
@ -695,27 +696,23 @@ class ServiceManager(OpenLPMixin, RegistryMixin, QtWidgets.QWidget, Ui_ServiceMa
default_file_name = format_time(default_pattern, local_time) default_file_name = format_time(default_pattern, local_time)
else: else:
default_file_name = '' default_file_name = ''
directory = path_to_str(Settings().value(self.main_window.service_manager_settings_section + '/last directory')) directory_path = Settings().value(self.main_window.service_manager_settings_section + '/last directory')
path = os.path.join(directory, default_file_name) file_path = directory_path / default_file_name
# SaveAs from osz to oszl is not valid as the files will be deleted on exit which is not sensible or usable in # SaveAs from osz to oszl is not valid as the files will be deleted on exit which is not sensible or usable in
# the long term. # the long term.
if self._file_name.endswith('oszl') or self.service_has_all_original_files: if self._file_name.endswith('oszl') or self.service_has_all_original_files:
file_name, filter_used = QtWidgets.QFileDialog.getSaveFileName( file_path, filter_used = FileDialog.getSaveFileName(
self.main_window, UiStrings().SaveService, path, self.main_window, UiStrings().SaveService, file_path,
translate('OpenLP.ServiceManager', translate('OpenLP.ServiceManager',
'OpenLP Service Files (*.osz);; OpenLP Service Files - lite (*.oszl)')) 'OpenLP Service Files (*.osz);; OpenLP Service Files - lite (*.oszl)'))
else: else:
file_name, filter_used = QtWidgets.QFileDialog.getSaveFileName( file_path, filter_used = FileDialog.getSaveFileName(
self.main_window, UiStrings().SaveService, path, self.main_window, UiStrings().SaveService, file_path,
translate('OpenLP.ServiceManager', 'OpenLP Service Files (*.osz);;')) translate('OpenLP.ServiceManager', 'OpenLP Service Files (*.osz);;'))
if not file_name: if not file_path:
return False return False
if os.path.splitext(file_name)[1] == '': file_path.with_suffix('.osz')
file_name += '.osz' self.set_file_name(file_path)
else:
ext = os.path.splitext(file_name)[1]
file_name.replace(ext, '.osz')
self.set_file_name(file_name)
self.decide_save_method() self.decide_save_method()
def decide_save_method(self, field=None): def decide_save_method(self, field=None):
@ -772,7 +769,7 @@ class ServiceManager(OpenLPMixin, RegistryMixin, QtWidgets.QWidget, Ui_ServiceMa
return return
file_to.close() file_to.close()
self.new_file() self.new_file()
self.set_file_name(file_name) self.set_file_name(str_to_path(file_name))
self.main_window.display_progress_bar(len(items)) self.main_window.display_progress_bar(len(items))
self.process_service_items(items) self.process_service_items(items)
delete_file(Path(p_file)) delete_file(Path(p_file))

View File

@ -25,10 +25,10 @@ The :mod:`db` module provides the ability to provide a csv file of all songs
import csv import csv
import logging import logging
from PyQt5 import QtWidgets
from openlp.core.common import Registry, translate from openlp.core.common import Registry, translate
from openlp.core.common.path import Path
from openlp.core.lib.ui import critical_error_message_box from openlp.core.lib.ui import critical_error_message_box
from openlp.core.ui.lib.filedialog import FileDialog
from openlp.plugins.songs.lib.db import Song from openlp.plugins.songs.lib.db import Song
@ -42,58 +42,55 @@ def report_song_list():
""" """
main_window = Registry().get('main_window') main_window = Registry().get('main_window')
plugin = Registry().get('songs').plugin plugin = Registry().get('songs').plugin
report_file_name, filter_used = QtWidgets.QFileDialog.getSaveFileName( report_file_path, filter_used = FileDialog.getSaveFileName(
main_window, main_window,
translate('SongPlugin.ReportSongList', 'Save File'), translate('SongPlugin.ReportSongList', 'Save File'),
translate('SongPlugin.ReportSongList', 'song_extract.csv'), Path(translate('SongPlugin.ReportSongList', 'song_extract.csv')),
translate('SongPlugin.ReportSongList', 'CSV format (*.csv)')) translate('SongPlugin.ReportSongList', 'CSV format (*.csv)'))
if not report_file_name: if not report_file_path:
main_window.error_message( main_window.error_message(
translate('SongPlugin.ReportSongList', 'Output Path Not Selected'), translate('SongPlugin.ReportSongList', 'Output Path Not Selected'),
translate('SongPlugin.ReportSongList', 'You have not set a valid output location for your ' translate('SongPlugin.ReportSongList', 'You have not set a valid output location for your report. \n'
'report. \nPlease select an existing path ' 'Please select an existing path on your computer.')
'on your computer.')
) )
return return
if not report_file_name.endswith('csv'): report_file_path.with_suffix('.csv')
report_file_name += '.csv'
file_handle = None
Registry().get('application').set_busy_cursor() Registry().get('application').set_busy_cursor()
try: try:
file_handle = open(report_file_name, 'wt') with report_file_path.open('wt') as file_handle:
fieldnames = ('Title', 'Alternative Title', 'Copyright', 'Author(s)', 'Song Book', 'Topic') fieldnames = ('Title', 'Alternative Title', 'Copyright', 'Author(s)', 'Song Book', 'Topic')
writer = csv.DictWriter(file_handle, fieldnames=fieldnames, quoting=csv.QUOTE_ALL) writer = csv.DictWriter(file_handle, fieldnames=fieldnames, quoting=csv.QUOTE_ALL)
headers = dict((n, n) for n in fieldnames) headers = dict((n, n) for n in fieldnames)
writer.writerow(headers) writer.writerow(headers)
song_list = plugin.manager.get_all_objects(Song) song_list = plugin.manager.get_all_objects(Song)
for song in song_list: for song in song_list:
author_list = [] author_list = []
for author_song in song.authors_songs: for author_song in song.authors_songs:
author_list.append(author_song.author.display_name) author_list.append(author_song.author.display_name)
author_string = ' | '.join(author_list) author_string = ' | '.join(author_list)
book_list = [] book_list = []
for book_song in song.songbook_entries: for book_song in song.songbook_entries:
if hasattr(book_song, 'entry') and book_song.entry: if hasattr(book_song, 'entry') and book_song.entry:
book_list.append('{name} #{entry}'.format(name=book_song.songbook.name, entry=book_song.entry)) book_list.append('{name} #{entry}'.format(name=book_song.songbook.name, entry=book_song.entry))
book_string = ' | '.join(book_list) book_string = ' | '.join(book_list)
topic_list = [] topic_list = []
for topic_song in song.topics: for topic_song in song.topics:
if hasattr(topic_song, 'name'): if hasattr(topic_song, 'name'):
topic_list.append(topic_song.name) topic_list.append(topic_song.name)
topic_string = ' | '.join(topic_list) topic_string = ' | '.join(topic_list)
writer.writerow({'Title': song.title, writer.writerow({'Title': song.title,
'Alternative Title': song.alternate_title, 'Alternative Title': song.alternate_title,
'Copyright': song.copyright, 'Copyright': song.copyright,
'Author(s)': author_string, 'Author(s)': author_string,
'Song Book': book_string, 'Song Book': book_string,
'Topic': topic_string}) 'Topic': topic_string})
Registry().get('application').set_normal_cursor() Registry().get('application').set_normal_cursor()
main_window.information_message( main_window.information_message(
translate('SongPlugin.ReportSongList', 'Report Creation'), translate('SongPlugin.ReportSongList', 'Report Creation'),
translate('SongPlugin.ReportSongList', translate('SongPlugin.ReportSongList',
'Report \n{name} \nhas been successfully created. ').format(name=report_file_name) 'Report \n{name} \nhas been successfully created. ').format(name=report_file_path)
) )
except OSError as ose: except OSError as ose:
Registry().get('application').set_normal_cursor() Registry().get('application').set_normal_cursor()
log.exception('Failed to write out song usage records') log.exception('Failed to write out song usage records')
@ -101,6 +98,3 @@ def report_song_list():
translate('SongPlugin.ReportSongList', translate('SongPlugin.ReportSongList',
'An error occurred while extracting: {error}' 'An error occurred while extracting: {error}'
).format(error=ose.strerror)) ).format(error=ose.strerror))
finally:
if file_handle:
file_handle.close()