Exemplo n.º 1
0
def downloadVersionManifest() -> Dict:
    """
    Downloads the minecraft version manifest and returns it parsed as a dictionary

    Format:
        {
            "latest": {
                "release": str
                "snapshot": str
            },
            "versions": [
                {
                    "id": str,
                    "type": str,
                    "url": str,
                    "time": str,
                    "releaseTime": str
                }
            ]
        }

    Returns:
        The version manifest
    """
    Logger.info("[Assets] Fetching version manifest...")
    request = _get(VERSION_MANIFEST_URL)
    manifest = json.load(request)
    Logger.info("[Assets] Successfully fetched version manifest")
    Logger.debug(manifest)
    return manifest
Exemplo n.º 2
0
def download_minecraft_server(version_id: str, target: str) -> str:
    """
    Downloads the minecraft server for version `version_id` and returns the full path.

    Args:
        version_id: the id for the version
        target: the target directory

    Returns:
        The full file path to `server.jar`

    """
    url = getVersionUrl(version_id)

    Logger.info(f"[Assets] Downloading minecraft server json at {url}")

    version = json.load(_get(url))

    Logger.info("[Assets] Downloaded version.json")
    Logger.debug(version)

    server_url = version["downloads"]["server"]["url"]
    Logger.info(f"[Assets] Starting to download server {version['id']}...")
    with _get(server_url) as server:
        download_size = server.length
        with click.progressbar(length=download_size,
                               label="Downloading server jar") as bar:
            fpath = join(target, "server.jar")
            with open(fpath, "wb+") as f:
                while chunk := server.read(16384):
                    f.write(chunk)
                    bar.update(len(chunk))
        Logger.info(f"[Assets] Downloaded {download_size / 1000000:.2f} mb")
        Logger.info(f"[Assets] Created server.jar at {fpath}")
Exemplo n.º 3
0
def debug_log_text(text: str, message):
    """Debug logs a multi-line text and annotates it with line numbers."""
    text = text.strip().split("\n")
    padding = len(str(len(text)))
    debug_code = "\n\t".join(f"[{str(index + 1).zfill(padding)}] {i}"
                             for index, i in enumerate(text))
    Logger.debug(f"{message}\n\t{debug_code}")
Exemplo n.º 4
0
    def add_var(self, name: str, value: Resource) -> Resource:
        """
        Adds a variable to this context and assigns it the correct variable context.
        Note that there must be a valid variable context!
        Fails if the variable name does already exist.

        Args:
            name: the name of the variable
            value: the resource

        Returns:
            None

        Raises:
            ValueError: If the resource does already exist
        """
        if name in self.namespace:
            raise ValueError(f"Variable {name} does already exist!")

        # should an error be thrown when no history is found?
        variable_context = self.variable_context.get(name, None)
        if variable_context is None:
            Logger.debug(
                f"[Context] No context data available for variable '{name}' ({value})"
            )

        value.is_variable = True
        self.namespace[name] = self.Variable(value, variable_context)
        return value
Exemplo n.º 5
0
def makeData(version: str) -> str:
    """
    writes all important minecraft data to a file and returns the path
    Note that this wil crash if the version is below 1.14.
    """

    version = version or get_latest_version()

    # first test if the file already exists
    directory = getVersionDir(version)
    file = join(directory, "data.json")
    if exists(file):
        with open(file) as f:
            try:
                data = json.load(f)
                if data.get("version", 0) != assets.__version__:
                    Logger.warn(
                        f"File '{file}' uses old version format {data.get('version', 0)} "
                        f"(Required {assets.__version__})")
                else:
                    Logger.debug(f"Already got data for version {version}")
                    return file
            except json.JSONDecodeError:
                pass

    contents = getDataJson(version)
    contents["version"] = assets.__version__
    with open(file, "w+") as f:
        json.dump(contents, f)
    Logger.info(f"Create data file {file}")
    return file
Exemplo n.º 6
0
    def toJson(self, markup: str, *args: Resource) -> List[dict]:
        """
        Converts a markup string to a minecraft json format string.

        Args:
            markup: the markup string
            *args: resources to insert into the placeholders

        Returns:
            A json string
        """
        self.state = dict(args=args, used_placeholders=set())
        try:
            Logger.debug(f"[MarkupParser] parsing '{markup}'")
            tree = get_json_markup_grammar().parse(markup)
            debug_log_text(tree.pretty(), "Parse tree: ")
            data = self.visit(tree)
        except UnexpectedToken as e:
            raise McScriptInvalidMarkupError(f"\nFailed to parse Markup string:\n"
                                             f"{e.get_context(markup, span=len(markup))}"
                                             f"Unexpected token: {e.token.type}('{e.token}')\n"
                                             f"Expected one of {e.expected}", self.compileState)

        all_args = set(range(len(args)))
        for used_arg in self.state["used_placeholders"]:
            all_args.remove(used_arg)

        if all_args:
            raise McScriptArgumentError(f"Not all arguments were used!\nunused indices: "
                                        f"{', '.join(str(i) for i in all_args)}", self.compileState)

        # remove duplicate text elements
        return self.compact_data(data)
Exemplo n.º 7
0
    def __init__(self, msg: str):
        Logger.error(f"Exception occurred: {self.__class__.__name__}")

        debug_exception = ["\n".join(f"\t* {i}" for i in msg.split("\n"))]
        super().__init__(msg)
        debug_exception += self.get_stack()
        debug_exception = "\n".join(debug_exception)
        Logger.debug(f"Exception message:\n{debug_exception}")
Exemplo n.º 8
0
 def __post_init__(self):
     if len(self.name) > 16:
         raise ValueError("Cannot create a scoreboard with a length > 16")
     if self.index >= len(VALID_OBJECTIVE_CHARACTERS)**3:
         raise ValueError(
             f"Maximum id exceeded: {self.index} expected at most {len(VALID_OBJECTIVE_CHARACTERS) ** 3 - 1}"
         )
     Logger.debug(
         f"[Scoreboard] created {self.name} with id {self.get_name()}")
Exemplo n.º 9
0
def import_sub_modules():
    for name in iterBuiltins():
        Logger.debug(f"[Resource] auto-importing {name}")
        import_module("." + name, __name__)