<commit_before>#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""

NieR:AutoModSave v0.1 by jimmyazrael
This script will guide and help you to import Nier:Automata's game saves shared by others.

Requirements:

1. Preferably you should have received the whole save folder,
   or at least you should have the following files:
   GameData.dat, one or more than one of the SlotData files
   and probably SystemData.dat. Although the use of SystemData.dat
   is still unknown.
2. Please make sure you back up your own save folder, as using other's
   save file will make yours unreadable. If you would like to use your save files
   again, simply treat your own backup save folder as the one shared by someone else
   and repeat the very same steps stated below.

Steps:

1. Back up your WHOLE save folder, which is likely located at `Documents/My Games/NieR_Automata`.
2. Remove everything except `Graphic.ini` in that folder.
3. Put the files (except `Graphic.ini`) you received from another player in the folder.

If you prefer exe:
    4. Put `NierAutoModSave.exe` in the same folder, run it, follow it, done.

If you prefer a Python script and you have Python installed:
    4. Put `NierAutoModSave.py` in the same folder and run it, follow it, done.
"""

import os
import sys
import glob
import time


class Main():
    """
    The main class.
    """

    def __init__(self):
        """
        The initialization method of Main() class.
        """

        # self.messages format: {<language>: {<message_id>: <message>},}

        # You can add a new language by adding a new item to the `self.messages` variable.
        self.messages = {
            "English": {
                "gd_not_found": """\
GameData.dat not found in this directory, please find and put it here.
Press ENTER to continue when the file is ready.""",
                "gd_found": "GameData.dat found in default folder:\n{0}",
                "gen_msg": """\
A new GameData.dat is currently needed to continue the process.
It can be generated by the game.
Please start the game. Do not close this window.""",
                "modsv": "Modifying {0}...",
                "modgd": "Modifying `GameData.dat`...",
                "end": "\nFinished. Glory to mankind!\nPress enter to exit..."
            },
            u"Chinese (中文)": {
                "gd_not_found": u"本目录下没有GameData.dat文件，请将其放入。\n放入后按回车继续。",
                "gd_found": "GameData.dat 在默认文件夹中找到:\n{0}",
                "gen_msg": u"""\
现在需要一个新的GameData.dat文件。
该文件应该由游戏自动生成。
请启动游戏。不要关闭此窗口。""",
                "modsv": u"修改 {0}...",
                "modgd": u"修改 GameData.dat...",
                "end": u"\n任务完成。荣耀归于人类！"
            },
            u"Tagalog": {
                "gd_not_found": "Hindi makita ang GameData.dat sa folder na ito. Pakihanap at pakilagay ang mga files dito at i-press ang ENTER.",
                "gd_found": "Nakita ang GameData.dat sa default folder:\n{0}",
                "gen_msg": """\
Kasalukuyang kailangan ang isang bagong GameData.dat upang magpatuloy sa proseso.
Ito ay awtomatikong gagawin ng laro.
Mangyaring buksan ang laro. Huwag isarado ang window na ito.""",
                "modsv": "Minomodify ang {0}...",
                "modgd": "Minomodify ang GameData.dat...",
                "end": "Tapos na. Glory to mankind! Pindutin ang enter para matapos na ang proseso."
            }
        }

        self.language = "English"  # Set default language to English.
        self.default_savefile_path = os.path.join(os.path.expanduser("~"), "Documents", "My Games", "NieR_Automata")

    def languageSelect(self):
        """
        Select a language from self.messages.

        :returns void:
        """

        print("Please select preferred language:\n")
        available_languages = list(self.messages.keys())
        i = 1
        # Print available keys (languages) of self.messages.
        for language in available_languages:
            print("[{0}] {1}".format(i, language))
            i += 1

        print()
        while True:
            try:
                # Get user's choice.
                user_choice = int(input("Language: ")) - 1  # Because Python index starts with 0.
                if user_choice < 0 or user_choice >= len(available_languages):
                    print("[ERROR] Language #{0} doesn't exist.".format(user_choice + 1))
                    continue

                else:
                    self.language = available_languages[user_choice]  # Set language.
                    break

            except(TypeError, ValueError):
                print("[ERROR] Please enter the number of the language you want to use.")
                continue

            except KeyboardInterrupt:
                print("[!] Using {0} as default language.".format(self.language))
                break

        return

    def getMessage(self, message_key: str):
        """
        Return a message from self.messages.

        :param str message_key: The key of the message to print.

        :returns str: The value of the key.
        """

        return self.messages[self.language][message_key]

    def main(self):
        """
        The main method of Main() class.

        :returns int: Error code.
                        0 = No error, all good.
                        1 = GameData.dat not found.
                        2 = CTRL+C pressed. (try/except block defined on program start.)
                        3 = An unknown error occured. (try/except block defined on program start.)
        """

        self.languageSelect()  # Select a language.

        # ? STEP #1: Check if GameData.dat is in the current or default save folder.

        # Check if GameData.dat is in the current directory.
        gamedata_exists = False
        while not gamedata_exists:
            if not os.path.isfile("GameData.dat"):
                # Try to find GameData.dat in the default save folder.
                if not os.path.isfile(os.path.join(self.default_savefile_path, "GameData.dat")):
                    input(self.getMessage("gd_not_found"))
                    continue

                else:
                    print(self.getMessage("confirm_gd_found").format(self.default_savefile_path))
                    while True:
                        set_savefile_path_confirm = input("Do you want to continue? (y/n): ")
                        if set_savefile_path_confirm.lower().startswith('y'):
                            self.savefile_path = self.default_savefile_path  # Set save folder.
                            gamedata_exists = True
                            break

                        else:
                            input(self.getMessage("gd_not_found"))
                            return 1

            else:
                # This means that the user has the GameData.dat in the current directory.
                self.savefile_path = "."
                break

        # ? STEP #2: Rename GameData.dat to savemod_GameData.dat.

        # If savemod_GameData.dat exists, delete it.
        if os.path.isfile("savemod_GameData.dat"):
            os.remove("savemod_GameData.dat")

        else:
            # Rename GameData.dat to savemod_GameData.dat.
            os.rename("GameData.dat", "savemod_GameData.dat")

        # ? STEP #3: Extract signature string.
        while True:
            try:
                with open(os.path.join(self.savefile_path, "GameData.dat"), "rb") as f:
                    signature = f.read(15)
                    break

            except IOError:
                print(self.getMessage("gen_msg"))
                while not os.path.exists(os.path.join(self.savefile_path, "GameData.dat")):
                    time.sleep(0.5)

                continue

        os.remove(os.path.join(self.savefile_path, "GameData.dat"))  # We don't need the original GameData.dat.

        # ? STEP #4: Modify save slot(s) data header with the signature string.
        for save_slot in glob.glob(os.path.join(self.savefile_path, "SlotData_?.dat")):
            print(self.getMessage("modsv").format(save_slot))
            with open(save_slot, "rb+") as f:
                content = f.read()
                content = content[:4] + signature + content[19:]
                f.seek(0)
                f.write(content)

        # ? STEP #5: Modify original shared GameData.dat.
        print(self.getMessage("modgd"))
        os.rename("savemod_GameData.dat", "GameData.dat")
        with open(os.path.join(self.savefile_path, "GameData.dat"), "rb+") as f:
            content = f.read()
            content = signature + content[15:]
            f.seek(0)
            f.write(content)

        # ? STEP #6: Profit.

        input(self.getMessage("end"))

        return 0


if __name__ == "__main__":
    try:
        sys.exit(Main().main())

    except KeyboardInterrupt:
        print("\n[!] Exiting...")
        sys.exit(2)

    except Exception as e:
        print("[!] An error occurred: {0}".format(e))
        sys.exit(3)<commit_msg>Wait for user input when an unexpected exception occurs.<commit_after>#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""

NieR:AutoModSave v0.1 by jimmyazrael
This script will guide and help you to import Nier:Automata's game saves shared by others.

Requirements:

1. Preferably you should have received the whole save folder,
   or at least you should have the following files:
   GameData.dat, one or more than one of the SlotData files
   and probably SystemData.dat. Although the use of SystemData.dat
   is still unknown.
2. Please make sure you back up your own save folder, as using other's
   save file will make yours unreadable. If you would like to use your save files
   again, simply treat your own backup save folder as the one shared by someone else
   and repeat the very same steps stated below.

Steps:

1. Back up your WHOLE save folder, which is likely located at `Documents/My Games/NieR_Automata`.
2. Remove everything except `Graphic.ini` in that folder.
3. Put the files (except `Graphic.ini`) you received from another player in the folder.

If you prefer exe:
    4. Put `NierAutoModSave.exe` in the same folder, run it, follow it, done.

If you prefer a Python script and you have Python installed:
    4. Put `NierAutoModSave.py` in the same folder and run it, follow it, done.
"""

import os
import sys
import glob
import time


class Main():
    """
    The main class.
    """

    def __init__(self):
        """
        The initialization method of Main() class.
        """

        # self.messages format: {<language>: {<message_id>: <message>},}

        # You can add a new language by adding a new item to the `self.messages` variable.
        self.messages = {
            "English": {
                "gd_not_found": """\
GameData.dat not found in this directory, please find and put it here.
Press ENTER to continue when the file is ready.""",
                "gd_found": "GameData.dat found in default folder:\n{0}",
                "gen_msg": """\
A new GameData.dat is currently needed to continue the process.
It can be generated by the game.
Please start the game. Do not close this window.""",
                "modsv": "Modifying {0}...",
                "modgd": "Modifying `GameData.dat`...",
                "end": "\nFinished. Glory to mankind!\nPress enter to exit..."
            },
            u"Chinese (中文)": {
                "gd_not_found": u"本目录下没有GameData.dat文件，请将其放入。\n放入后按回车继续。",
                "gd_found": "GameData.dat 在默认文件夹中找到:\n{0}",
                "gen_msg": u"""\
现在需要一个新的GameData.dat文件。
该文件应该由游戏自动生成。
请启动游戏。不要关闭此窗口。""",
                "modsv": u"修改 {0}...",
                "modgd": u"修改 GameData.dat...",
                "end": u"\n任务完成。荣耀归于人类！"
            },
            u"Tagalog": {
                "gd_not_found": "Hindi makita ang GameData.dat sa folder na ito. Pakihanap at pakilagay ang mga files dito at i-press ang ENTER.",
                "gd_found": "Nakita ang GameData.dat sa default folder:\n{0}",
                "gen_msg": """\
Kasalukuyang kailangan ang isang bagong GameData.dat upang magpatuloy sa proseso.
Ito ay awtomatikong gagawin ng laro.
Mangyaring buksan ang laro. Huwag isarado ang window na ito.""",
                "modsv": "Minomodify ang {0}...",
                "modgd": "Minomodify ang GameData.dat...",
                "end": "Tapos na. Glory to mankind! Pindutin ang enter para matapos na ang proseso."
            }
        }

        self.language = "English"  # Set default language to English.
        self.default_savefile_path = os.path.join(os.path.expanduser("~"), "Documents", "My Games", "NieR_Automata")

    def languageSelect(self):
        """
        Select a language from self.messages.

        :returns void:
        """

        print("Please select preferred language:\n")
        available_languages = list(self.messages.keys())
        i = 1
        # Print available keys (languages) of self.messages.
        for language in available_languages:
            print("[{0}] {1}".format(i, language))
            i += 1

        print()
        while True:
            try:
                # Get user's choice.
                user_choice = int(input("Language: ")) - 1  # Because Python index starts with 0.
                if user_choice < 0 or user_choice >= len(available_languages):
                    print("[ERROR] Language #{0} doesn't exist.".format(user_choice + 1))
                    continue

                else:
                    self.language = available_languages[user_choice]  # Set language.
                    break

            except(TypeError, ValueError):
                print("[ERROR] Please enter the number of the language you want to use.")
                continue

            except KeyboardInterrupt:
                print("[!] Using {0} as default language.".format(self.language))
                break

        return

    def getMessage(self, message_key: str):
        """
        Return a message from self.messages.

        :param str message_key: The key of the message to print.

        :returns str: The value of the key.
        """

        return self.messages[self.language][message_key]

    def main(self):
        """
        The main method of Main() class.

        :returns int: Error code.
                        0 = No error, all good.
                        1 = GameData.dat not found.
                        2 = CTRL+C pressed. (try/except block defined on program start.)
                        3 = An unknown error occured. (try/except block defined on program start.)
        """

        self.languageSelect()  # Select a language.

        # ? STEP #1: Check if GameData.dat is in the current or default save folder.

        # Check if GameData.dat is in the current directory.
        gamedata_exists = False
        while not gamedata_exists:
            if not os.path.isfile("GameData.dat"):
                # Try to find GameData.dat in the default save folder.
                if not os.path.isfile(os.path.join(self.default_savefile_path, "GameData.dat")):
                    input(self.getMessage("gd_not_found"))
                    continue

                else:
                    print(self.getMessage("confirm_gd_found").format(self.default_savefile_path))
                    while True:
                        set_savefile_path_confirm = input("Do you want to continue? (y/n): ")
                        if set_savefile_path_confirm.lower().startswith('y'):
                            self.savefile_path = self.default_savefile_path  # Set save folder.
                            gamedata_exists = True
                            break

                        else:
                            input(self.getMessage("gd_not_found"))
                            return 1

            else:
                # This means that the user has the GameData.dat in the current directory.
                self.savefile_path = "."
                break

        # ? STEP #2: Rename GameData.dat to savemod_GameData.dat.

        # If savemod_GameData.dat exists, delete it.
        if os.path.isfile("savemod_GameData.dat"):
            os.remove("savemod_GameData.dat")

        else:
            # Rename GameData.dat to savemod_GameData.dat.
            os.rename("GameData.dat", "savemod_GameData.dat")

        # ? STEP #3: Extract signature string.
        while True:
            try:
                with open(os.path.join(self.savefile_path, "GameData.dat"), "rb") as f:
                    signature = f.read(15)
                    break

            except IOError:
                print(self.getMessage("gen_msg"))
                while not os.path.exists(os.path.join(self.savefile_path, "GameData.dat")):
                    time.sleep(0.5)

                continue

        os.remove(os.path.join(self.savefile_path, "GameData.dat"))  # We don't need the original GameData.dat.

        # ? STEP #4: Modify save slot(s) data header with the signature string.
        for save_slot in glob.glob(os.path.join(self.savefile_path, "SlotData_?.dat")):
            print(self.getMessage("modsv").format(save_slot))
            with open(save_slot, "rb+") as f:
                content = f.read()
                content = content[:4] + signature + content[19:]
                f.seek(0)
                f.write(content)

        # ? STEP #5: Modify original shared GameData.dat.
        print(self.getMessage("modgd"))
        os.rename("savemod_GameData.dat", "GameData.dat")
        with open(os.path.join(self.savefile_path, "GameData.dat"), "rb+") as f:
            content = f.read()
            content = signature + content[15:]
            f.seek(0)
            f.write(content)

        # ? STEP #6: Profit.

        input(self.getMessage("end"))

        return 0


if __name__ == "__main__":
    try:
        sys.exit(Main().main())

    except KeyboardInterrupt:
        print("\n[!] Exiting...")
        sys.exit(2)

    except Exception as e:
        print("[!] An error occurred: {0}".format(e))
        input("Press enter to exit.")
        sys.exit(3)
{'fraction_non_alphanumeric': 0.10465308825964564, 'fraction_numerical': 0.005850858309874704, 'mean_word_length': 1.848294293350102, 'pattern_counts': {'":': 44, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2925175', 'n_tokens_mistral': 5376, 'n_tokens_neox': 5172, 'n_words': 1605}