Completed
Branch master (c65a32)
by Jochen
02:08
created

search_snippets.get_scope_label()   A

Complexity

Conditions 3

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 6
nop 2
dl 0
loc 8
rs 10
c 0
b 0
f 0
1
#!/usr/bin/env python
2
3
"""Search in (the latest versions of) snippets.
4
5
:Copyright: 2006-2019 Jochen Kupperschmidt
6
:License: Modified BSD, see LICENSE for details.
7
"""
8
9
import click
10
11
from byceps.services.snippet import service as snippet_service
12
from byceps.services.snippet.transfer.models import Scope
13
from byceps.util.system import get_config_filename_from_env_or_exit
14
15
from _util import app_context
16
from _validators import validate_site
17
18
19
def validate_site_if_given(ctx, param, value):
20
    if value is None:
21
        return None
22
23
    return validate_site(ctx, param, value)
24
25
26
@click.command()
27
@click.pass_context
28
@click.argument('search_term')
29
@click.option('--site', callback=validate_site_if_given)
30
@click.option('-v', '--verbose', is_flag=True)
31
def execute(ctx, search_term, site, verbose):
32
    scope = None
33
    if site is not None:
34
        scope = Scope.for_site(site.id)
35
36
    scope_label = get_scope_label(verbose, scope)
37
38
    matches = snippet_service.search_snippets(search_term, scope=scope)
39
40
    if not matches:
41
        if verbose:
42
            click.secho(
43
                f'No matching snippets for {scope_label} '
44
                f'and search term "{search_term}".',
45
                fg='yellow',
46
            )
47
        return
48
49
    for version in matches:
50
        snippet = version.snippet
51
        click.secho(f'{format_scope(snippet.scope)}\t{snippet.name}')
52
53
    if verbose:
54
        click.secho(
55
            f'\n{len(matches):d} matching snippet(s) '
56
            f'for {scope_label} and search term "{search_term}".',
57
            fg='green',
58
        )
59
60
61
def get_scope_label(verbose: bool, scope: Scope) -> str:
62
    if not verbose:
63
        return '<unknown>'
64
65
    if scope is None:
66
        return 'any scope'
67
68
    return f'scope "{format_scope(scope)}"'
69
70
71
def format_scope(scope):
72
    return f'{scope.type_}/{scope.name}'
73
74
75
if __name__ == '__main__':
76
    config_filename = get_config_filename_from_env_or_exit()
77
    with app_context(config_filename):
78
        execute()
79