The function for rascals
The function builds two lists of filenames that it feeds depending on whether it has already encountered the file containing the title or not, which depends on the active file when the regex is launched. The file containing the title is the one containing the 1st note, the one on which the merge will be done.
The two lists of file names are merged to get the complete list of files to be merged.
We raise an exception with the '
raise' instruction to stop the function after the '
merge' and before the '
return' which would cancel the result. This is the dirty side of the job.
At runtime, a warning message appears, which says:
Merging: Files merged out.
Code:
from calibre.gui2.tweak_book import current_container
from calibre.gui2.tweak_book.boss import get_boss
from calibre.ebooks.oeb.polish.split import merge
class Merging(LookupError):
pass
# Warning : very dirty work around
# Custom class exception, to provoke the end of job without return
# If we use return, we loose the result of the merging
def replace(match, number, file_name, metadata, dictionaries, data, functions, *args, **kwargs):
if match is None: # this is the last passage (all matches found)
ctnr = current_container()
# Merge files whose name is in the list 'note_files_list'
# (stored in persistent dic 'data', a parameter of replace())
# into the file whose name is in 'merge_master' (also stored in data)
data['note_files_list'] = data['first_notes'] + data['last_notes']
if data and len(data['note_files_list']) > 1:
merge(ctnr, 'text', data['note_files_list'], data['merge_master'])
get_boss().apply_container_update_to_gui()
# very dirty trick : get out without applying 'return' :
raise Merging("Files merged out")
else:
if 'merge_master' not in data :
# data is empty, therefore it's the 1st iteration
# the list of files and the master of merge are initialized
data['note_files_list'] = []
data['merge_master'] = []
if match.group(1):
# If group 1 exists, the note contains the title and therefore the note is the 1st note
# The master of merge becomes the current note file
data['first'] = True
data['merge_master'] = file_name
data['first_notes'] = [file_name]
data['last_notes'] = []
else:
data['first'] = False
data['first_notes'] = []
data['last_notes'] = [file_name]
# Ask for a passage after the last find (match will be None)
# Ask for processing the files in the order they appear in the book
replace.call_after_last_match = True
replace.file_order = 'spine'
else:
if match.group(1):
data['first'] = True
# The master of merge becomes the current note file
data['merge_master'] = file_name
# Increments the list of files by adding the name of the current file
if data['first']:
data['first_notes'].append(file_name)
else:
data['last_notes'].append(file_name)
return match.group()