summaryrefslogtreecommitdiff
path: root/archivist/cli.py
blob: 0b8abe12fac4bf1bb22975f211c5707465cd1c0f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
import click

CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])

def enable_debug():
    import logging
    logger = logging.getLogger('peewee')
    logger.setLevel(logging.DEBUG)
    logger.addHandler(logging.StreamHandler())

@click.group(context_settings = CONTEXT_SETTINGS)
@click.option('--debug', '-d', is_flag=True, default=False)
def cli(debug):
    if debug: enable_debug()

@cli.group()
def db():
    """Database Management"""
    pass

@db.command()
def init():
    """Initialize the database, if not done already."""
    from .model import create_tables, db
    from .prefixes import register_prefixes
    create_tables()
    with db.atomic():
        register_prefixes()

@db.command()
@click.confirmation_option(prompt="Are you sure you want to drop the database?")
def drop():
    """Completely drop all tables."""
    from .model import drop_tables
    drop_tables()

@cli.group()
def tag():
    """Handling of tags"""
    pass

@tag.command('list')
def list_tags():
    from .model import Tag

    print("Tags")
    print("====")
    print()

    for t in Tag.select():
        print(' *', t)

@tag.command('prefixes')
def list_prefixes():
    from .model import Prefix
    
    print("Prefixes")
    print("========")
    print()

    for p in Prefix.select():
        print("  * %s (builtin: %s; pseudo: %s)" % (p.name, p.builtin, p.pseudo))

class PrefixTag:
    def __init__(self, tag, prefix = None):
        self.tag = tag
        self.prefix = prefix

    def __str__(self):
        if self.prefix:
            return '%s:%s' % (self.prefix, self.tag)
        else:
            return self.tag

class PrefixTagType(click.ParamType):
    name = 'prefixed tag'

    def convert(self, value, param, ctx):
        try:
            prefix, tag = value.split(':')
            if not tag:
                return PrefixTag(prefix)

            return PrefixTag(tag, prefix)
        except ValueError:
            self.fail("%s is an invalid tag. Correct form '[prefix:]tag'." % value, param, ctx)

TAG = PrefixTagType()

@tag.command('add')
@click.argument('name', type = TAG)
@click.argument('description', required = False)
def add_tag(name, description):
    from .model import Tag, Prefix, db

    with db.atomic():
        if name.prefix:
            prefix, created = Prefix.get_or_create(name = name.prefix)

        if not created and prefix.pseudo:
            raise click.UsageError("Prefix '%s' is not allowed to carry additional tags." % name.prefix)

        tag, created = Tag.create_or_get(name = name.tag, prefix = name.prefix, description = description)
        if not created:
            print("Tag already existed:", tag)

@tag.command('edit')
@click.option('--description')
@click.argument('name', type = TAG)
def edit_tag(description, name):
    from .model import Tag, Prefix, db

    try:
        tag = Tag.get(name = name.tag, prefix = name.prefix)
    except Tag.DoesNotExist:
        raise click.UsageError("Tag '%s' does not exist." % name)

    if description:
        tag.description = description
        tag.save()