From d97b588cf56dd2b05c208fe79a1bd50e1e476bc9 Mon Sep 17 00:00:00 2001 From: fireundubh Date: Mon, 25 Sep 2023 05:13:22 -0700 Subject: [PATCH 01/15] Updated license --- LICENSE | 391 +++++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 373 insertions(+), 18 deletions(-) diff --git a/LICENSE b/LICENSE index 5a5ae26c..2702903c 100644 --- a/LICENSE +++ b/LICENSE @@ -1,20 +1,375 @@ -The MIT License (MIT) - Copyright (c) 2019 fireundubh -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. \ No newline at end of file From 6cbd9516bbb2e39dc9bfeaec781d3da0c5bbd225 Mon Sep 17 00:00:00 2001 From: fireundubh Date: Sat, 9 Sep 2023 13:38:17 -0700 Subject: [PATCH 02/15] Added preliminary support for Starfield projects --- pyro/Constants.py | 3 +++ pyro/PackageManager.py | 2 +- pyro/PapyrusProject.py | 6 +++--- pyro/PapyrusProject.xsd | 1 + pyro/ProjectBase.py | 12 ++++++++++++ pyro/__main__.py | 4 ++-- 6 files changed, 22 insertions(+), 6 deletions(-) diff --git a/pyro/Constants.py b/pyro/Constants.py index e972e042..c1146268 100644 --- a/pyro/Constants.py +++ b/pyro/Constants.py @@ -3,18 +3,21 @@ class FlagsName(Constant): FO4: str = 'Institute_Papyrus_Flags.flg' + SF1: str = 'Starfield_Papyrus_Flags.flg' SSE: str = 'TESV_Papyrus_Flags.flg' TES5: str = 'TESV_Papyrus_Flags.flg' class GameName(Constant): FO4: str = 'Fallout 4' + SF1: str = 'Starfield' SSE: str = 'Skyrim Special Edition' TES5: str = 'Skyrim' class GameType(Constant): FO4: str = 'fo4' + SF1: str = 'sf1' SSE: str = 'sse' TES5: str = 'tes5' diff --git a/pyro/PackageManager.py b/pyro/PackageManager.py index 41f78bf6..3676e61d 100644 --- a/pyro/PackageManager.py +++ b/pyro/PackageManager.py @@ -213,7 +213,7 @@ def build_commands(self, containing_folder: str, output_path: str) -> str: flags = wcmatch.RECURSIVE | wcmatch.IGNORECASE - if self.options.game_type == GameType.FO4: + if self.options.game_type == GameType.FO4 or self.options.game_type == GameType.SF1: for _ in wcmatch.WcMatch(containing_folder, '!*.dds', flags=flags).imatch(): arguments.append('-fo4') break diff --git a/pyro/PapyrusProject.py b/pyro/PapyrusProject.py index 6511175a..314a0221 100644 --- a/pyro/PapyrusProject.py +++ b/pyro/PapyrusProject.py @@ -752,11 +752,11 @@ def build_commands(self) -> list: for object_name, script_path in psc_paths.items(): import_paths: list = self.import_paths - if self.options.game_type != GameType.FO4: + if self.options.game_type != GameType.FO4 and self.options.game_type != GameType.SF1: object_name = script_path # remove unnecessary import paths for script - if self.options.game_type == GameType.FO4: + if self.options.game_type == GameType.FO4 or self.options.game_type == GameType.SF1: for import_path in reversed(self.import_paths): if self._can_remove_folder(import_path, object_name, script_path): import_paths.remove(import_path) @@ -768,7 +768,7 @@ def build_commands(self) -> list: arguments.append(';'.join(import_paths), key='i', enquote_value=True) arguments.append(output_path, key='o', enquote_value=True) - if self.options.game_type == GameType.FO4: + if self.options.game_type == GameType.FO4 or self.options.game_type == GameType.SF1: # noinspection PyUnboundLocalVariable if self.release: arguments.append('-release') diff --git a/pyro/PapyrusProject.xsd b/pyro/PapyrusProject.xsd index 10e33bce..bd7dce0b 100644 --- a/pyro/PapyrusProject.xsd +++ b/pyro/PapyrusProject.xsd @@ -151,6 +151,7 @@ + diff --git a/pyro/ProjectBase.py b/pyro/ProjectBase.py index 706843f1..1ea6f375 100644 --- a/pyro/ProjectBase.py +++ b/pyro/ProjectBase.py @@ -117,6 +117,8 @@ def get_flags_path(self) -> str: if self.options.game_path: if endswith(self.options.game_path, GameName.FO4, ignorecase=True): return FlagsName.FO4 + if endswith(self.options.game_path, GameName.SF1, ignorecase=True): + return FlagsName.SF1 return FlagsName.TES5 @@ -155,6 +157,8 @@ def get_registry_path(self, game_type: str = '') -> str: game_name = GameName.get(game_type) else: raise KeyError('Cannot determine registry path from game type') + if startswith(game_name, 'Starfield'): + return r'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Steam App 1716740\InstallLocation' if startswith(game_name, 'Fallout'): game_name = game_name.replace(' ', '') return rf'HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Bethesda Softworks\{game_name}\Installed Path' @@ -233,6 +237,10 @@ def get_remote_temp_path(self) -> str: @staticmethod def _get_game_type_from_path(path: str) -> str: parts: list = path.casefold().split(os.sep) + if GameName.SF1.casefold() in parts: + return GameType.SF1 + if GameName.SF1.casefold().replace(' ', '') in parts: + return GameType.SF1 if GameName.FO4.casefold() in parts: return GameType.FO4 if GameName.FO4.casefold().replace(' ', '') in parts: @@ -269,6 +277,10 @@ def get_game_type(self) -> str: return game_type if self.options.flags_path: + if endswith(self.options.flags_path, FlagsName.SF1, ignorecase=True): + ProjectBase.log.info(f'Using game type: {GameName.FO4} (determined from flags path)') + return GameType.SF1 + if endswith(self.options.flags_path, FlagsName.FO4, ignorecase=True): ProjectBase.log.info(f'Using game type: {GameName.FO4} (determined from flags path)') return GameType.FO4 diff --git a/pyro/__main__.py b/pyro/__main__.py index 7089b77c..a1b43d08 100644 --- a/pyro/__main__.py +++ b/pyro/__main__.py @@ -62,8 +62,8 @@ _game_arguments = _parser.add_argument_group('game arguments') _game_arguments.add_argument('-g', '--game-type', action='store', type=str, - choices=('fo4', 'tes5', 'sse'), - help='set game type (choices: fo4, tes5, sse)') + choices=('fo4', 'tes5', 'sf1', 'sse'), + help='set game type (choices: fo4, tes5, sf1, sse)') _game_path_arguments = _game_arguments.add_mutually_exclusive_group() _game_path_arguments.add_argument('--game-path', From 21b424f0dfe7216213dda813c53fe2310d725832 Mon Sep 17 00:00:00 2001 From: fireundubh Date: Sat, 23 Sep 2023 16:18:29 -0700 Subject: [PATCH 03/15] Added --log-level argument --- pyro/Application.py | 7 +++++++ pyro/__main__.py | 4 ++++ 2 files changed, 11 insertions(+) diff --git a/pyro/Application.py b/pyro/Application.py index c11593d6..c90d8380 100644 --- a/pyro/Application.py +++ b/pyro/Application.py @@ -32,6 +32,13 @@ def __init__(self, parser: argparse.ArgumentParser) -> None: self.parser.print_help() sys.exit(1) + # set up log levels + log_level_argv = self.args.log_level.upper() + log_level = getattr(logging, log_level_argv, logging.DEBUG) + self.log.setLevel(log_level) + + Application.log.debug(f'Set log level to: {log_level_argv}') + self.args.input_path = self._try_fix_input_path(self.args.input_path or self.args.input_path_deprecated) if not self.args.create_project and not os.path.isfile(self.args.input_path): diff --git a/pyro/__main__.py b/pyro/__main__.py index a1b43d08..f82a2b46 100644 --- a/pyro/__main__.py +++ b/pyro/__main__.py @@ -121,6 +121,10 @@ help='resolve variables and paths in project file') _program_arguments = _parser.add_argument_group('program arguments') + _program_arguments.add_argument('--log-level', dest='log_level', + action='store', type=str, default='debug', + choices=('all', 'debug', 'info', 'warn', 'error', 'fatal'), + help='show help and exit') _program_arguments.add_argument('--help', dest='show_help', action='store_true', default=False, help='show help and exit') From 6e8d999c99f8fb8726814c37db481268d2dde09a Mon Sep 17 00:00:00 2001 From: fireundubh Date: Sat, 23 Sep 2023 16:27:07 -0700 Subject: [PATCH 04/15] Fixed issue where empty commands could become cascading errors --- pyro/BuildFacade.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyro/BuildFacade.py b/pyro/BuildFacade.py index 8c4526f3..53092263 100644 --- a/pyro/BuildFacade.py +++ b/pyro/BuildFacade.py @@ -86,7 +86,7 @@ def _limit_priority() -> None: def try_compile(self) -> None: """Builds and passes commands to Papyrus Compiler""" - commands: list = self.ppj.build_commands() + commands: list = [c for c in self.ppj.build_commands() if c] self.compile_data.command_count = len(commands) From d62c752477f5570c329ad700671f3a533c5ee74b Mon Sep 17 00:00:00 2001 From: fireundubh Date: Sat, 23 Sep 2023 16:29:00 -0700 Subject: [PATCH 05/15] Disabled event command concatenation due to OS limit (commands will run sequentially in separate processes) --- pyro/ProcessManager.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/pyro/ProcessManager.py b/pyro/ProcessManager.py index acc9a9c1..20ed3622 100644 --- a/pyro/ProcessManager.py +++ b/pyro/ProcessManager.py @@ -36,11 +36,13 @@ def run_event(event_node: etree.ElementBase, project_path: str) -> None: ws: re.Pattern = re.compile('[ \t\n\r]+') environ: dict = os.environ.copy() - command: str = ' && '.join( - ws.sub(' ', node.text) - for node in filter(is_command_node, event_node) - ) + # command: str = ' && '.join( + # ws.sub(' ', node.text) + # for node in filter(is_command_node, event_node) + # ) + for node in filter(is_command_node, event_node): + command = ws.sub(' ', node.text) ProcessManager.run_command(command, project_path, environ) @staticmethod From aa24668a88ed386459ebd415cbd671f42b6de640 Mon Sep 17 00:00:00 2001 From: fireundubh Date: Sat, 23 Sep 2023 16:30:59 -0700 Subject: [PATCH 06/15] Normalize paths when parsing absolute paths --- pyro/ProjectBase.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/pyro/ProjectBase.py b/pyro/ProjectBase.py index 1ea6f375..ec0fbdba 100644 --- a/pyro/ProjectBase.py +++ b/pyro/ProjectBase.py @@ -67,7 +67,10 @@ def parse(self, value: str) -> str: """Expands string tokens and environment variables, and returns the parsed string""" t = StringTemplate(value) try: - return os.path.expanduser(os.path.expandvars(t.substitute(self.variables))) + retval = os.path.expanduser(os.path.expandvars(t.substitute(self.variables))) + if os.path.isabs(retval): + retval = os.path.normpath(retval) + return retval except KeyError as e: ProjectBase.log.error(f'Failed to parse variable "{e.args[0]}" in "{value}". Is the variable name correct?') sys.exit(1) From bd7f135f93384e851b4b807a7c4e0c4984ae102e Mon Sep 17 00:00:00 2001 From: fireundubh Date: Sat, 23 Sep 2023 16:33:08 -0700 Subject: [PATCH 07/15] Minor enhancement to string template --- pyro/StringTemplate.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/pyro/StringTemplate.py b/pyro/StringTemplate.py index e8218712..1a13fa43 100644 --- a/pyro/StringTemplate.py +++ b/pyro/StringTemplate.py @@ -1,5 +1,9 @@ +import re as _re from string import Template class StringTemplate(Template): + # noinspection PyClassVar delimiter: str = '@' + idpattern = '([_a-z][_a-z0-9]*)' + flags = _re.IGNORECASE | _re.ASCII From a501ab33042c2506a9fc429eae0abaa54fcf2237 Mon Sep 17 00:00:00 2001 From: fireundubh Date: Sat, 23 Sep 2023 16:40:15 -0700 Subject: [PATCH 08/15] Output package contents using debug log level instead of info --- pyro/PackageManager.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pyro/PackageManager.py b/pyro/PackageManager.py index 3676e61d..c871e19f 100644 --- a/pyro/PackageManager.py +++ b/pyro/PackageManager.py @@ -281,7 +281,7 @@ def create_packages(self) -> None: adj_relpath = os.path.normpath(os.path.join(attr_path, relpath)) - PackageManager.log.info(f'+ "{adj_relpath.casefold()}"') + PackageManager.log.debug(f'+ "{adj_relpath.casefold()}"') target_path: str = os.path.join(self.options.temp_path, adj_relpath) @@ -353,7 +353,7 @@ def create_zip(self) -> None: _, attr_file_name = os.path.split(include_path) arcname = attr_file_name if attr_path == os.curdir else os.path.join(attr_path, attr_file_name) - PackageManager.log.info('+ "{}"'.format(arcname)) + PackageManager.log.debug('+ "{}"'.format(arcname)) z.write(include_path, arcname, compress_type=compress_type) self.includes += 1 From e4c1c003cc74614e942dc6adf00c4bf0e7991ba3 Mon Sep 17 00:00:00 2001 From: fireundubh Date: Sat, 23 Sep 2023 16:41:03 -0700 Subject: [PATCH 09/15] Output compiler command using debug log level --- pyro/BuildFacade.py | 1 + 1 file changed, 1 insertion(+) diff --git a/pyro/BuildFacade.py b/pyro/BuildFacade.py index 53092263..a262afc6 100644 --- a/pyro/BuildFacade.py +++ b/pyro/BuildFacade.py @@ -94,6 +94,7 @@ def try_compile(self) -> None: if self.ppj.options.no_parallel or self.compile_data.command_count == 1: for command in commands: + BuildFacade.log.debug(f'Command: {command}') if ProcessManager.run_compiler(command) == ProcessState.SUCCESS: self.compile_data.success_count += 1 elif self.compile_data.command_count > 0: From 9bc5d35523ccc927ef7d4d7b1a922774304b99a9 Mon Sep 17 00:00:00 2001 From: fireundubh Date: Sat, 23 Sep 2023 16:43:43 -0700 Subject: [PATCH 10/15] Added support for Caprica Rooted project files to containing folder Removed implicit import path discovery --- pyro/BuildFacade.py | 2 +- pyro/PapyrusProject.py | 211 ++++++++++++++--------------------------- pyro/PathHelper.py | 52 ++++------ pyro/ProcessManager.py | 65 +++++++------ 4 files changed, 121 insertions(+), 209 deletions(-) diff --git a/pyro/BuildFacade.py b/pyro/BuildFacade.py index a262afc6..6ccb872d 100644 --- a/pyro/BuildFacade.py +++ b/pyro/BuildFacade.py @@ -92,7 +92,7 @@ def try_compile(self) -> None: self.compile_data.time.start_time = time.time() - if self.ppj.options.no_parallel or self.compile_data.command_count == 1: + if self.ppj.options.no_parallel or self.compile_data.command_count == 1 or endswith(self.ppj.get_compiler_path(), 'Caprica.exe', ignorecase=True) : for command in commands: BuildFacade.log.debug(f'Command: {command}') if ProcessManager.run_compiler(command) == ProcessState.SUCCESS: diff --git a/pyro/PapyrusProject.py b/pyro/PapyrusProject.py index 314a0221..039f769a 100644 --- a/pyro/PapyrusProject.py +++ b/pyro/PapyrusProject.py @@ -223,36 +223,17 @@ def try_populate_imports(self) -> None: PapyrusProject.log.error('Failed to build list of import paths') sys.exit(1) - if not self.options.no_implicit_imports: - # ensure that folder paths are implicitly imported - implicit_folder_paths: list = self._get_implicit_folder_imports() + # remove project path, if added by user + self.import_paths = [p for p in self.import_paths if not startswith(p, self.project_path, ignorecase=True)] - if len(implicit_folder_paths) > 0: - PapyrusProject.log.info('Implicitly imported folder paths found:') - for path in implicit_folder_paths: - PapyrusProject.log.info(f'+ "{path}"') + # prepend project path + self.import_paths.insert(0, self.project_path) - PathHelper.merge_implicit_import_paths(implicit_folder_paths, self.import_paths) - - # we need to populate psc paths after explicit and implicit import paths are populated - # this also needs to be set before we populate implicit import paths from psc paths - # not sure if this must run again after populating implicit import paths from psc paths self.psc_paths = self._get_psc_paths() if not self.psc_paths: PapyrusProject.log.error('Failed to build list of script paths') sys.exit(1) - if not self.options.no_implicit_imports: - # this adds implicit imports from script paths - implicit_script_paths: list = self._get_implicit_script_imports() - - if len(implicit_script_paths) > 0: - PapyrusProject.log.info('Implicitly imported script paths found:') - for path in implicit_script_paths: - PapyrusProject.log.info(f'+ "{path}"') - - PathHelper.merge_implicit_import_paths(implicit_script_paths, self.import_paths) - def try_set_game_type(self) -> None: # we need to set the game type after imports are populated but before pex paths are populated # allow xml to set game type but defer to passed argument @@ -415,22 +396,14 @@ def _update_attributes(self, parent_node: etree.ElementBase) -> None: def _calculate_object_name(self, psc_path: str) -> str: return PathHelper.calculate_relative_object_name(psc_path, self.import_paths) - @staticmethod - def _can_remove_folder(import_path: str, object_name: str, script_path: str) -> bool: - import_path = import_path.casefold() - object_name = object_name.casefold() - script_path = script_path.casefold() - return startswith(script_path, import_path) and os.path.join(import_path, object_name) != script_path - def _find_missing_script_paths(self) -> dict: """Returns list of script paths for compiled scripts that do not exist""" results: dict = {} for object_name, script_path in self.psc_paths.items(): - pex_path: str = os.path.join(self.options.output_path, object_name.replace('.psc', '.pex')) + pex_path: str = os.path.join(self.get_output_path(), object_name.replace('.psc', '.pex')) if not os.path.isfile(pex_path) and script_path not in results: - object_name = script_path if not os.path.isabs(script_path) else self._calculate_object_name(script_path) results[object_name] = script_path return results @@ -470,44 +443,6 @@ def _get_import_paths(self) -> list: return PathHelper.uniqify(results) - def _get_implicit_folder_imports(self) -> list: - """Returns absolute implicit import paths from Folder node paths""" - implicit_paths: list = [] - - if self.folders_node is None: - return [] - - def try_append_path(path: str) -> None: - if os.path.isdir(path) and path not in self.import_paths: - implicit_paths.append(path) - - for folder_node in filter(is_folder_node, self.folders_node): - folder_path: str = os.path.normpath(folder_node.text) - try_append_path(folder_path if os.path.isabs(folder_path) else os.path.join(self.project_path, folder_path)) - - return PathHelper.uniqify(implicit_paths) - - def _get_implicit_script_imports(self) -> list: - """Returns absolute implicit import paths from Script node paths""" - implicit_paths: list = [] - - for object_name, script_path in self.psc_paths.items(): - script_folder_path = os.path.dirname(script_path) - - for import_path in self.import_paths: - # TODO: figure out how to handle imports on different drives - try: - relpath = os.path.relpath(script_folder_path, import_path) - except ValueError as e: - PapyrusProject.log.warning(f'{e} (path: "{script_folder_path}", start: "{import_path}")') - continue - - test_path = os.path.normpath(os.path.join(import_path, relpath)) - if os.path.isdir(test_path) and test_path not in self.import_paths: - implicit_paths.append(test_path) - - return PathHelper.uniqify(implicit_paths) - def _get_pex_paths(self) -> list: """ Returns absolute paths to compiled scripts that may not exist yet in output folder @@ -523,32 +458,30 @@ def _get_pex_paths(self) -> list: return pex_paths + def get_object_item(self, path: str) -> tuple: + object_name = path if not os.path.isabs(path) else self._calculate_object_name(path) + object_path = path if endswith(path, '.psc', ignorecase=True) else f'{path}.psc' + return object_name, object_path + def _get_psc_paths(self) -> dict: """Returns script paths from Folders and Scripts nodes""" object_names: dict = {} - def add_object_name(p: str) -> None: - object_names[p if not os.path.isabs(p) else self._calculate_object_name(p)] = p - - # try to populate paths with scripts from Folders and Scripts nodes + # populate object names dictionary if self.folders_node is not None: for path in self._get_script_paths_from_folders_node(): - add_object_name(path) + k, v = self.get_object_item(path) + object_names[k] = v if self.scripts_node is not None: for path in self._get_script_paths_from_scripts_node(): - add_object_name(path) + k, v = self.get_object_item(path) + object_names[k] = v # convert user paths to absolute paths - for object_name, script_path in object_names.items(): + for k, v in object_names.items(): # ignore existing absolute paths - if os.path.isabs(script_path) and os.path.isfile(script_path): - continue - - # try to add existing project-relative paths - test_path = os.path.join(self.project_path, script_path) - if os.path.isfile(test_path): - object_names[object_name] = test_path + if os.path.isabs(v) and os.path.isfile(v): continue # try to add existing import-relative paths @@ -556,9 +489,24 @@ def add_object_name(p: str) -> None: if not os.path.isabs(import_path): import_path = os.path.join(self.project_path, import_path) - test_path = os.path.join(import_path, script_path) + # test for shallow matches + test_path = os.path.join(import_path, v) if os.path.isfile(test_path): - object_names[object_name] = test_path + object_names[k] = test_path + break + + # go deep + matcher = wcmatch.WcMatch(import_path, '*.psc', flags=wcmatch.IGNORECASE | wcmatch.RECURSIVE) + + flag = False + + for f in matcher.imatch(): + if endswith(f, os.path.basename(v), ignorecase=True): + object_names[k] = f + flag = True + break + + if flag: break PapyrusProject.log.info(f'{len(object_names)} unique script paths resolved to absolute paths.') @@ -643,25 +591,6 @@ def _get_script_paths_from_folders_node(self) -> typing.Generator: no_recurse=attr_no_recurse) continue - # try to add project-relative folder path - test_path = os.path.join(self.project_path, folder_path) - if os.path.isdir(test_path): - # count scripts to avoid issue where an errant `test_path` may exist and contain no sources - # this can be a problem if that folder contains sources but user error is hard to fix - test_passed = False - - user_flags = wcmatch.RECURSIVE if not attr_no_recurse else 0x0 - matcher = wcmatch.WcMatch(test_path, '*.psc', flags=wcmatch.IGNORECASE | user_flags) - for _ in matcher.imatch(): - test_passed = True - break - - if test_passed: - yield from PathHelper.find_script_paths_from_folder(test_path, - no_recurse=attr_no_recurse, - matcher=matcher) - continue - # try to add import-relative folder path for import_path in self.import_paths: test_path = os.path.join(import_path, folder_path) @@ -732,10 +661,6 @@ def build_commands(self) -> list: arguments = CommandArguments() - compiler_path: str = self.options.compiler_path - flags_path: str = self.options.flags_path - output_path: str = self.options.output_path - if self.options.no_incremental_build: psc_paths: dict = self.psc_paths else: @@ -746,44 +671,46 @@ def build_commands(self) -> list: if object_name not in psc_paths.keys(): psc_paths[object_name] = script_path - source_import_paths = deepcopy(self.import_paths) + if endswith(self.get_compiler_path(), 'Caprica.exe', ignorecase=True): + arguments.append(self.get_compiler_path(), enquote_value=True) - # TODO: depth sorting solution is not foolproof! parse psc files for imports to determine command order - for object_name, script_path in psc_paths.items(): - import_paths: list = self.import_paths + arguments.append(os.path.join(self.program_path, 'tools', 'caprica.cfg'), key='-config-file', enquote_value=True) - if self.options.game_type != GameType.FO4 and self.options.game_type != GameType.SF1: - object_name = script_path + if self.options.game_type == GameType.SF1: + arguments.append('starfield', key='g', enquote_value=True) + elif self.options.game_type == GameType.FO4: + arguments.append('fallout4', key='g', enquote_value=True) + elif self.options.game_type in [GameType.TES5, GameType.SSE]: + arguments.append('skyrim', key='g', enquote_value=True) - # remove unnecessary import paths for script - if self.options.game_type == GameType.FO4 or self.options.game_type == GameType.SF1: - for import_path in reversed(self.import_paths): - if self._can_remove_folder(import_path, object_name, script_path): - import_paths.remove(import_path) + arguments.append(self.get_flags_path(), key='f', enquote_value=True) + arguments.append(';'.join(self.import_paths), key='i', enquote_value=True) + arguments.append(self.get_output_path(), key='o', enquote_value=True) - arguments.clear() - arguments.append(compiler_path, enquote_value=True) - arguments.append(object_name, enquote_value=True) - arguments.append(flags_path, key='f', enquote_value=True) - arguments.append(';'.join(import_paths), key='i', enquote_value=True) - arguments.append(output_path, key='o', enquote_value=True) + object_names = ';'.join(psc_paths.keys()) + arguments.append(object_names, enquote_value=True) - if self.options.game_type == GameType.FO4 or self.options.game_type == GameType.SF1: - # noinspection PyUnboundLocalVariable - if self.release: - arguments.append('-release') - - # noinspection PyUnboundLocalVariable - if self.final: - arguments.append('-final') - - if self.optimize: - arguments.append('-op') - - arg_s = arguments.join() - commands.append(arg_s) - - self.import_paths = source_import_paths + else: + for object_name, script_path in psc_paths.items(): + arguments.clear() + arguments.append(self.get_compiler_path(), enquote_value=True) + arguments.append(object_name if self.options.game_type == GameType.FO4 else script_path, enquote_value=True) + arguments.append(self.get_flags_path(), key='f', enquote_value=True) + arguments.append(';'.join(self.import_paths), key='i', enquote_value=True) + arguments.append(self.get_output_path(), key='o', enquote_value=True) + + if self.options.game_type in [GameType.FO4, GameType.SF1]: + if self.release: + arguments.append('-release') + + if self.final: + arguments.append('-final') + + if self.optimize: + arguments.append('-op') + + arg_s = arguments.join() + commands.append(arg_s) return commands diff --git a/pyro/PathHelper.py b/pyro/PathHelper.py index 0d093005..7584799d 100644 --- a/pyro/PathHelper.py +++ b/pyro/PathHelper.py @@ -11,9 +11,27 @@ class PathHelper: + @staticmethod + def calculate_absolute_script_path(object_name: str, import_paths: list) -> str: + for import_path in reversed(PathHelper.uniqify(import_paths)): + if not os.path.isabs(import_path): + import_path = os.path.join(os.getcwd(), import_path) + + import_path = os.path.normpath(import_path) + + file_path = os.path.join(import_path, object_name) + + if not endswith(file_path, '.psc', ignorecase=True): + file_path += '.psc' + + if os.path.isfile(file_path): + return file_path + + return '' + @staticmethod def calculate_relative_object_name(script_path: str, import_paths: list) -> str: - """Returns import-relative path from absolute path (should be used only for Fallout 4 paths)""" + """Returns import-relative path from absolute path""" # reverse the list to find the best import path file_name = os.path.basename(script_path) @@ -45,38 +63,6 @@ def uniqify(items: Iterable) -> list: """Returns ordered list without duplicates""" return list(dict.fromkeys(items)) - @staticmethod - def find_index_of_ancestor_import_path(implicit_path: str, import_paths: list) -> int: - """Returns index of ancestor of implicit path in import paths""" - for i, import_path in enumerate(import_paths): - if import_path.casefold() in implicit_path.casefold(): - return i - return -1 - - @staticmethod - def merge_implicit_import_paths(implicit_paths: list, import_paths: list) -> None: - """Inserts orphan and descendant implicit paths into list of import paths at correct positions""" - if not implicit_paths: - return - - implicit_paths.sort() - - for implicit_path in reversed(PathHelper.uniqify(implicit_paths)): - implicit_path = os.path.normpath(implicit_path) - - # do not add import paths that are already declared - if any(endswith(x, implicit_path, ignorecase=True) for x in import_paths): - continue - - # insert implicit path before ancestor import path, if ancestor exists - i = PathHelper.find_index_of_ancestor_import_path(implicit_path, import_paths) - if i > -1: - import_paths.insert(i, implicit_path) - continue - - # insert orphan implicit path at the first position - import_paths.insert(0, implicit_path) - @staticmethod def url2pathname(url_path: str) -> str: """Returns normalized unquoted path from URL""" diff --git a/pyro/ProcessManager.py b/pyro/ProcessManager.py index 20ed3622..6a2a29fe 100644 --- a/pyro/ProcessManager.py +++ b/pyro/ProcessManager.py @@ -43,7 +43,7 @@ def run_event(event_node: etree.ElementBase, project_path: str) -> None: for node in filter(is_command_node, event_node): command = ws.sub(' ', node.text) - ProcessManager.run_command(command, project_path, environ) + ProcessManager.run_command(command, project_path, environ) @staticmethod def run_command(command: str, cwd: str, env: dict) -> ProcessState: @@ -61,8 +61,7 @@ def run_command(command: str, cwd: str, env: dict) -> ProcessState: try: while process.poll() is None: - line: str = process.stdout.readline().strip() - if line: + if (line := process.stdout.readline().strip()) != '': ProcessManager.log.info(line) except KeyboardInterrupt: @@ -112,22 +111,20 @@ def run_bsarch(command: str) -> ProcessState: try: while process.poll() is None: - line = process.stdout.readline().strip() + if (line := process.stdout.readline().strip()) != '': + if startswith(line, exclusions): + continue - if startswith(line, exclusions): - continue + if startswith(line, 'Packing'): + package_path = line.split(':', 1)[1].strip() + ProcessManager.log.info(f'Packaging folder "{package_path}"...') + continue - if startswith(line, 'Packing'): - package_path = line.split(':', 1)[1].strip() - ProcessManager.log.info(f'Packaging folder "{package_path}"...') - continue + if startswith(line, 'Archive Name'): + archive_path = line.split(':', 1)[1].strip() + ProcessManager.log.info(f'Building "{archive_path}"...') + continue - if startswith(line, 'Archive Name'): - archive_path = line.split(':', 1)[1].strip() - ProcessManager.log.info(f'Building "{archive_path}"...') - continue - - if line: ProcessManager.log.info(line) except KeyboardInterrupt: @@ -179,23 +176,25 @@ def run_compiler(command: str) -> ProcessState: try: while process.poll() is None: - line = process.stdout.readline().strip() - - if not line or startswith(line, exclusions): - continue - - match = line_error.search(line) - - if match is not None: - path, location, message = match.groups() - head, tail = os.path.split(path) - ProcessManager.log.error(f'COMPILATION FAILED: ' - f'{os.path.basename(head)}\\{tail}{location}: {message}') - process.terminate() - error_count += 1 - - elif 'error(s)' not in line: - ProcessManager.log.info(line) + if (line := process.stdout.readline().strip()) != '': + if startswith(line, exclusions): + continue + + if (match := line_error.search(line)) is not None: + path, location, message = match.groups() + head, tail = os.path.split(path) + ProcessManager.log.error(f'COMPILATION FAILED: ' + f'{os.path.basename(head)}\\{tail}{location}: {message}') + process.terminate() + error_count += 1 + + elif startswith(line, 'Fatal Error', ignorecase=True): + ProcessManager.log.error(line) + process.terminate() + error_count += 1 + + elif 'error(s)' not in line: + ProcessManager.log.info(line) except KeyboardInterrupt: try: From cb8a0935354af68780110bf73da9134cbb829028 Mon Sep 17 00:00:00 2001 From: fireundubh Date: Sat, 23 Sep 2023 18:43:53 -0700 Subject: [PATCH 11/15] deprecate --no-implicit-imports argument --- pyro/__main__.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/pyro/__main__.py b/pyro/__main__.py index f82a2b46..b9636504 100644 --- a/pyro/__main__.py +++ b/pyro/__main__.py @@ -31,9 +31,10 @@ _build_arguments.add_argument('--ignore-errors', action='store_true', default=False, help='ignore compiler errors during build') - _build_arguments.add_argument('--no-implicit-imports', + # deprecated argument (functionality no longer exists, retained arg to avoid breaking change) + _build_arguments.add_argument('--no-implicit-imports', dest='no_implicit_imports_deprecated', action='store_true', default=False, - help='do not build with implicit imports') + help=SUPPRESS) _build_arguments.add_argument('--no-incremental-build', action='store_true', default=False, help='do not build incrementally') From ede6dc9d5ed5df70898b4db4b50d1f03ca71bb1e Mon Sep 17 00:00:00 2001 From: fireundubh Date: Sat, 23 Sep 2023 21:18:41 -0700 Subject: [PATCH 12/15] Implemented Caprica.cfg generation when passing long commands to avoid OS limit Added --compiler-config-path argument to change Caprica.cfg template --- pyro/PapyrusProject.py | 42 ++++++++++++++++++++++++++++++++++-------- pyro/ProcessManager.py | 2 +- pyro/ProjectBase.py | 6 ++++++ pyro/__main__.py | 4 ++++ 4 files changed, 45 insertions(+), 9 deletions(-) diff --git a/pyro/PapyrusProject.py b/pyro/PapyrusProject.py index 039f769a..6d406894 100644 --- a/pyro/PapyrusProject.py +++ b/pyro/PapyrusProject.py @@ -674,21 +674,47 @@ def build_commands(self) -> list: if endswith(self.get_compiler_path(), 'Caprica.exe', ignorecase=True): arguments.append(self.get_compiler_path(), enquote_value=True) - arguments.append(os.path.join(self.program_path, 'tools', 'caprica.cfg'), key='-config-file', enquote_value=True) + object_names = ';'.join(psc_paths.keys()) + + with open(self.get_compiler_config_path(), encoding='utf-8') as f: + options = f.read().splitlines() + + # disable parallel compilation if the user overrides the default + if self.options.no_parallel and 'parallel-compile=1' in options: + for i, option in enumerate(options): + if startswith(option, 'parallel-compile', ignorecase=True): + options.pop(i) + break + + use_config_file_for_input_paths = False + + if len(object_names) > 32486: # 32766 total - 280 chars for all arguments + use_config_file_for_input_paths = True + options.append(f'input-file={object_names.strip()}\n') - if self.options.game_type == GameType.SF1: - arguments.append('starfield', key='g', enquote_value=True) - elif self.options.game_type == GameType.FO4: - arguments.append('fallout4', key='g', enquote_value=True) + config_dir_path = os.path.dirname(self.get_compiler_config_path()) + config_file_path = os.path.join(config_dir_path, f'caprica_{str(int(time.time()))}.cfg') + + with open(config_file_path, mode='w', encoding='utf-8') as f: + f.write('\n'.join(options)) + + arguments.append(config_file_path, key='-config-file', enquote_value=True) + + # caprica defaults to starfield + game_name = 'starfield' + if self.options.game_type == GameType.FO4: + game_name = 'fallout4' elif self.options.game_type in [GameType.TES5, GameType.SSE]: - arguments.append('skyrim', key='g', enquote_value=True) + game_name = 'skyrim' + + arguments.append(game_name, key='g', enquote_value=True) arguments.append(self.get_flags_path(), key='f', enquote_value=True) arguments.append(';'.join(self.import_paths), key='i', enquote_value=True) arguments.append(self.get_output_path(), key='o', enquote_value=True) - object_names = ';'.join(psc_paths.keys()) - arguments.append(object_names, enquote_value=True) + if not use_config_file_for_input_paths: + arguments.append(object_names, enquote_value=True) else: for object_name, script_path in psc_paths.items(): diff --git a/pyro/ProcessManager.py b/pyro/ProcessManager.py index 6a2a29fe..dfc65db3 100644 --- a/pyro/ProcessManager.py +++ b/pyro/ProcessManager.py @@ -146,7 +146,7 @@ def run_compiler(command: str) -> ProcessState: """ command_size = len(command) - if command_size > 32768: + if command_size > 32766: ProcessManager.log.error(f'Cannot create process because command exceeds max length: {command_size}') return ProcessState.FAILURE diff --git a/pyro/ProjectBase.py b/pyro/ProjectBase.py index ec0fbdba..e104d135 100644 --- a/pyro/ProjectBase.py +++ b/pyro/ProjectBase.py @@ -104,6 +104,12 @@ def get_compiler_path(self) -> str: relative_root_path=os.getcwd(), fallback_path=[self.options.game_path, 'Papyrus Compiler', 'PapyrusCompiler.exe']) + def get_compiler_config_path(self) -> str: + """Returns absolute compiler config file path from arguments""" + return self._get_path(self.options.compiler_config_path, + relative_root_path=os.getcwd(), + fallback_path=[self.program_path, 'tools', 'caprica.cfg']) + def get_flags_path(self) -> str: """ Returns absolute flags path or flags file name from arguments or game path diff --git a/pyro/__main__.py b/pyro/__main__.py index b9636504..ce37ca50 100644 --- a/pyro/__main__.py +++ b/pyro/__main__.py @@ -51,6 +51,10 @@ action='store', type=str, help='relative or absolute path to PapyrusCompiler.exe\n' '(if relative, must be relative to current working directory)') + _compiler_arguments.add_argument('--compiler-config-path', + action='store', type=str, + help='relative or absolute path to compiler config file\n' + '(if relative, must be relative to current working directory)') _compiler_arguments.add_argument('--flags-path', action='store', type=str, help='relative or absolute path to Papyrus Flags file\n' From 802daa9c5dd50691a4c954b1534974a480477b4e Mon Sep 17 00:00:00 2001 From: fireundubh Date: Sun, 24 Sep 2023 08:46:32 -0700 Subject: [PATCH 13/15] Fixed issue where failure not reported on error during Caprica run --- pyro/ProcessManager.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyro/ProcessManager.py b/pyro/ProcessManager.py index dfc65db3..69702e04 100644 --- a/pyro/ProcessManager.py +++ b/pyro/ProcessManager.py @@ -188,7 +188,7 @@ def run_compiler(command: str) -> ProcessState: process.terminate() error_count += 1 - elif startswith(line, 'Fatal Error', ignorecase=True): + elif startswith(line, ('Error', 'Fatal Error'), ignorecase=True): ProcessManager.log.error(line) process.terminate() error_count += 1 From 4b1edb419a607cd925b2f694b1091c4a19f945a2 Mon Sep 17 00:00:00 2001 From: fireundubh Date: Sun, 24 Sep 2023 10:01:24 -0700 Subject: [PATCH 14/15] Fixed issue where incremental build was no longer working Implemented Caprica session performance stats --- pyro/Application.py | 24 +++++++++++----------- pyro/BuildFacade.py | 35 +++++++++++++++++++++++---------- pyro/PapyrusProject.py | 26 ++++++++++++++++++------ pyro/Performance/CompileData.py | 22 +++++++++++++++++++++ pyro/TimeElapsed.py | 8 ++++---- 5 files changed, 83 insertions(+), 32 deletions(-) diff --git a/pyro/Application.py b/pyro/Application.py index c90d8380..c51a8b83 100644 --- a/pyro/Application.py +++ b/pyro/Application.py @@ -165,7 +165,7 @@ def run(self) -> int: ppj.try_run_event(CompileEvent.POST) if ppj.options.anonymize: - if build.compile_data.failed_count == 0 or ppj.options.ignore_errors: + if build.get_compile_data().failed_count == 0 or ppj.options.ignore_errors: if ppj.use_pre_anonymize_event: ppj.try_run_event(AnonymizeEvent.PRE) @@ -174,13 +174,13 @@ def run(self) -> int: if ppj.use_post_anonymize_event: ppj.try_run_event(AnonymizeEvent.POST) else: - Application.log.error(f'Cannot anonymize scripts because {build.compile_data.failed_count} scripts failed to compile') - sys.exit(build.compile_data.failed_count) + Application.log.error(f'Cannot anonymize scripts because {build.get_compile_data().failed_count} scripts failed to compile') + sys.exit(build.get_compile_data().failed_count) else: Application.log.info('Cannot anonymize scripts because Anonymize is disabled in project') if ppj.options.package: - if build.compile_data.failed_count == 0 or ppj.options.ignore_errors: + if build.get_compile_data().failed_count == 0 or ppj.options.ignore_errors: if ppj.use_pre_package_event: ppj.try_run_event(PackageEvent.PRE) @@ -189,13 +189,13 @@ def run(self) -> int: if ppj.use_post_package_event: ppj.try_run_event(PackageEvent.POST) else: - Application.log.error(f'Cannot create Packages because {build.compile_data.failed_count} scripts failed to compile') - sys.exit(build.compile_data.failed_count) + Application.log.error(f'Cannot create Packages because {build.get_compile_data().failed_count} scripts failed to compile') + sys.exit(build.get_compile_data().failed_count) elif ppj.packages_node is not None: Application.log.info('Cannot create Packages because Package is disabled in project') if ppj.options.zip: - if build.compile_data.failed_count == 0 or ppj.options.ignore_errors: + if build.get_compile_data().failed_count == 0 or ppj.options.ignore_errors: if ppj.use_pre_zip_event: ppj.try_run_event(ZipEvent.PRE) @@ -204,13 +204,13 @@ def run(self) -> int: if ppj.use_post_zip_event: ppj.try_run_event(ZipEvent.POST) else: - Application.log.error(f'Cannot create ZipFile because {build.compile_data.failed_count} scripts failed to compile') - sys.exit(build.compile_data.failed_count) + Application.log.error(f'Cannot create ZipFile because {build.get_compile_data().failed_count} scripts failed to compile') + sys.exit(build.get_compile_data().failed_count) elif ppj.zip_files_node is not None: Application.log.info('Cannot create ZipFile because Zip is disabled in project') if build.scripts_count > 0: - Application.log.info(build.compile_data.to_string() if build.compile_data.success_count > 0 else 'No scripts were compiled.') + Application.log.info(build.get_compile_data().to_string() if build.get_compile_data().success_count > 0 else 'No scripts were compiled.') if ppj.packages_node is not None: Application.log.info(build.package_data.to_string() if build.package_data.file_count > 0 else 'No files were packaged.') @@ -220,7 +220,7 @@ def run(self) -> int: Application.log.info('DONE!') - if ppj.use_post_build_event and build.compile_data.failed_count == 0: + if ppj.use_post_build_event and build.get_compile_data().failed_count == 0: ppj.try_run_event(BuildEvent.POST) - return build.compile_data.failed_count + return build.get_compile_data().failed_count diff --git a/pyro/BuildFacade.py b/pyro/BuildFacade.py index 6ccb872d..e7964d97 100644 --- a/pyro/BuildFacade.py +++ b/pyro/BuildFacade.py @@ -3,6 +3,7 @@ import os import sys import time +from typing import Union from copy import deepcopy import psutil @@ -11,7 +12,8 @@ from pyro.PackageManager import PackageManager from pyro.PapyrusProject import PapyrusProject from pyro.PathHelper import PathHelper -from pyro.Performance.CompileData import CompileData +from pyro.Performance.CompileData import (CompileData, + CompileDataCaprica) from pyro.Performance.PackageData import PackageData from pyro.Performance.ZippingData import ZippingData from pyro.PexReader import PexReader @@ -28,6 +30,7 @@ class BuildFacade: ppj: PapyrusProject = None compile_data: CompileData = CompileData() + compile_data_caprica: CompileData = CompileDataCaprica() package_data: PackageData = PackageData() zipping_data: ZippingData = ZippingData() @@ -84,31 +87,43 @@ def _limit_priority() -> None: process = psutil.Process(os.getpid()) process.nice(psutil.BELOW_NORMAL_PRIORITY_CLASS if sys.platform == 'win32' else 19) + def get_compile_data(self) -> Union[CompileData, CompileDataCaprica]: + using_caprica = endswith(self.ppj.get_compiler_path(), 'Caprica.exe', ignorecase=True) + return self.compile_data_caprica if using_caprica else self.compile_data + def try_compile(self) -> None: """Builds and passes commands to Papyrus Compiler""" - commands: list = [c for c in self.ppj.build_commands() if c] + using_caprica = endswith(self.ppj.get_compiler_path(), 'Caprica.exe', ignorecase=True) + + compile_data = self.get_compile_data() - self.compile_data.command_count = len(commands) + compile_data.command_count, commands = self.ppj.build_commands() - self.compile_data.time.start_time = time.time() + compile_data.time.start_time = time.time() - if self.ppj.options.no_parallel or self.compile_data.command_count == 1 or endswith(self.ppj.get_compiler_path(), 'Caprica.exe', ignorecase=True) : + if using_caprica or self.ppj.options.no_parallel or compile_data.command_count == 1: for command in commands: BuildFacade.log.debug(f'Command: {command}') if ProcessManager.run_compiler(command) == ProcessState.SUCCESS: - self.compile_data.success_count += 1 - elif self.compile_data.command_count > 0: + compile_data.success_count += 1 + + elif compile_data.command_count > 0: multiprocessing.freeze_support() - worker_limit = min(self.compile_data.command_count, self.ppj.options.worker_limit) + worker_limit = min(compile_data.command_count, self.ppj.options.worker_limit) with multiprocessing.Pool(processes=worker_limit, initializer=BuildFacade._limit_priority) as pool: for state in pool.imap(ProcessManager.run_compiler, commands): if state == ProcessState.SUCCESS: - self.compile_data.success_count += 1 + compile_data.success_count += 1 pool.close() pool.join() - self.compile_data.time.end_time = time.time() + compile_data.time.end_time = time.time() + + # caprica success = all files compiled + if using_caprica and compile_data.success_count > 0: + compile_data.scripts_count = compile_data.command_count + compile_data.success_count = compile_data.success_count def try_anonymize(self) -> None: """Obfuscates identifying metadata in compiled scripts""" diff --git a/pyro/PapyrusProject.py b/pyro/PapyrusProject.py index 6d406894..4d375309 100644 --- a/pyro/PapyrusProject.py +++ b/pyro/PapyrusProject.py @@ -401,7 +401,12 @@ def _find_missing_script_paths(self) -> dict: results: dict = {} for object_name, script_path in self.psc_paths.items(): - pex_path: str = os.path.join(self.get_output_path(), object_name.replace('.psc', '.pex')) + if endswith(object_name, '.pex', ignorecase=True): + pex_path = os.path.join(self.get_output_path(), object_name) + elif endswith(object_name, '.psc', ignorecase=True): + pex_path = os.path.join(self.get_output_path(), object_name.replace('.psc', '.pex')) + else: + pex_path = os.path.join(self.get_output_path(), object_name + '.pex') if not os.path.isfile(pex_path) and script_path not in results: results[object_name] = script_path @@ -450,7 +455,7 @@ def _get_pex_paths(self) -> list: pex_paths: list = [] for object_name, script_path in self.psc_paths.items(): - pex_path = os.path.join(self.options.output_path, object_name.replace('.psc', '.pex')) + pex_path = os.path.join(self.options.output_path, os.path.basename(script_path).replace('.psc', '.pex')) # do not check if file exists, we do that in _find_missing_script_paths for a different reason if pex_path not in pex_paths: @@ -626,12 +631,17 @@ def _try_exclude_unmodified_scripts(self) -> dict: psc_paths: dict = {} for object_name, script_path in self.psc_paths.items(): - script_name, _ = os.path.splitext(os.path.basename(script_path)) + if endswith(object_name, '.pex', ignorecase=True): + script_name = object_name + elif endswith(object_name, '.psc', ignorecase=True): + script_name = object_name.replace('.psc', '.pex') + else: + script_name = object_name + '.pex' # if pex exists, compare time_t in pex header with psc's last modified timestamp matching_path: str = '' for pex_path in self.pex_paths: - if endswith(pex_path, f'{script_name}.pex', ignorecase=True): + if endswith(pex_path, script_name, ignorecase=True): matching_path = pex_path break @@ -653,7 +663,7 @@ def _try_exclude_unmodified_scripts(self) -> dict: return psc_paths - def build_commands(self) -> list: + def build_commands(self) -> tuple[int, list]: """ Builds list of commands for compiling scripts """ @@ -671,6 +681,10 @@ def build_commands(self) -> list: if object_name not in psc_paths.keys(): psc_paths[object_name] = script_path + # do not try to compile nothing + if psc_paths is None or psc_paths == {}: + return 0, [] + if endswith(self.get_compiler_path(), 'Caprica.exe', ignorecase=True): arguments.append(self.get_compiler_path(), enquote_value=True) @@ -738,7 +752,7 @@ def build_commands(self) -> list: arg_s = arguments.join() commands.append(arg_s) - return commands + return len(psc_paths.keys()), commands def try_run_event(self, event: Event) -> None: if event == ImportEvent.PRE: diff --git a/pyro/Performance/CompileData.py b/pyro/Performance/CompileData.py index 57de8fb4..07fae394 100644 --- a/pyro/Performance/CompileData.py +++ b/pyro/Performance/CompileData.py @@ -27,3 +27,25 @@ def to_string(self) -> str: f'{self.success_count} succeeded, ' \ f'{self.failed_count} failed ' \ f'({self.scripts_count} scripts)' + +@dataclass +class CompileDataCaprica: + time: TimeElapsed = field(init=False, default_factory=TimeElapsed) + scripts_count: int = field(init=False, default_factory=int) + success_count: int = field(init=False, default_factory=int) + command_count: int = field(init=False, default_factory=int) + + def __post_init__(self) -> None: + self.time = TimeElapsed() + + @property + def failed_count(self) -> int: + return 1 if self.success_count == 0 else 0 + + def to_string(self) -> str: + raw_time = '{0:.3f}s'.format(self.time.value()) + avg_time = '{0:.4f}s'.format(self.time.average(self.scripts_count)) + + return f'Compile time: ' \ + f'{raw_time} ({avg_time}/script) - ' \ + f'({self.scripts_count} scripts)' diff --git a/pyro/TimeElapsed.py b/pyro/TimeElapsed.py index cb9bc3e0..9d71a4a6 100644 --- a/pyro/TimeElapsed.py +++ b/pyro/TimeElapsed.py @@ -10,13 +10,13 @@ def __init__(self) -> None: self.start_time = 0.0 self.end_time = 0.0 - def average(self, dividend: int) -> Decimal: + def average(self, dividend: int) -> int: if dividend == 0: - return round(Decimal(0), 3) + return round(Decimal(0), 8) value = self.value() if value.compare(0) == 0: - return round(Decimal(0), 3) - return round(value / Decimal(dividend, self._context), 3) + return round(Decimal(0), 8) + return round(value / Decimal(dividend, self._context), 8) def value(self) -> Decimal: return Decimal(self.end_time) - Decimal(self.start_time) From 39e961704c04ca150d4b0b6b9f6c1733d3333002 Mon Sep 17 00:00:00 2001 From: fireundubh Date: Sun, 24 Sep 2023 13:05:55 -0700 Subject: [PATCH 15/15] Fixed issue where project path was not always the current working directory --- pyro/ProjectBase.py | 1 + 1 file changed, 1 insertion(+) diff --git a/pyro/ProjectBase.py b/pyro/ProjectBase.py index e104d135..fb8396c9 100644 --- a/pyro/ProjectBase.py +++ b/pyro/ProjectBase.py @@ -38,6 +38,7 @@ def __init__(self, options: ProjectOptions) -> None: self.project_name = os.path.splitext(os.path.basename(self.options.input_path))[0] self.project_path = os.path.dirname(self.options.input_path) + os.chdir(self.project_path) def __setattr__(self, key: str, value: object) -> None: if isinstance(value, str) and endswith(key, 'path'):