Skip to content

Support directory-like "browsing" of SBAsset6 objects? #35

@apocalyptech

Description

@apocalyptech

(Very excellent library you've created, btw - thanks a bunch!)

While writing a little utility with this library, I came across the need to get "directory listings" of paths within the pakfile. Something for a possible enhancement to the SBAsset6 class, perhaps?

In my own app I added it with an ugly little class like so:

class PakTree(object):
    """
    Tree-based dict so we can "browse" pak contents by directory.
    Makes no distinction between directories and files.
    """

    def __init__(self):
        self.top = {}

    def add_path(self, pathname):
        """
        Adds a path to our tree
        """
        parts = pathname.split('/')[1:]
        cur = self.top
        for part in parts:
            if part not in cur:
                cur[part] = {}
            cur = cur[part]

    def get_all_in_path(self, path):
        """
        Gets all "files" within the given path.
        """
        parts = path.split('/')[1:]
        cur = self.top
        for part in parts:
            if part not in cur:
                return []
            cur = cur[part]
        return sorted(cur.keys())

    def get_all_matching_ext(self, path, ext):
        """
        Gets all "files" within the given path which match the given
        extension.  Note that "extension" is being used here a bit
        generously - be sure to pass in a leading dot if you want it
        to *actually* be an extension.
        """
        to_ret = []
        for item in self.get_all_in_path(path):
            if item.endswith(ext):
                to_ret.append(item)
        return to_ret

Which gets populated via:

            paktree = PakTree()
            pakdata = starbound.SBAsset6(pakdf)
            pakdata.read_index()
            for path in pakdata.index.keys():
                paktree.add_path(path)

... but that's pretty ugly, and the get_all_matching_ext method may not be something you'd want in the base package anyway. If this is something you'd be interested in having, I could try my hand at a more-suitable-for-public-consumption version.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions