from __future__ import annotations
import html
import pathlib
import sys
from typing import TYPE_CHECKING
from urllib.parse import quote
if TYPE_CHECKING:
from modules.config.config import Config
from modules.dat.process_dat import Dat, DatNode
import modules.constants as const
from modules.titletools import Removes
from modules.utils import Font, eprint, get_datetime
class WriteFiles:
"""Methods for writing files to disk."""
@staticmethod
def output(
processed_titles: dict[str, set[DatNode]],
quick_lookup: dict[str, dict[str, set[DatNode]]],
report: tuple[dict[str, set[str]], set[str]],
config: Config,
input_dat: Dat,
removed_titles: Removes,
dat_file: str,
) -> None:
"""
The main function for managing output. The actual writing of files is done by
other functions.
Args:
processed_titles (dict[str, set[DatNode]]): A work in progress dictionary of
DatNodes, originally populated from the input DAT and actively being
worked on by Retool.
quick_lookup (dict[str, set[DatNode]]): A dictionary keyed by multiple title
properties that enables quick lookup of titles. Due to the way Python
references variables, changes made here are also reflected in
`processed_titles`.
report (tuple[dict[str, set[str]], set[str]]): Contains all the titles
included and removed from the output DAT, and their relationships. Used if
the user specifies `--report`.
config (Config): The Retool config object.
input_dat (Dat): The Retool input_dat object.
removed_titles (Removes): The Retool removes object, which contains and
categorizes all the titles that have been removed from consideration. It is
used for recovering titles defined by user includes, stats, and other output
files generated by Retool.
dat_file (str): The DAT file being processed.
"""
timestamp: str = get_datetime().strftime('%Y-%m-%d %H-%M-%S')
# Check if a system config is in play
region_order: list[str] = config.region_order_user
if config.system_region_order_user:
if {'override': 'true'} in config.system_region_order_user:
region_order = [
str(x) for x in config.system_region_order_user if 'override' not in x
]
if config.user_input.output_region_split:
for region in region_order:
region_processed_titles: dict[str, set[DatNode]] = {}
for group in processed_titles:
for title in processed_titles[group]:
if title.primary_region == region and not title.cloneof:
if group not in region_processed_titles:
region_processed_titles[group] = set()
region_processed_titles[group].add(title)
if region_processed_titles:
WriteFiles.write_dat(
region_processed_titles,
quick_lookup,
config,
input_dat,
timestamp,
output_file_removes='',
output_file_region=f' ({region})',
dat_file=dat_file,
)
else:
WriteFiles.write_dat(
processed_titles,
quick_lookup,
config,
input_dat,
timestamp,
output_file_removes='',
output_file_region='',
dat_file=dat_file,
main_dat_file=True,
)
# Add removed titles to a separate DAT if requested
if config.user_input.output_remove_dat:
removed_titles_output: dict[str, set[DatNode]] = {}
# Get the titles from various remove categories
for removes_group in removed_titles.__dict__.values():
for title in removes_group:
if title.group_name not in removed_titles_output:
removed_titles_output[title.group_name] = set()
removed_titles_output[title.group_name].add(title)
# Add clones
for titles in processed_titles.values():
for title in titles:
if title.cloneof:
title.exclude_reason = f'Clone of {title.cloneof}'
title.cloneof = ''
if (
title.group_name not in removed_titles_output
and not config.user_input.legacy
):
removed_titles_output[title.group_name] = set()
if not config.user_input.legacy:
removed_titles_output[title.group_name].add(title)
# Write the DAT/s
if removed_titles_output:
if config.user_input.output_region_split:
for region in region_order:
region_removed_titles: dict[str, set[DatNode]] = {}
for group in removed_titles_output:
for title in removed_titles_output[group]:
if title.primary_region == region and not title.cloneof:
if group not in region_removed_titles:
region_removed_titles[group] = set()
region_removed_titles[group].add(title)
if region_removed_titles:
WriteFiles.write_dat(
region_removed_titles,
quick_lookup,
config,
input_dat,
timestamp,
output_file_removes=' (Removed titles)',
output_file_region=f' ({region})',
dat_file=dat_file,
)
else:
WriteFiles.write_dat(
removed_titles_output,
quick_lookup,
config,
input_dat,
timestamp,
output_file_removes=' (Removed titles)',
output_file_region='',
dat_file=dat_file,
)
# Write the report if requested
if config.user_input.report:
WriteFiles.write_report(report, removed_titles, config, input_dat, timestamp)
@staticmethod
def write_dat(
processed_titles: dict[str, set[DatNode]],
quick_lookup: dict[str, dict[str, set[DatNode]]],
config: Config,
input_dat: Dat,
timestamp: str,
output_file_removes: str = '',
output_file_region: str = '',
dat_file: str = '',
main_dat_file: bool = False,
) -> None:
"""
Writes DAT files. Additionally writes the output for `--listnames` if the user has
requested it, which contains the names of the titles which have been kept, and
optionally a user-defined prefix and suffix.
Args:
processed_titles (dict[str, set[DatNode]]): A work in progress dictionary of
DatNodes, originally populated from the input DAT and actively being
worked on by Retool.
quick_lookup (dict[str, set[DatNode]]): A dictionary keyed by multiple title
properties that enables quick lookup of titles. Due to the way Python
references variables, changes made here are also reflected in
`processed_titles`.
config (Config): The Retool config object.
input_dat (Dat): The Retool input_dat object.
timestamp (str): Timestamp used in the date header of the output DAT and its
filename.
output_file_removes (str, optional): The string to append to a DAT file if it
contains the titles Retool has removed. Defaults to `''`.
output_file_region (str, optional): An additional region tag to append to the
removes DAT filename if the user has opted to split by region. Defaults
to `''`.
dat_file (str, optional): The path to the input DAT file.
main_dat_file (bool): Whether this is the main DAT file being written.
"""
eprint(
f'• Creating{output_file_region.replace("(", "").replace(")", "")}{output_file_removes.replace("(", "").replace(")", "").lower()} DAT file... ',
)
config.stats.final_count = 0
config.stats.clones_count = 0
# Create a list of titles, deduped of superset titles
final_titles: set[DatNode] = set()
dupe_check: set[str] = set()
for titles in processed_titles.values():
for title in titles:
if title.full_name not in dupe_check:
dupe_check.add(title.full_name)
final_titles.add(title)
dupe_check.clear()
# Generate the XML content
final_xml: list[str] = []
dat_xml: list[str] = []
list_names: list[str] = []
local_names: dict[str, int] = {}
config.stats.file_count = 0
# Create the title data first
if input_dat.numbered:
title_list = sorted(final_titles, key=lambda x: x.numbered_name)
else:
title_list = sorted(final_titles, key=lambda x: x.full_name)
for title in title_list:
rom_mia: bool = False
for rom in title.roms:
# Don't include MIA roms in the output if the user doesn't want them
if config.user_input.no_mia and rom['mia']:
rom_mia = True
# Keep a count of the total uncompressed size of all roms/disks in the DAT file
if rom['size']:
config.stats.original_size += int(rom['size'])
if not rom_mia:
# Work with numbered DAT files
if input_dat.numbered:
final_name = title.numbered_name
else:
final_name = title.full_name
# Deal with local names causing duplicates
if config.user_input.local_names and title.local_name:
if title.local_name in local_names:
if config.user_input.verbose:
eprint(
'\n• The following title\'s local name '
'is already in the output DAT and must be renamed. Its '
'clone relationship will be removed. This can only be '
'fixed in the clone list for the system.',
level='warning',
)
eprint(
f'\n {title.local_name} > {title.local_name} (Dupe {local_names[title.local_name] + 1}){Font.end}',
level='warning',
wrap=False,
)
if config.user_input.warningpause:
eprint(pause=True)
local_names[title.local_name] += 1
title.local_name = (
f'{title.local_name} (Dupe {local_names[title.local_name]})'
)
title.cloneof = ''
else:
local_names[title.local_name] = 0
final_name = title.local_name
# Set the tag used for titles, either game or machine
element_name: str = title.tag_name
if config.user_input.machine_not_game:
element_name = 'machine'
# Deal with arbitrary attributes added by DAT file maintainers
element_attribs: str = ''
if title.tag_attribs:
element_attribs_list: list[str] = []
for key, value in title.tag_attribs.items():
element_attribs_list.append(f'{key}="{value}"')
element_attribs = f' {" ".join(element_attribs_list)}'
# Tag RetroAchievements titles
retroachievements: str = ''
if config.user_input.label_retro and title.is_retroachievement:
retroachievements = ' retroachievements="yes"'
# Deal with clones and parents
if title.cloneof:
config.stats.clones_count += 1
if config.user_input.legacy:
config.stats.final_count += 1
# Find out if the parent has a local name and use it if so
if config.user_input.local_names:
if title.cloneof in quick_lookup['full_name_index']:
clone_titles: set[DatNode] = quick_lookup['full_name_index'][
title.cloneof
]
for clone_title in clone_titles:
if clone_title.local_name:
# Catch clone problems caused by duplicate local names
if final_name == clone_title.local_name:
if config.user_input.verbose:
eprint(
'\n• The following title\'s local name '
'is the same as its parent. Its clone relationship will '
'be removed. This can only be fixed in the clone list '
'for the system.',
level='warning',
)
eprint(
f'\n {final_name}{Font.end}',
level='warning',
wrap=False,
)
if config.user_input.warningpause:
eprint(pause=True)
dat_xml.append(
f'\t<{element_name} name="{html.escape(final_name, quote=False)}"{retroachievements}{element_attribs}>\n'
)
else:
dat_xml.append(
f'\t<{element_name} name="{html.escape(final_name, quote=False)}" cloneof="{html.escape(clone_title.local_name, quote=False)}"{retroachievements}{element_attribs}>\n'
)
else:
dat_xml.append(
f'\t<{element_name} name="{html.escape(final_name, quote=False)}" cloneof="{html.escape(title.cloneof, quote=False)}"{retroachievements}{element_attribs}>\n'
)
else:
dat_xml.append(
f'\t<{element_name} name="{html.escape(final_name, quote=False)}" cloneof="{html.escape(title.cloneof, quote=False)}"{retroachievements}{element_attribs}>\n'
)
if config.user_input.list_names:
list_names.append(final_name)
config.stats.file_count += 1
else:
continue
elif not title.cloneof:
config.stats.final_count += 1
dat_xml.append(
f'\t<{element_name} name="{html.escape(final_name, quote=False)}"{retroachievements}{element_attribs}>\n'
)
if config.user_input.list_names:
list_names.append(final_name)
config.stats.file_count += 1
for category in sorted(title.categories):
dat_xml.append(
f'\t\t{html.escape(category, quote=False)}\n'
)
if title.exclude_reason:
dat_xml.append(
f'\t\tRemove reason: {html.escape(title.exclude_reason, quote=False)}\n'
)
if title.description:
dat_xml.append(
f'\t\t{html.escape(title.description, quote=False)}\n'
)
else:
dat_xml.append('\t\t\n')
if config.user_input.legacy:
for region in sorted(title.regions):
if not title.languages:
dat_xml.append(
f'\t\t\n'
)
else:
for language in sorted(title.languages):
dat_xml.append(
f'\t\t\n'
)
if title.unrecognized_children:
for unrecognized_child in title.unrecognized_children:
dat_xml.append(f'\t\t{unrecognized_child}\n')
size: int = 0
for rom in sorted(title.roms, key=lambda x: x["name"]):
crc: str = ''
md5: str = ''
sha1: str = ''
sha256: str = ''
header: str = ''
mia: str = ''
if rom['crc']:
crc = f'crc="{rom["crc"]}"'
if rom['md5']:
md5 = f'md5="{rom["md5"]}"'
if rom['sha1']:
sha1 = f'sha1="{rom["sha1"]}"'
if rom['sha256']:
sha256 = f'sha256="{rom["sha256"]}"'
if rom['header']:
header = f'header="{rom["header"]}"'
if rom['mia']:
mia = f'mia="{rom["mia"]}"'
if rom['size']:
size += int(rom['size'])
rom_status: str = ''
if not (rom['crc'] or rom['md5'] or rom['sha1'] or rom['sha256']):
if not rom['size']:
rom['size'] = '0'
rom_status = 'status="nodump"'
rom_xml: list[str] = [f'name="{html.escape(rom["name"], quote=False)}"']
if rom["size"]:
rom_xml.append(f'size="{rom["size"]}"')
rom_xml.extend([mia, rom_status, header, crc, md5, sha1, sha256])
rom_xml = [x for x in rom_xml if x != '']
dat_xml.append(f'\t\t<{rom["type"]} {" ".join(rom_xml)}/>\n')
dat_xml.append(f'\t{element_name}>\n')
config.stats.final_size += size
dat_xml.append('\n')
# Now create the header data
if input_dat.author:
input_dat.author = input_dat.author.replace(' & Retool', '')
input_dat.author = f'{html.escape(input_dat.author, quote=False)}'
else:
input_dat.author = 'Unknown'
# Show user exclude options in the output filename
excludes: str = ''
if config.user_input.excludes:
excludes = f' [-{config.user_input.excludes}]'
# Add DAT manager directives that were in the original DAT
rom_header: list[str] = []
for directive in input_dat.dat_manager_directives:
rom_header.append(f'\t\t{directive.strip()}\n')
dtd_line: str = ''
if input_dat.datafile_tag == '':
dtd_line = ''
final_xml.append('\n')
if dtd_line:
final_xml.append(f'{dtd_line}\n')
if input_dat.datafile_tag:
final_xml.append(f'{input_dat.datafile_tag}\n')
# Set some header content based on whether we're testing output, and therefore need non-volatile content
retool_version: str
dat_date: str
if config.user_input.test:
retool_version = 'X'
dat_date = '2023-06-17 00-00-00'
else:
retool_version = f'{const.__version__}'
dat_date = timestamp
if config.user_input.original_header:
final_xml.append('\t\n')
final_xml.extend(input_dat.original_header)
final_xml.append('\n')
else:
final_xml.extend(
[
'\t\n',
f'\t\t{html.escape(input_dat.name, quote=False)} (Retool){output_file_region}{output_file_removes}\n',
f'\t\t{html.escape(input_dat.name, quote=False)} ({config.stats.file_count:,}){config.user_input.user_options}{excludes} ({input_dat.version}) (Retool){output_file_region}{output_file_removes}\n',
f'\t\t{html.escape(input_dat.version, quote=False)}\n',
f'\t\t{dat_date}\n',
f'\t\t{input_dat.author}\n',
'\t\thttp://www.github.com/unexpectedpanda/retool\n',
f'\t\t{html.escape(input_dat.url, quote=False)}\n',
]
)
if rom_header:
final_xml.extend(rom_header)
final_xml.append(f'\t\tCreated by Retool {retool_version}\n')
final_xml.append('\t\n')
final_xml.extend(dat_xml)
# Set the output folder
if config.user_input.replace:
config.user_input.output_folder_name = pathlib.Path(dat_file).parent
if config.user_input.test:
input_dat.output_filename = f'{config.user_input.output_folder_name}/tests/comparison/{input_dat.name}{output_file_region}{output_file_removes}{config.user_input.user_options}{excludes}.dat'
else:
input_dat.output_filename = f'{config.user_input.output_folder_name}/{input_dat.name} ({input_dat.version}) (Retool {timestamp}){output_file_region}{output_file_removes} ({config.stats.file_count:,}){config.user_input.user_options}{excludes}.dat'
if {'override': 'true'} in config.system_user_path_settings:
if config.system_output:
input_dat.output_filename = f'{pathlib.Path(config.system_output)!s}/{input_dat.name} ({input_dat.version}) (Retool {timestamp}){output_file_region}{output_file_removes} ({config.stats.file_count:,}){config.user_input.user_options}{excludes}.dat'
# Overwrite the input file if the DAT isn't being split
if config.user_input.replace and main_dat_file:
input_dat.output_filename = dat_file
# Create the output folder if it doesn't exist
if not pathlib.Path(input_dat.output_filename[:-4]).parent.exists():
pathlib.Path(pathlib.Path(input_dat.output_filename[:-4]).parent).mkdir(
parents=True, exist_ok=True
)
# Write a list of title names if requested
if config.user_input.list_names:
try:
with open(
pathlib.Path(f'{input_dat.output_filename[:-4]} names.txt'),
'w',
encoding='utf-8',
) as output_file:
def output_list_names(prefix: str, suffix: str, name: str) -> None:
"""
Writes the lines in the list of title names, appends prefixes
and suffixes if present. Converts to a URL encoded string if the
prefix starts with `http://`, `https://`, or `ftp://`.
Args:
prefix (str): The prefix to add to the line.
suffix (str): The suffix to add to the line.
name (str): The title to add to the line.
"""
if prefix.startswith(('http://', 'https://', 'ftp://')):
output_file.writelines(f'{prefix}{quote(name)}{suffix}\n')
else:
output_file.writelines(f'{prefix}{name}{suffix}\n')
for name in list_names:
if {'override options': 'true'} in config.system_exclusions_options:
output_list_names(
config.system_user_prefix, config.system_user_suffix, name
)
else:
output_list_names(config.user_prefix, config.user_suffix, name)
except OSError as e:
eprint(f'• {Font.b}Error{Font.be}: {e!s}\n', level='error')
raise
# Figure out if the user has used redirection to push content to stdout
stdout: bool = config.stdout and not config.user_input.user_output_folder
# Write the output DAT
try:
with (
open(pathlib.Path(input_dat.output_filename), 'w', encoding='utf-8')
if not stdout
else sys.stdout
) as output_destination:
output_destination.writelines(final_xml)
except OSError as e:
eprint(f'• {Font.b}Error{Font.be}: {e!s}\n')
raise
eprint(
f'• Creating{output_file_region.replace("(", "").replace(")", "")}{output_file_removes.replace("(", "").replace(")", "").lower()} DAT file... done.',
overwrite=True,
)
@staticmethod
def write_report(
report: tuple[dict[str, set[str]], set[str]],
removed_titles: Removes,
config: Config,
input_dat: Dat,
timestamp: str,
) -> None:
"""
Write the output file for `--report`, which contains a list of what titles have
been kept and removed.
Args:
report (tuple[dict[str, set[str]], set[DatNode]]): Contains all the titles
included and removed from the output DAT, and their relationships.
removed_titles (Removes): The Retool removes object, which contains and
categorizes all the titles that have been removed from consideration. It
is used for recovering titles defined by user includes, stats, and other
output files generated by Retool.
config (Config): The Retool config object.
input_dat (Dat): The Retool input_dat object.
timestamp (str): Timestamp used in the output filename.
"""
eprint('• Creating report file... ')
# Figure out 1G1R titles with clones
title_names_with_clones: dict[str, set[str]] = report[0]
# Figure out titles without clones
titles_without_clones: set[str] = report[1]
report_contents: list[str] = []
report_contents.append(
'This file shows which titles have been kept in the output dat with a `+`,'
'\nand which have been removed with a `-`. If the `-` is indented, then the'
'\ntitle was removed because it was a clone of the previous title with a `+`.\n'
)
if (
title_names_with_clones
or titles_without_clones
or removed_titles.add_ons_removes
or removed_titles.aftermarket_removes
or removed_titles.applications_removes
or removed_titles.audio_removes
or removed_titles.bad_dumps_removes
or removed_titles.bios_removes
or removed_titles.bonus_discs_removes
or removed_titles.coverdiscs_removes
or removed_titles.demos_removes
or removed_titles.educational_removes
or removed_titles.games_removes
or removed_titles.manuals_removes
or removed_titles.mia_removes
or removed_titles.multimedia_removes
or removed_titles.pirate_removes
or removed_titles.preproduction_removes
or removed_titles.promotional_removes
or removed_titles.unlicensed_removes
or removed_titles.video_removes
or removed_titles.clone_list_ignores
or removed_titles.mia_removes
or removed_titles.language_removes
or removed_titles.region_removes
or removed_titles.global_excludes
or removed_titles.system_excludes
or removed_titles.global_filter_removes
or removed_titles.system_filter_removes
):
report_contents.append('\nSECTIONS\n========\n')
report_contents.append(
'Search for these section names to jump to that part of the file.\n\n'
)
if title_names_with_clones:
report_contents.append('* TITLES WITH CLONES\n')
if titles_without_clones:
report_contents.append('* TITLES WITHOUT CLONES\n')
if removed_titles.add_ons_removes:
report_contents.append('* ADD-ON REMOVES\n')
if removed_titles.aftermarket_removes:
report_contents.append('* AFTERMARKET REMOVES\n')
if removed_titles.applications_removes:
report_contents.append('* APPLICATION REMOVES\n')
if removed_titles.audio_removes:
report_contents.append('* AUDIO REMOVES\n')
if removed_titles.bad_dumps_removes:
report_contents.append('* BAD DUMP REMOVES\n')
if removed_titles.bios_removes:
report_contents.append('* BIOS AND OTHER CHIP REMOVES\n')
if removed_titles.bonus_discs_removes:
report_contents.append('* BONUS DISC REMOVES\n')
if removed_titles.coverdiscs_removes:
report_contents.append('* COVERDISC REMOVES\n')
if removed_titles.demos_removes:
report_contents.append('* DEMO, KIOSK, AND SAMPLE REMOVES\n')
if removed_titles.educational_removes:
report_contents.append('* EDUCATIONAL REMOVES\n')
if removed_titles.games_removes:
report_contents.append('* GAME REMOVES\n')
if removed_titles.manuals_removes:
report_contents.append('* MANUAL REMOVES\n')
if removed_titles.mia_removes:
report_contents.append('* MIA REMOVES\n')
if removed_titles.multimedia_removes:
report_contents.append('* MULTIMEDIA REMOVES\n')
if removed_titles.pirate_removes:
report_contents.append('* PIRATE REMOVES\n')
if removed_titles.preproduction_removes:
report_contents.append('* PREPRODUCTION REMOVES\n')
if removed_titles.promotional_removes:
report_contents.append('* PROMOTIONAL REMOVES\n')
if removed_titles.unlicensed_removes:
report_contents.append('* UNLICENSED REMOVES\n')
if removed_titles.video_removes:
report_contents.append('* VIDEO REMOVES\n')
if removed_titles.clone_list_ignores:
report_contents.append('* CLONE LIST REMOVES\n')
if removed_titles.language_removes:
report_contents.append('* LANGUAGE REMOVES\n')
if removed_titles.region_removes:
report_contents.append('* REGION REMOVES\n')
if removed_titles.global_excludes:
report_contents.append('* GLOBAL EXCLUDES\n')
if removed_titles.system_excludes:
report_contents.append('* SYSTEM EXCLUDES\n')
if removed_titles.global_filter_removes:
report_contents.append('* GLOBAL POST FILTER REMOVES\n')
if removed_titles.system_filter_removes:
report_contents.append('* SYSTEM POST FILTER REMOVES\n')
report_contents.append('\n')
if title_names_with_clones:
report_contents.append('\nTITLES WITH CLONES\n==================\n\n')
# Assign clones to their 1G1R titles
for title_name, title_group in sorted(title_names_with_clones.items()):
report_contents.append(f'+ {title_name}')
for clone in sorted(title_group):
report_contents.append(f'\n - {clone}')
if clone == sorted(title_group)[-1]:
report_contents.append('\n')
if titles_without_clones:
report_contents.append('\nTITLES WITHOUT CLONES\n=====================\n\n')
for full_name in sorted(titles_without_clones):
report_contents.append(f'+ {full_name}\n')
def user_removes(removes_type: str, removes_list: set[DatNode]) -> None:
"""
Adds granular removes content to the report file.
Args:
removes_type (str): The heading for this part of the removes list.
removes_list (set[DatNode]): The titles that have been removed for
this part of the removes list.
"""
if removes_list:
report_contents.append(f'\n{removes_type.upper()} REMOVES\n')
report_contents.append('=' * len(f'{removes_type.upper()} REMOVES'))
report_contents.append(
f'\nThese titles were removed because the user excluded {removes_type} titles.\n\n'
)
for title in sorted(removes_list, key=lambda x: x.full_name):
report_contents.append(f'- {title.full_name}\n')
user_removes('add-on', removed_titles.add_ons_removes)
user_removes('aftermarket', removed_titles.aftermarket_removes)
user_removes('application', removed_titles.applications_removes)
user_removes('audio', removed_titles.audio_removes)
user_removes('bad dump', removed_titles.bad_dumps_removes)
user_removes('BIOS and other chip', removed_titles.bios_removes)
user_removes('bonus disc', removed_titles.bonus_discs_removes)
user_removes('coverdisc', removed_titles.coverdiscs_removes)
user_removes('demo, kiosk, and sample', removed_titles.demos_removes)
user_removes('educational', removed_titles.educational_removes)
user_removes('game', removed_titles.games_removes)
user_removes('manual', removed_titles.manuals_removes)
user_removes('mia', removed_titles.mia_removes)
user_removes('multimedia', removed_titles.multimedia_removes)
user_removes('pirate', removed_titles.pirate_removes)
user_removes('preproduction', removed_titles.preproduction_removes)
user_removes('promotional', removed_titles.promotional_removes)
user_removes('unlicensed', removed_titles.unlicensed_removes)
user_removes('video', removed_titles.video_removes)
if removed_titles.clone_list_ignores:
report_contents.append('\nCLONE LIST REMOVES\n==================\n')
report_contents.append(
'These titles were force removed because they were set to be ignored in the clone list.\n\n'
)
for title in sorted(removed_titles.clone_list_ignores, key=lambda x: x.full_name):
report_contents.append(f'- {title.full_name}\n')
if removed_titles.language_removes:
report_contents.append('\nLANGUAGE REMOVES\n================\n')
report_contents.append(
'These titles were removed because the user excluded one or more languages.\n\n'
)
for title in sorted(removed_titles.language_removes, key=lambda x: x.full_name):
report_contents.append(f'- {title.full_name}\n')
if removed_titles.region_removes:
report_contents.append('\nREGION REMOVES\n==============\n')
report_contents.append(
'These titles were removed because the user excluded one or more regions.\n\n'
)
for title in sorted(removed_titles.region_removes, key=lambda x: x.full_name):
report_contents.append(f'- {title.full_name}\n')
if removed_titles.global_excludes:
report_contents.append('\nGLOBAL EXCLUDES\n===============\n')
report_contents.append(
'These titles were removed because they matched the user\'s global excludes.\n\n'
)
for title in sorted(removed_titles.global_excludes, key=lambda x: x.full_name):
report_contents.append(f'- {title.full_name}\n')
if removed_titles.system_excludes:
report_contents.append('\nSYSTEM EXCLUDES\n===============\n')
report_contents.append(
'These titles were removed because they matched the user\'s system excludes.\n\n'
)
for title in sorted(removed_titles.system_excludes, key=lambda x: x.full_name):
report_contents.append(f'- {title.full_name}\n')
if removed_titles.global_filter_removes:
report_contents.append('\nGLOBAL POST FILTER REMOVES\n==========================\n')
report_contents.append(
'These titles were removed because they matched the user\'s global post filters.\n\n'
)
for title in sorted(
removed_titles.global_filter_removes, key=lambda x: x.full_name
):
report_contents.append(f'- {title.full_name}\n')
if removed_titles.system_filter_removes:
report_contents.append('\nSYSTEM POST FILTER REMOVES\n==========================\n')
report_contents.append(
'These titles were removed because they matched the user\'s system post filters.\n\n'
)
for title in sorted(
removed_titles.system_filter_removes, key=lambda x: x.full_name
):
report_contents.append(f'- {title.full_name}\n')
# Show user exclude options in the output filename
excludes: str = ''
if config.user_input.excludes:
excludes = f' [-{config.user_input.excludes}]'
output_filename: str = (
f'{config.user_input.output_folder_name}/{input_dat.name} ({input_dat.version}) (Retool {timestamp}){config.user_input.user_options}{excludes}'
)
if {'override': 'true'} in config.system_user_path_settings:
if config.system_output:
output_filename = f'{pathlib.Path(config.system_output)!s}/{input_dat.name} ({input_dat.version}) (Retool {timestamp}){config.user_input.user_options}{excludes}'
if config.user_input.test:
output_filename = f'{config.user_input.output_folder_name}/tests/comparison/{input_dat.name}{config.user_input.user_options}{excludes}'
try:
with open(
pathlib.Path(f'{output_filename} report.txt'), 'w', encoding='utf-8'
) as output_file:
output_file.writelines(report_contents)
except OSError as e:
eprint(f'• {Font.b}Error{Font.be}: {e!s}\n', level='error')
raise
eprint('• Creating report file... done.', overwrite=True)