예제 #1
0
def uninstall_mod(mod: BcmlMod, wait_merge: bool = False):
    has_patches = (mod.path / "patches").exists()
    try:
        shutil.rmtree(str(mod.path), onerror=force_del)
    except (OSError, PermissionError, WindowsError) as err:
        raise RuntimeError(
            f"The folder for {mod.name} could not be removed. "
            "You may need to delete it manually and remerge, or "
            "close all open programs (including BCML and Windows Explorer) "
            "and try again. The location of the folder is "
            f"<code>{str(mod.path)}</code>.") from err

    for fall_mod in [
            m for m in util.get_installed_mods(True)
            if m.priority > mod.priority
    ]:
        fall_mod.change_priority(fall_mod.priority - 1)

    if not util.get_installed_mods():
        shutil.rmtree(util.get_master_modpack_dir())
        util.create_bcml_graphicpack_if_needed()
    else:
        if not wait_merge:
            refresh_merges()

    if has_patches and not util.get_settings("no_cemu"):
        shutil.rmtree(
            util.get_cemu_dir() / "graphicPacks" / "bcmlPatches" /
            util.get_safe_pathname(mod.name),
            ignore_errors=True,
        )

    print(f"{mod.name} has been uninstalled.")
예제 #2
0
def uninstall_mod(mod: BcmlMod, wait_merge: bool = False):
    print(f"Uninstalling {mod.name}...")
    try:
        shutil.rmtree(str(mod.path))
    except (OSError, PermissionError) as err:
        raise RuntimeError(
            f"The folder for {mod.name} could not be removed. "
            "You may need to delete it manually and remerge, or "
            "close all open programs (including BCML and Windows Explorer) "
            "and try again. The location of the folder is "
            f"<code>{str(mod.path)}</code>.") from err

    for fall_mod in [
            m for m in util.get_installed_mods(True)
            if m.priority > mod.priority
    ]:
        fall_mod.change_priority(fall_mod.priority - 1)

    if not util.get_installed_mods():
        shutil.rmtree(util.get_master_modpack_dir())
        util.create_bcml_graphicpack_if_needed()
    else:
        if not wait_merge:
            refresh_merges()

    print(f"{mod.name} has been uninstalled.")
예제 #3
0
def get_deepmerge_mods() -> List[BcmlMod]:
    """ Gets a list of all installed mods that use deep merge """
    dmods = [
        mod for mod in util.get_installed_mods()
        if (mod.path / 'logs' / 'deepmerge.yml').exists()
    ]
    return sorted(dmods, key=lambda mod: mod.priority)
예제 #4
0
 def get_all_diffs(self):
     diffs = ParameterIO()
     for mod in util.get_installed_mods():
         diff = self.get_mod_diff(mod)
         if diff:
             merge_plists(diffs, diff, True)
     return diffs if diffs.lists or diffs.objects else None
예제 #5
0
파일: texts.py 프로젝트: StoneyMoonCat/BCML
 def get_all_diffs(self):
     diffs = []
     for mod in util.get_installed_mods():
         diff = self.get_mod_diff(mod)
         if diff:
             diffs.append(diff)
     return diffs
예제 #6
0
 def get_all_diffs(self):
     diffs = {}
     for mod in [
             mod for mod in util.get_installed_mods()
             if self.is_mod_logged(mod)
     ]:
         diffs[mod] = get_modded_packs_in_mod(mod)
     return diffs
예제 #7
0
파일: _api.py 프로젝트: arkhamsaiyan/BCML
 def get_mods(self, params):
     if not params:
         params = {"disabled": False}
     mods = [
         mod.to_json()
         for mod in util.get_installed_mods(params["disabled"])
     ]
     util.vprint(mods)
     return mods
예제 #8
0
파일: merge.py 프로젝트: NiceneNerd/BCML
 def get_all_diffs(self):
     diffs = None
     for mod in util.get_installed_mods():
         diff = self.get_mod_diff(mod)
         if diff:
             if not diffs:
                 diffs = ParameterIO()
             merge_plists(diffs, diff, True)
     return diffs
예제 #9
0
def export(output: Path):
    print("Loading files...")
    tmp_dir = Path(mkdtemp())
    if tmp_dir.exists():
        try:
            rmtree(tmp_dir)
        except (OSError, FileNotFoundError, PermissionError) as err:
            raise RuntimeError(
                "There was a problem cleaning the temporary export directory. This may be"
                " a fluke, so consider restarting BCML and trying again."
            ) from err
    link_master_mod(tmp_dir)
    print("Adding rules.txt...")
    rules_path = tmp_dir / "rules.txt"
    mods = util.get_installed_mods()
    if util.get_settings("wiiu"):
        rules_path.write_text(
            "[Definition]\n"
            "titleIds = 00050000101C9300,00050000101C9400,00050000101C9500\n"
            "name = Exported BCML Mod\n"
            "path = The Legend of Zelda: Breath of the Wild/Mods/Exported BCML\n"
            f'description = Exported merge of {", ".join([mod.name for mod in mods])}\n'
            "version = 4\n",
            encoding="utf-8",
        )
    if output.suffix == ".bnp" or output.name.endswith(".bnp.7z"):
        print("Exporting BNP...")
        dev.create_bnp_mod(
            mod=tmp_dir,
            meta={},
            output=output,
            options={"rstb": {
                "no_guess": util.get_settings("no_guess")
            }},
        )
    else:
        print("Exporting as graphic pack mod...")
        x_args = [get_7z_path(), "a", str(output), f'{str(tmp_dir / "*")}']
        result: subprocess.CompletedProcess
        if os.name == "nt":
            result = subprocess.run(
                x_args,
                creationflags=util.CREATE_NO_WINDOW,
                check=False,
                capture_output=True,
                universal_newlines=True,
            )
        else:
            result = subprocess.run(x_args,
                                    check=False,
                                    capture_output=True,
                                    universal_newlines=True)
        if result.stderr:
            raise RuntimeError(
                f"There was an error exporting your mod(s). {result.stderr}")
    rmtree(tmp_dir, True)
예제 #10
0
def get_pack_mods() -> List[BcmlMod]:
    """
    Gets a list of all installed pack mods

    :return: Returns a list of mods that modify pack files
    :rtype: list of class:`bcml.util.BcmlMod`
    """
    pmods = [mod for mod in util.get_installed_mods() if (
        mod.path / 'logs' / 'packs.log').exists()]
    return sorted(pmods, key=lambda mod: mod.priority)
예제 #11
0
def merge_events():
    """ Merges all installed event info mods """
    event_mods = [mod for mod in util.get_installed_mods() \
                  if (mod.path / 'logs' / 'eventinfo.yml').exists()]
    merged_events = util.get_master_modpack_dir() / 'logs' / 'eventinfo.byml'
    event_merge_log = util.get_master_modpack_dir() / 'logs' / 'eventinfo.log'
    event_mod_hash = str(hash(tuple(event_mods)))

    if not event_mods:
        print('No event info merging necessary')
        if merged_events.exists():
            merged_events.unlink()
            event_merge_log.unlink()
            try:
                stock_eventinfo = util.get_nested_file_bytes(
                    str(util.get_game_file('Pack/Bootup.pack')) + '//Event/EventInfo.product.sbyml',
                    unyaz=False
                )
                util.inject_file_into_bootup(
                    'Event/EventInfo.product.sbyml',
                    stock_eventinfo
                )
            except FileNotFoundError:
                pass
        return
    if event_merge_log.exists() and event_merge_log.read_text() == event_mod_hash:
        print('No event info merging necessary')
        return

    print('Loading event info mods...')
    modded_events = {}
    for mod in event_mods:
        modded_events.update(get_events_for_mod(mod))
    new_events = get_stock_eventinfo()
    for event, data in modded_events.items():
        new_events[event] = data

    print('Writing new event info...')
    event_bytes = byml.Writer(new_events, be=True).get_bytes()
    util.inject_file_into_bootup(
        'Event/EventInfo.product.sbyml',
        util.compress(event_bytes),
        create_bootup=True
    )
    print('Saving event info merge log...')
    event_merge_log.write_text(event_mod_hash)
    merged_events.write_bytes(event_bytes)

    print('Updating RSTB...')
    rstb_size = rstb.SizeCalculator().calculate_file_size_with_ext(event_bytes, True, '.byml')
    rstable.set_size('Event/EventInfo.product.byml', rstb_size)
예제 #12
0
파일: _api.py 프로젝트: arkhamsaiyan/BCML
 def export(self):
     if not util.get_installed_mods():
         raise Exception("No mods installed to export.")
     out = self.window.create_file_dialog(
         webviewb.SAVE_DIALOG,
         file_types=(
             f"{('Graphic Pack' if util.get_settings('wiiu') else 'Atmosphere')} (*.zip)",
             "BOTW Nano Patch (*.bnp)",
         ),
         save_filename="exported-mods.zip",
     )
     if out:
         output = Path(out if isinstance(out, str) else out[0])
         install.export(output)
예제 #13
0
파일: _api.py 프로젝트: VelouriasMoon/BCML
 def save_mod_list(self, params=None):
     result = self.window.create_file_dialog(
         webviewb.SAVE_DIALOG,
         file_types=("JSON File (*.json)",),
         allow_multiple=False,
     )
     if not result:
         return
     out = Path(result if isinstance(result, str) else result[0])
     out.write_text(
         json.dumps(
             [mod.to_json() for mod in util.get_installed_mods(disabled=True)],
             indent=4,
         )
     )
예제 #14
0
파일: install.py 프로젝트: sammysung/BCML
def refresh_cemu_mods():
    """ Updates Cemu's enabled graphic packs """
    setpath = util.get_cemu_dir() / 'settings.xml'
    if not setpath.exists():
        raise FileNotFoundError('The Cemu settings file could not be found.')
    setread = ''
    with setpath.open('r') as setfile:
        for line in setfile:
            setread += line.strip()
    settings = minidom.parseString(setread)
    try:
        gpack = settings.getElementsByTagName('GraphicPack')[0]
    except IndexError:
        gpack = settings.createElement('GraphicPack')
        settings.appendChild(gpack)
    # Issue #33 - check for new cemu Entry layout
    new_cemu_version = False
    for entry in gpack.getElementsByTagName('Entry'):
        if len(entry.getElementsByTagName('filename')) == 0:
            new_cemu_version = True
            break
    # Issue #33 - end Entry layout check
    for entry in gpack.getElementsByTagName('Entry'):
        # Issue #33 - handle BCML node by Cemu version
        if new_cemu_version:
            if 'BCML' in entry.getAttribute('filename'):
                gpack.removeChild(entry)
        else:
            try:
                if 'BCML' in entry.getElementsByTagName(
                        'filename')[0].childNodes[0].data:
                    gpack.removeChild(entry)
            except IndexError:
                pass
    bcmlentry = create_settings_mod_node(settings, new_cemu_version)
    # Issue #33 - end BCML node
    gpack.appendChild(bcmlentry)
    for mod in util.get_installed_mods():
        # Issue #33 - handle new mod nodes by Cemu version
        modentry = create_settings_mod_node(settings, new_cemu_version, mod)
        # Issue #33 - end handling new mod nodes
        gpack.appendChild(modentry)
    settings.writexml(setpath.open('w', encoding='utf-8'),
                      addindent='    ',
                      newl='\n')
예제 #15
0
파일: _api.py 프로젝트: arkhamsaiyan/BCML
 def remerge(self, params):
     try:
         if not util.get_installed_mods():
             if util.get_master_modpack_dir().exists():
                 rmtree(util.get_master_modpack_dir())
                 install.link_master_mod()
             return
         if params["name"] == "all":
             install.refresh_merges()
         else:
             [
                 m() for m in mergers.get_mergers()
                 if m().friendly_name == params["name"]
             ][0].perform_merge()
     except Exception as err:  # pylint: disable=broad-except
         raise Exception(
             f"There was an error merging your mods. {str(err)}\n"
             "Note that this could leave your game in an unplayable state.")
예제 #16
0
def generate_master_rstb(verbose: bool = False):
    """Merges all installed RSTB modifications"""
    print('Merging RSTB changes...')
    if (util.get_master_modpack_dir() / 'logs' / 'master-rstb.log').exists():
        (util.get_master_modpack_dir() / 'logs' / 'master-rstb.log').unlink()

    table = get_stock_rstb()
    rstb_values = {}
    for mod in util.get_installed_mods():
        rstb_values.update(get_mod_rstb_values(mod))
    if (util.get_master_modpack_dir() / 'logs' / 'rstb.log').exists():
        rstb_values.update(get_mod_rstb_values(util.get_master_modpack_dir()))
    if (util.get_master_modpack_dir() / 'logs' / 'map.log').exists():
        rstb_values.update(get_mod_rstb_values(
            util.get_master_modpack_dir(), log_name='map.log'))

    table, rstb_changes = merge_rstb(table, rstb_values)
    for change in rstb_changes:
        if not change[1] or (change[1] and verbose):
            print(change[0])

    for bootup_pack in util.get_master_modpack_dir().glob('content/Pack/Bootup_*.pack'):
        lang = util.get_file_language(bootup_pack)
        if table.is_in_table(f'Message/Msg_{lang}.product.sarc'):
            table.delete_entry(f'Message/Msg_{lang}.product.sarc')

    rstb_path = util.get_master_modpack_dir() / 'content' / 'System' / 'Resource' / \
                                                'ResourceSizeTable.product.srsizetable'
    if not rstb_path.exists():
        rstb_path.parent.mkdir(parents=True, exist_ok=True)
    with rstb_path.open('wb') as r_file:
        with io.BytesIO() as buf:
            table.write(buf, True)
            r_file.write(util.compress(buf.getvalue()))

    rstb_log = util.get_master_modpack_dir() / 'logs' / 'master-rstb.log'
    rstb_log.parent.mkdir(parents=True, exist_ok=True)
    with rstb_log.open('w', encoding='utf-8') as r_file:
        r_file.write('\n'.join([change[0].strip() for change in rstb_changes]))
예제 #17
0
파일: pack.py 프로젝트: StoneyMoonCat/BCML
 def get_all_diffs(self):
     diffs = {}
     for mod in util.get_installed_mods():
         diffs[mod] = self.get_mod_diff(mod)
     return diffs
예제 #18
0
 def get_all_diffs(self):
     diffs = []
     for mod in [mod for mod in util.get_installed_mods() if self.is_mod_logged(mod)]:
         diffs.append(self.get_mod_diff(mod))
     return diffs
예제 #19
0
파일: install.py 프로젝트: sammysung/BCML
def install_mod(mod: Path,
                verbose: bool = False,
                options: dict = None,
                wait_merge: bool = False,
                insert_priority: int = 0):
    """
    Installs a graphic pack mod, merging RSTB changes and optionally packs and texts

    :param mod: Path to the mod to install. Must be a RAR, 7z, or ZIP archive or a graphicpack
    directory containing a rules.txt file.
    :type mod: class:`pathlib.Path`
    :param verbose: Whether to display more detailed output, defaults to False.
    :type verbose: bool, optional
    :param wait_merge: Install mod and log changes, but wait to run merge manually,
    defaults to False.
    :type wait_merge: bool, optional
    :param insert_priority: Insert mod(s) at priority specified, defaults to get_next_priority().
    :type insert_priority: int
    """
    if insert_priority == 0:
        insert_priority = get_next_priority()
    util.create_bcml_graphicpack_if_needed()
    if isinstance(mod, str):
        mod = Path(mod)
    if mod.is_file():
        print('Extracting mod...')
        tmp_dir = open_mod(mod)
    elif mod.is_dir():
        if (mod / 'rules.txt').exists():
            print(f'Loading mod from {str(mod)}...')
            tmp_dir = util.get_work_dir() / f'tmp_{mod.name}'
            shutil.copytree(str(mod), str(tmp_dir))
        else:
            print(f'Cannot open mod at {str(mod)}, no rules.txt found')
            return
    else:
        print(f'Error: {str(mod)} is neither a valid file nor a directory')
        return

    pool: Pool = None
    try:
        rules = util.RulesParser()
        rules.read(tmp_dir / 'rules.txt')
        mod_name = str(rules['Definition']['name']).strip(' "\'')
        print(f'Identified mod: {mod_name}')

        logs = tmp_dir / 'logs'
        if logs.exists():
            print('This mod supports Quick Install! Loading changes...')
            for merger in [merger() for merger in mergers.get_mergers() \
                           if merger.NAME in options['disable']]:
                if merger.is_mod_logged(BcmlMod('', 0, tmp_dir)):
                    (tmp_dir / 'logs' / merger.log_name()).unlink()
        else:
            pool = Pool(cpu_count())
            generate_logs(tmp_dir=tmp_dir,
                          verbose=verbose,
                          options=options,
                          original_pool=pool)
    except Exception as e:  # pylint: disable=broad-except
        if hasattr(e, 'error_text'):
            raise e
        clean_error = RuntimeError()
        try:
            name = mod_name
        except NameError:
            name = 'your mod, the name of which could not be detected'
        clean_error.error_text = (
            f'There was an error while processing {name}. '
            'This could indicate there is a problem with the mod itself, '
            'but it could also reflect a new or unusual edge case BCML does '
            'not anticipate. Here is the error:\n\n'
            f'{traceback.format_exc(limit=-4)}')
        raise clean_error

    priority = insert_priority
    print(f'Assigned mod priority of {priority}')
    mod_id = util.get_mod_id(mod_name, priority)
    mod_dir = util.get_modpack_dir() / mod_id

    try:
        for existing_mod in util.get_installed_mods():
            if existing_mod.priority >= priority:
                priority_shifted = existing_mod.priority + 1
                new_id = util.get_mod_id(existing_mod.name, priority_shifted)
                new_path = util.get_modpack_dir() / new_id
                shutil.move(str(existing_mod.path), str(new_path))
                existing_mod_rules = util.RulesParser()
                existing_mod_rules.read(str(new_path / 'rules.txt'))
                existing_mod_rules['Definition']['fsPriority'] = str(
                    priority_shifted)
                with (new_path / 'rules.txt').open('w',
                                                   encoding='utf-8') as r_file:
                    existing_mod_rules.write(r_file)

        mod_dir.parent.mkdir(parents=True, exist_ok=True)
        print()
        print(f'Moving mod to {str(mod_dir)}...')
        if mod.is_file():
            try:
                shutil.move(str(tmp_dir), str(mod_dir))
            except Exception:  # pylint: disable=broad-except
                try:
                    shutil.copytree(str(tmp_dir), str(mod_dir))
                    try:
                        shutil.rmtree(str(tmp_dir))
                    except Exception:  # pylint: disable=broad-except
                        pass
                except Exception:  # pylint: disable=broad-except
                    raise OSError(
                        'BCML could not transfer your mod from the temp directory '
                        'to the BCML directory.')
        elif mod.is_dir():
            shutil.copytree(str(tmp_dir), str(mod_dir))

        rulepath = os.path.basename(rules['Definition']['path']).replace(
            '"', '')
        rules['Definition']['path'] = f'{{BCML: DON\'T TOUCH}}/{rulepath}'
        rules['Definition']['fsPriority'] = str(priority)
        with Path(mod_dir / 'rules.txt').open('w', encoding='utf-8') as r_file:
            rules.write(r_file)

        output_mod = BcmlMod(mod_name, priority, mod_dir)
        try:
            util.get_mod_link_meta(rules)
            util.get_mod_preview(output_mod, rules)
        except Exception:  # pylint: disable=broad-except
            pass

        print(f'Enabling {mod_name} in Cemu...')
        refresh_cemu_mods()
    except Exception:  # pylint: disable=broad-except
        clean_error = RuntimeError()
        clean_error.error_text = (
            f'There was an error installing {mod_name}. '
            'It processed successfully, but could not be added to your BCML '
            'mods. This may indicate a problem with your BCML installation. '
            'Here is the error:\n\n'
            f'{traceback.format_exc(limit=-4)}\n\n'
            f'{mod_name} is being removed and no changes will be made.')
        if mod_dir.exists():
            try:
                uninstall_mod(mod_dir, wait_merge=True)
            except Exception:  # pylint: disable=broad-except
                shutil.rmtree(str(mod_dir))
        raise clean_error

    if wait_merge:
        print('Mod installed, merge still pending...')
    else:
        try:
            if not pool:
                pool = Pool(cpu_count)
            print('Performing merges...')
            if not options:
                options = {}
            if 'disable' not in options:
                options['disable'] = []
            for merger in mergers.sort_mergers([cls() for cls in mergers.get_mergers() \
                                                if cls.NAME not in options['disable']]):
                merger.set_pool(pool)
                if merger.NAME in options:
                    merger.set_options(options[merger.NAME])
                if merger.is_mod_logged(output_mod):
                    merger.perform_merge()
            print()
            print(f'{mod_name} installed successfully!')
            pool.close()
            pool.join()
        except Exception:  # pylint: disable=broad-except
            clean_error = RuntimeError()
            clean_error.error_text = (
                f'There was an error merging {mod_name}. '
                'It processed and installed without error, but it has not '
                'successfully merged with your other mods. '
                'Here is the error:\n\n'
                f'{traceback.format_exc(limit=-4)}\n\n'
                f'To protect your mod setup, BCML will remove {mod_name} '
                'and remerge.')
            try:
                uninstall_mod(mod_dir)
            except FileNotFoundError:
                pass
            raise clean_error
    return output_mod
예제 #20
0
 def get_all_diffs(self):
     diffs = []
     for mod in util.get_installed_mods():
         diffs.extend(self.get_mod_diff(mod))
     return diffs
예제 #21
0
파일: install.py 프로젝트: sammysung/BCML
def change_mod_priority(path: Path,
                        new_priority: int,
                        wait_merge: bool = False,
                        verbose: bool = False):
    """
    Changes the priority of a mod

    :param path: The path to the mod.
    :type path: class:`pathlib.Path`
    :param new_priority: The new priority of the mod.
    :type new_priority: int
    :param wait_merge: Resort priorities but don't remerge anything yet, defaults to False.
    :type wait_merge: bool, optional
    :param verbose: Whether to display more detailed output, defaults to False.
    :type verbose: bool, optional
    """
    mod = util.get_mod_info(path / 'rules.txt')
    print(
        f'Changing priority of {mod.name} from {mod.priority} to {new_priority}...'
    )
    mods = util.get_installed_mods()
    if new_priority > mods[len(mods) - 1][1]:
        new_priority = len(mods) - 1
    mods.remove(mod)
    mods.insert(new_priority - 100, util.BcmlMod(mod.name, new_priority, path))

    all_mergers = [merger() for merger in mergers.get_mergers()]
    remergers = set()
    partials = {}
    for merger in all_mergers:
        if merger.is_mod_logged(mod):
            remergers.add(merger)
            if merger.can_partial_remerge():
                partials[merger.NAME] = set(merger.get_mod_affected(mod))

    print('Resorting other affected mods...')
    for mod in mods:
        if mod.priority != (mods.index(mod) + 100):
            adjusted_priority = mods.index(mod) + 100
            mods.remove(mod)
            mods.insert(adjusted_priority - 100,
                        BcmlMod(mod.name, adjusted_priority, mod.path))
            if verbose:
                print(f'Changing priority of {mod.name} from'
                      f'{mod.priority} to {adjusted_priority}...')
    for mod in mods:
        if not mod.path.stem.startswith(f'{mod.priority:04}'):
            for merger in all_mergers:
                if merger.is_mod_logged(mod):
                    remergers.add(merger)
                    if merger.can_partial_remerge():
                        if merger.NAME not in partials:
                            partials[merger.NAME] = set()
                        partials[merger.NAME] |= set(
                            merger.get_mod_affected(mod))

            new_mod_id = util.get_mod_id(mod[0], mod[1])
            shutil.move(str(mod[2]), str(mod[2].parent / new_mod_id))
            rules = util.RulesParser()
            rules.read(str(mod.path.parent / new_mod_id / 'rules.txt'))
            rules['Definition']['fsPriority'] = str(mod[1])
            with (mod[2].parent / new_mod_id / 'rules.txt').open(
                    'w', encoding='utf-8') as r_file:
                rules.write(r_file)
            refresh_cemu_mods()
    if not wait_merge:
        for merger in mergers.sort_mergers(remergers):
            if merger.NAME in partials:
                merger.set_options({'only_these': partials[merger.NAME]})
            merger.perform_merge()
    if wait_merge:
        print('Mods resorted, will need to remerge later')
    print('Finished updating mod priorities.')
예제 #22
0
def install_mod(
    mod: Path,
    options: dict = None,
    selects: dict = None,
    pool: Optional[multiprocessing.pool.Pool] = None,
    insert_priority: int = 0,
    merge_now: bool = False,
    updated: bool = False,
):
    if not insert_priority:
        insert_priority = get_next_priority()

    try:
        if isinstance(mod, str):
            mod = Path(mod)
        if mod.is_file():
            print("Opening mod...")
            tmp_dir = open_mod(mod)
        elif mod.is_dir():
            if not ((mod / "rules.txt").exists() or
                    (mod / "info.json").exists()):
                print(
                    f"Cannot open mod at {str(mod)}, no rules.txt or info.json found"
                )
                return
            print(f"Loading mod from {str(mod)}...")
            tmp_dir = Path(mkdtemp())
            if tmp_dir.exists():
                shutil.rmtree(tmp_dir)
            shutil.copytree(str(mod), str(tmp_dir))
            if (mod /
                    "rules.txt").exists() and not (mod / "info.json").exists():
                print("Upgrading old mod format...")
                upgrade.convert_old_mod(mod, delete_old=True)
        else:
            print(f"Error: {str(mod)} is neither a valid file nor a directory")
            return
    except Exception as err:  # pylint: disable=broad-except
        raise util.InstallError(err) from err

    if not options:
        options = {"options": {}, "disable": []}

    this_pool: Optional[multiprocessing.pool.Pool] = None  # type: ignore
    try:
        rules = json.loads((tmp_dir / "info.json").read_text("utf-8"))
        mod_name = rules["name"].strip(" '\"").replace("_", "")
        print(f"Identified mod: {mod_name}")
        if rules["depends"]:
            try:
                installed_metas = {
                    v[0]: v[1]
                    for m in util.get_installed_mods()
                    for v in util.BcmlMod.meta_from_id(m.id)
                }
            except (IndexError, TypeError) as err:
                raise RuntimeError(
                    f"This BNP has invalid or corrupt dependency data.")
            for depend in rules["depends"]:
                depend_name, depend_version = util.BcmlMod.meta_from_id(depend)
                if (depend_name not in installed_metas) or (
                        depend_name in installed_metas
                        and depend_version > installed_metas[depend_name]):
                    raise RuntimeError(
                        f"{mod_name} requires {depend_name} version {depend_version}, "
                        f"but it is not installed. Please install {depend_name} and "
                        "try again.")
        friendly_plaform = lambda p: "Wii U" if p == "wiiu" else "Switch"
        user_platform = "wiiu" if util.get_settings("wiiu") else "switch"
        if rules["platform"] != user_platform:
            raise ValueError(
                f'"{mod_name}" is for {friendly_plaform(rules["platform"])}, not '
                f" {friendly_plaform(user_platform)}.'")
        if "priority" in rules and rules["priority"] == "base":
            insert_priority = 100

        logs = tmp_dir / "logs"
        if logs.exists():
            print("Loading mod logs...")
            for merger in [
                    merger()  # type: ignore
                    for merger in mergers.get_mergers()
                    if merger.NAME in options["disable"]
            ]:
                if merger.is_mod_logged(BcmlMod(tmp_dir)):
                    (tmp_dir / "logs" / merger.log_name).unlink()
        else:
            this_pool = pool or Pool(maxtasksperchild=500)
            dev._pack_sarcs(tmp_dir,
                            util.get_hash_table(util.get_settings("wiiu")),
                            this_pool)
            generate_logs(tmp_dir=tmp_dir, options=options, pool=this_pool)
            if not util.get_settings("strip_gfx"):
                (tmp_dir / ".processed").touch()
    except Exception as err:  # pylint: disable=broad-except
        try:
            name = mod_name
        except NameError:
            name = "your mod, the name of which could not be detected"
        raise util.InstallError(err, name) from err

    if selects:
        for opt_dir in {
                d
                for d in (tmp_dir / "options").glob("*") if d.is_dir()
        }:
            if opt_dir.name not in selects:
                shutil.rmtree(opt_dir, ignore_errors=True)
            else:
                file: Path
                for file in {
                        f
                        for f in opt_dir.rglob("**/*")
                        if ("logs" not in f.parts and f.is_file())
                }:
                    out = tmp_dir / file.relative_to(opt_dir)
                    out.parent.mkdir(parents=True, exist_ok=True)
                    try:
                        os.link(file, out)
                    except FileExistsError:
                        if file.suffix in util.SARC_EXTS:
                            try:
                                old_sarc = oead.Sarc(
                                    util.unyaz_if_needed(out.read_bytes()))
                            except (ValueError, oead.InvalidDataError,
                                    RuntimeError):
                                out.unlink()
                                os.link(file, out)
                            try:
                                link_sarc = oead.Sarc(
                                    util.unyaz_if_needed(file.read_bytes()))
                            except (ValueError, oead.InvalidDataError,
                                    RuntimeError):
                                del old_sarc
                                continue
                            new_sarc = oead.SarcWriter.from_sarc(link_sarc)
                            link_files = {
                                f.name
                                for f in link_sarc.get_files()
                            }
                            for sarc_file in old_sarc.get_files():
                                if sarc_file.name not in link_files:
                                    new_sarc.files[sarc_file.name] = bytes(
                                        sarc_file.data)
                            del old_sarc
                            del link_sarc
                            out.write_bytes(new_sarc.write()[1])
                            del new_sarc
                        else:
                            out.unlink()
                            os.link(file, out)

    rstb_path = (tmp_dir / util.get_content_path() / "System" / "Resource" /
                 "ResourceSizeTable.product.srsizetable")
    if rstb_path.exists():
        rstb_path.unlink()

    priority = insert_priority
    print(f"Assigned mod priority of {priority}")
    mod_id = util.get_mod_id(mod_name, priority)
    mod_dir = util.get_modpack_dir() / mod_id

    try:
        if not updated:
            for existing_mod in util.get_installed_mods(True):
                if existing_mod.priority >= priority:
                    existing_mod.change_priority(existing_mod.priority + 1)

        if (tmp_dir / "patches").exists() and not util.get_settings("no_cemu"):
            patch_dir = (util.get_cemu_dir() / "graphicPacks" /
                         f"bcmlPatches" /
                         util.get_safe_pathname(rules["name"]))
            patch_dir.mkdir(parents=True, exist_ok=True)
            for file in {
                    f
                    for f in (tmp_dir / "patches").rglob("*") if f.is_file()
            }:
                out = patch_dir / file.relative_to(tmp_dir / "patches")
                out.parent.mkdir(parents=True, exist_ok=True)
                shutil.copyfile(file, out)

        mod_dir.parent.mkdir(parents=True, exist_ok=True)
        print(f"Moving mod to {str(mod_dir)}...")
        if mod.is_file():
            try:
                shutil.move(str(tmp_dir), str(mod_dir))
            except Exception:  # pylint: disable=broad-except
                try:
                    shutil.rmtree(str(mod_dir))
                    shutil.copytree(str(tmp_dir), str(mod_dir))
                    shutil.rmtree(str(tmp_dir), ignore_errors=True)
                except Exception:  # pylint: disable=broad-except
                    raise OSError(
                        "BCML could not transfer your mod from the temp directory to the"
                        " BCML directory.")
        elif mod.is_dir():
            shutil.copytree(str(tmp_dir), str(mod_dir))

        shutil.rmtree(tmp_dir, ignore_errors=True)

        rules["priority"] = priority
        (mod_dir / "info.json").write_text(json.dumps(rules,
                                                      ensure_ascii=False,
                                                      indent=2),
                                           encoding="utf-8")
        (mod_dir / "options.json").write_text(json.dumps(options,
                                                         ensure_ascii=False,
                                                         indent=2),
                                              encoding="utf-8")

        output_mod = BcmlMod(mod_dir)
        try:
            util.get_mod_link_meta(rules)
            util.get_mod_preview(output_mod)
        except Exception:  # pylint: disable=broad-except
            pass
    except Exception as err:  # pylint: disable=broad-except
        if mod_dir.exists():
            try:
                uninstall_mod(mod_dir, wait_merge=True)
            except Exception:  # pylint: disable=broad-except
                shutil.rmtree(str(mod_dir))
        raise util.InstallError(err, mod_name) from err

    try:
        if merge_now:
            for merger in [m() for m in mergers.get_mergers()]:
                if this_pool or pool:
                    merger.set_pool(this_pool or pool)
                if merger.NAME in options["options"]:
                    merger.set_options(options["options"][merger.NAME])
                merger.perform_merge()
    except Exception as err:  # pylint: disable=broad-except
        raise util.MergeError(err) from err

    if this_pool and not pool:
        this_pool.close()
        this_pool.join()
    return output_mod