~homeworkprod/byceps

ref: 90357856fb25b54d9e60125d1b658be3514449ae byceps/scripts/search_snippets.py -rwxr-xr-x 1.8 KiB
90357856 — Jochen Kupperschmidt Prepare login-based test with frozen time for Flask v2.x, Werkzeug v2.x 5 months ago
                                                                                
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
#!/usr/bin/env python

"""Search in (the latest versions of) snippets.

:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""

import click

from byceps.services.snippet import service as snippet_service
from byceps.services.snippet.transfer.models import Scope

from _util import call_with_app_context
from _validators import validate_site


def validate_site_if_given(ctx, param, value):
    if value is None:
        return None

    return validate_site(ctx, param, value)


@click.command()
@click.pass_context
@click.argument('search_term')
@click.option('--site', callback=validate_site_if_given)
@click.option('-v', '--verbose', is_flag=True)
def execute(ctx, search_term, site, verbose):
    scope = None
    if site is not None:
        scope = Scope.for_site(site.id)

    scope_label = get_scope_label(verbose, scope)

    matches = snippet_service.search_snippets(search_term, scope=scope)

    if not matches:
        if verbose:
            click.secho(
                f'No matching snippets for {scope_label} '
                f'and search term "{search_term}".',
                fg='yellow',
            )
        return

    for version in matches:
        snippet = version.snippet
        click.secho(f'{format_scope(snippet.scope)}\t{snippet.name}')

    if verbose:
        click.secho(
            f'\n{len(matches):d} matching snippet(s) '
            f'for {scope_label} and search term "{search_term}".',
            fg='green',
        )


def get_scope_label(verbose: bool, scope: Scope) -> str:
    if not verbose:
        return '<unknown>'

    if scope is None:
        return 'any scope'

    return f'scope "{format_scope(scope)}"'


def format_scope(scope):
    return f'{scope.type_}/{scope.name}'


if __name__ == '__main__':
    call_with_app_context(execute)