Report on stats by bucket

def buckets(bucket=None, account=None, matched=False, kdenied=False,
            errors=False, dbpath=None, size=None, denied=False,
            format=None, incomplete=False, oversize=False, region=(),
            not_region=(), inventory=None, output=None, config=None, sort=None,
            tagprefix=None, not_bucket=None):
    """Report on stats by bucket"""

    d = db.db(dbpath)

    if tagprefix and not config:
        raise ValueError(
            "account tag value inclusion requires account config file")

    if config and tagprefix:
        with open(config) as fh:
            data = json.load(fh).get('accounts')
            account_data = {}
            for a in data:
                for t in a['tags']:
                    if t.startswith(tagprefix):
                        account_data[a['name']] = t[len(tagprefix):]

    buckets = []
    for b in sorted(d.buckets(account),
                    key=operator.attrgetter('bucket_id')):
        if bucket and b.name not in bucket:
            continue
        if not_bucket and b.name in not_bucket:
            continue
        if matched and not b.matched:
            continue
        if kdenied and not b.keys_denied:
            continue
        if errors and not b.error_count:
            continue
        if size and b.size < size:
            continue
        if inventory and not b.using_inventory:
            continue
        if denied and not b.denied:
            continue
        if oversize and b.scanned <= b.size:
            continue
        if incomplete and b.percent_scanned >= incomplete:
            continue
        if region and b.region not in region:
            continue
        if not_region and b.region in not_region:
            continue
        if tagprefix:
            setattr(b, tagprefix[:-1], account_data[b.account])
        buckets.append(b)

    if sort:
        key = operator.attrgetter(sort)
        buckets = list(reversed(sorted(buckets, key=key)))
    formatter = format == 'csv' and format_csv or format_plain
    keys = tagprefix and (tagprefix[:-1],) or ()
    formatter(buckets, output, keys=keys)