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 | if verbose: |
||
37 | if scope is not None: |
||
38 | scope_label = 'scope "{}"'.format(format_scope(scope)) |
||
39 | else: |
||
40 | scope_label = 'any scope' |
||
41 | |||
42 | matches = snippet_service.search_snippets(search_term, scope=scope) |
||
43 | |||
44 | if not matches: |
||
45 | if verbose: |
||
46 | click.secho( |
||
47 | f'No matching snippets for {scope_label} ' |
||
48 | f'and search term "{search_term}".', |
||
49 | fg='yellow') |
||
50 | return |
||
51 | |||
52 | for version in matches: |
||
53 | snippet = version.snippet |
||
54 | click.secho('{}\t{}'.format(format_scope(snippet.scope), snippet.name)) |
||
55 | |||
56 | if verbose: |
||
57 | click.secho( |
||
58 | '\n{:d} matching snippet(s) for {} and search term "{}".' |
||
59 | .format(len(matches), scope_label, search_term), |
||
0 ignored issues
–
show
introduced
by
Loading history...
|
|||
60 | fg='green') |
||
61 | |||
62 | |||
63 | def format_scope(scope): |
||
64 | return f'{scope.type_}/{scope.name}' |
||
65 | |||
66 | |||
67 | if __name__ == '__main__': |
||
68 | config_filename = get_config_filename_from_env_or_exit() |
||
69 | with app_context(config_filename): |
||
70 | execute() |
||
71 |