Beispiel #1
0
def get_files_info(directory, data_list=None):
    ret = []

    base_path = join(data_path, directory)
    index_config = join(base_path, 'index.cfg')
    index = RawConfigParser()
    index.modified = False
    if isfile(index_config):
        index.read(index_config)

    files_list = [
        f for f in listdir(base_path)
        if isfile(join(base_path, f)) and f[-4:] == '.csv'
    ]
    removed_order = None
    order_num = len(index.sections())
    for f in files_list:
        file_path = join(base_path, f)
        info = {
            'file': f,
            'dir': directory,
            'size': getsize(file_path),
            'mtime': getmtime(file_path),
        }
        if index.has_section(f):
            info['order'] = index.getint(f, 'order')
            info['active'] = index.getboolean(f, 'active')
            info['comment'] = index.get(f, 'comment')

        else:
            index.add_section(f)
            order_num += 1
            info['order'] = order_num
            info['active'] = True
            info['comment'] = u''
            index.set(f, 'order', info['order'])
            index.set(f, 'active', info['active'])
            index.set(f, 'comment', info['comment'])
            index.modified = True

        if data_list is not None:
            data = next(
                (x for x in data_list if x.get('file') == info['file']))
            if data is not None and data.get('remove') is True:
                index.remove_section(f)
                index.modified = True
                removed_order = data['order']
                unlink(file_path)
                continue

            elif data is not None:
                info['order'] = int(data.get('order', info['order']))
                info['active'] = bool(data.get('active', info['active']))
                info['comment'] = unicode(data.get('comment', info['comment']))
                index.set(f, 'order', info['order'])
                index.set(f, 'active', info['active'])
                index.set(f, 'comment', info['comment'])
                index.modified = True

        ret.append(info)

    if removed_order is not None:
        ret.sort(key=lambda nfo: nfo['order'])
        for i, info in enumerate(ret):
            if info['order'] > removed_order:
                info['order'] -= 1
                index.set(info['file'], 'order', info['order'])

    if index.modified:
        with open(index_config, 'wb') as fd:
            index.write(fd)

    ret.sort(key=lambda nfo: nfo['order'])
    return ret