Example #1
0
def handle_inspect(**kwargs):
    """ Handle inspect actions.

    Args:
        **kwargs (dict): Arguments
    """
    default_args = {
        'input': None
    }

    default_args.update(kwargs)

    args = dict_to_namedtuple(default_args)

    # split input path
    dirname, basename = os.path.split(unicode(args.input))

    # open input filesystem
    try:
        in_fs = OSFS(dirname)

        if in_fs.isfile(basename):
            inspect_file(in_fs.getsyspath(basename))
        elif in_fs.isdir(basename):
            inspect_dir(in_fs.opendir(basename))
    except CreateFailed:
        console.error('Input {} does not exist.'.format(args.input))

        return
def main():
    parser = argparse.ArgumentParser(description='Create free editor.slf')
    parser.add_argument('original', help="Original editor.slf")
    parser.add_argument(
        '-o',
        '--output',
        default='build/editor.slf',
        help="Where to store the created slf file"
    )
    args = parser.parse_args()

    if not os.path.exists(os.path.dirname(args.output)):
        os.makedirs(os.path.dirname(args.output))

    target_fs = BufferedSlfFS()
    replacement_fs = OSFS('editor')
    with open(args.original, 'rb') as source_file:
        source_fs = SlfFS(source_file)

        target_fs.library_name = source_fs.library_name
        target_fs.library_path = source_fs.library_path
        target_fs.version = source_fs.version
        target_fs.sort = source_fs.sort

        for directory in source_fs.walkdirs():
            if directory == '/':
                continue
            target_fs.makedir(directory)
        for file in source_fs.walkfiles():
            base_name, _ = os.path.splitext(file)
            with source_fs.open(file, 'rb') as source, target_fs.open(file, 'wb') as target:
                ja2_images = load_8bit_sti(source)
                replacement_path = base_name + '.gif'
                replacement_file_exists = replacement_fs.isfile(replacement_path)
                replacement_dir = file
                replacement_dir_exists = replacement_fs.isdir(replacement_dir)
                if len(ja2_images) == 1 and replacement_file_exists:
                    print("Replacing {0} with {1}".format(file, replacement_path))
                    replacement_img = Image.open(replacement_fs.open(replacement_path, 'rb'))
                    ja2_images._palette = replacement_img.palette
                    ja2_images.images[0]._image = replacement_img
                elif len(ja2_images) > 1 and replacement_dir_exists:
                    for i in range(len(ja2_images)):
                        replacement_path = replacement_dir + '/{}.gif'.format(i)

                        print("Replacing {0} with {1}".format(file, replacement_path))
                        replacement_img = Image.open(replacement_fs.open(replacement_path, 'rb'))
                        ja2_images._palette = replacement_img.palette
                        ja2_images.images[i]._image = replacement_img
                else:
                    print("Replacing {0} with nothingness".format(file))
                    for sub_image in ja2_images.images:
                        width, height = sub_image.image.size
                        sub_image._image = Image.new('P', (width, height), color=54)

                save_8bit_sti(ja2_images, target)

    with open(args.output, 'wb') as target_file:
        target_fs.save(target_file)
def eggifySingle(srcFS, src, destFS, dest, config=None):
    """ Eggify single source to single destination.

    Args:
        src (basestring)
        dest (basestring)

    Raises:
        MissingDestinationException
    """

    if dest is None:
        raise MissingDestinationException()

    if config is None:
        config = {}

    if src.startswith("/") or src[1] == ":":
        head, tail = os.path.split(src)

        srcFS = OSFS(head)
        src = tail

    if srcFS.isfile(unicode(src)):
        assertFS(destFS.getsyspath(unicode(dest)))

        workingDir = srcFS.getsyspath(unicode("/"))
        devnull = open(os.devnull, 'w')

        cmd = ["python", src, "bdist_egg"]

        if "purge" in config.keys() and config["purge"]:
            cmd.append("--exclude-source-files")            

        subprocess.check_call(cmd, cwd=workingDir, stdout=devnull, stderr=devnull)
    
        if srcFS.isdir(unicode("dist")):
            distFS = srcFS.opendir(unicode("dist"))

            for name in reversed(sorted(distFS.listdir("/"))):
                if name.endswith(".egg"):
                    destEggFS = destFS.opendir(unicode(dest))

                    # remove existing eggs
                    removeOldEggs(destEggFS, name)

                    eggSrcPath = distFS.getsyspath(unicode(name))
                    eggDestPath = destEggFS.getsyspath(unicode(name))

                    copy_file(distFS, unicode(name), destEggFS, unicode(name))

                    print "copied {} to {}".format(eggSrcPath, eggDestPath)

                    break
Example #4
0
def handle_preview(**kwargs):
    """ Handle preview actions.

    Args:
        **kwargs (dict): Arguments
    """
    default_args = {
        'input': None,
        'output': None,
        'prefix': None,
        'layer': None,
        'num_threads': None,
        'multithreading': 1
    }

    default_args.update(kwargs)

    args = dict_to_namedtuple(default_args)

    # open output filesystem
    out_fs = assure_fs(args.output)

    # join layer
    layer = None

    if args.layer:
        layer = ' '.join(args.layer)

    # split input path
    dirname, basename = os.path.split(unicode(args.input))

    # open input filesystem
    try:
        in_fs = OSFS(dirname)

        if in_fs.isfile(basename):
            filename, extension = os.path.splitext(basename)

            # prepend prefix to filename
            if args.prefix:
                filename = args.prefix + filename

            out_name = unicode(filename + '.jpg')

            preview_file(in_fs.getsyspath(basename), out_fs.getsyspath(out_name), layer)
        elif in_fs.isdir(basename):
            preview_dir(in_fs.opendir(basename), out_fs, args.num_threads, bool(args.multithreading), prefix=args.prefix, layer=layer)
    except CreateFailed:
        console.error('Input {} does not exist.'.format(args.input))

        return
Example #5
0
    def reduce_path(carry_fs, value):
        """ Reduce path by opening or creating each segment and returning the last. 

        Args:
            carry_fs (fs): Opened filesystem
            value (str): Next path segment

        Returns:
            fs
        """
        if not isinstance(carry_fs, FS):
            carry_fs = OSFS(carry_fs + separator)

        if not carry_fs.isdir(value):
            carry_fs.makedirs(value)

        # open next carry_fs
        next_carry_fs = OSFS(carry_fs.getsyspath(value))

        # close carry_fs
        carry_fs.close()

        return next_carry_fs
Example #6
0
def dl_pages():
    base = 'band_pages'
    bandpages = OSFS(base)
    c = 0
    with requests.session() as session:
        with open('bandpages_original.csv', 'r') as bndin:
            for row in DictReader(bndin):
                band = row['band']
                wlink = row['wlink']
                malink = row['malink']
                if not bandpages.isdir(band):
                    bandpages.makedir(band)
                session.headers.update({'User-Agent': useragents[c]})
                request = session.get(wlink)
                write_page(band, 'wiki', request)
                if malink != 'none':
                    request = session.get(malink)
                    write_page(band, 'ma', request)
                c += 1
                if c == 3:
                    c = 0

    bandpages.close()
Example #7
0
def main():
    parser = argparse.ArgumentParser(description='Create free editor.slf')
    parser.add_argument('--original', help="Original editor.slf")
    parser.add_argument('-o',
                        '--output',
                        default='build/editor.slf',
                        help="Where to store the created slf file")
    parser.add_argument('--name', help="Library name")
    args = parser.parse_args()

    if not os.path.exists(os.path.dirname(args.output)):
        os.makedirs(os.path.dirname(args.output))

    if args.original is None:
        target_fs = create_free_editorslf(args.name)
        with open(args.output, 'wb') as target_file:
            target_fs.save(target_file)
        generate_md5_file(args.output)
        return

    # create editor.slf by replacing images in the original editor.slf
    target_fs = BufferedSlfFS()
    replacement_fs = OSFS('editor')
    with open(args.original, 'rb') as source_file:
        source_fs = SlfFS(source_file)

        target_fs.library_name = args.name or source_fs.library_name
        target_fs.library_path = source_fs.library_path
        target_fs.version = source_fs.version
        target_fs.sort = source_fs.sort

        for directory in source_fs.walkdirs():
            if directory == '/':
                continue
            target_fs.makedir(directory)
        for file in source_fs.walkfiles():
            base_name, _ = os.path.splitext(file)
            with source_fs.open(file, 'rb') as source, target_fs.open(
                    file, 'wb') as target:
                ja2_images = load_8bit_sti(source)
                replacement_path = base_name + '.gif'
                replacement_file_exists = replacement_fs.isfile(
                    replacement_path)
                replacement_dir = file
                replacement_dir_exists = replacement_fs.isdir(replacement_dir)
                if len(ja2_images) == 1 and replacement_file_exists:
                    print("Replacing {0} with {1}".format(
                        file, replacement_path))
                    replacement_img = Image.open(
                        replacement_fs.open(replacement_path, 'rb'))
                    ja2_images._palette = replacement_img.palette
                    ja2_images.images[0]._image = replacement_img
                elif len(ja2_images) > 1 and replacement_dir_exists:
                    for i in range(len(ja2_images)):
                        replacement_path = replacement_dir + '/{}.gif'.format(
                            i)

                        print("Replacing {0} with {1}".format(
                            file, replacement_path))
                        replacement_img = Image.open(
                            replacement_fs.open(replacement_path, 'rb'))
                        ja2_images._palette = replacement_img.palette
                        ja2_images.images[i]._image = replacement_img
                else:
                    print("Replacing {0} with nothingness".format(file))
                    for sub_image in ja2_images.images:
                        width, height = sub_image.image.size
                        sub_image._image = Image.new('P', (width, height),
                                                     color=54)

                save_8bit_sti(ja2_images, target)

    with open(args.output, 'wb') as target_file:
        target_fs.save(target_file)
    generate_md5_file(args.output)
Example #8
0
def handle_rechannel(**kwargs):
    """ Handle rechannel actions.

    Args:
        **kwargs (dict): Arguments
    """
    default_args = {
        'input': None,
        'output': None,
        'prefix': None,
        'map': None,
        'num_threads': None,
        'multithreading': 1
    }

    default_args.update(kwargs)

    args = dict_to_namedtuple(default_args)

    # open output filesystem
    out_fs = assure_fs(args.output)

    # split map path
    dirname, basename = os.path.split(unicode(args.map))
    try:
        map_fs = OSFS(dirname)

        if map_fs.isfile(basename):
            with map_fs.open(basename) as file_handle:
                try:
                    layer_map = json.loads(file_handle.read())
                except Exception as error:
                    console.error(error)

                    return
        else:
            console.error('Map {} does not exist.'.format(args.map))

            return
    except CreateFailed:
        console.error('Map parent directory {} does not exist.'.format(args.map))

        return

    # split input path
    dirname, basename = os.path.split(unicode(args.input))

    # open input filesystem
    try:
        in_fs = OSFS(dirname)

        if in_fs.isfile(basename):
            # prepend prefix to basename
            if args.prefix:
                basename = args.prefix + basename

            rechannel_file(in_fs.getsyspath(basename), out_fs.getsyspath(basename), layer_map)
        elif in_fs.isdir(basename):
            rechannel_dir(in_fs.opendir(basename), out_fs, layer_map, args.num_threads, bool(args.multithreading), prefix=args.prefix)
    except CreateFailed:
        console.error('Input {} does not exist.'.format(args.input))

        return