aboutsummaryrefslogtreecommitdiffstats
path: root/peebz/command.py
blob: 7b6dc167230c6967e99cf4cc3575896a1b4a8b38 (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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: GPL-2.0-or-later
# Copyright (C) 2020 by the Linux Foundation
#

import sys
import argparse
import time

import b4
import logging
import logging.handlers
import peebz

logger = peebz.logger


def cmd_parse(cmdargs):
    import peebz.parse
    peebz.parse.main(cmdargs)


def cmd_bz2pi(cmdargs):
    import peebz.bz2pi
    peebz.bz2pi.main(cmdargs)


def cmd_pi2bz(cmdargs):
    import peebz.pi2bz
    peebz.pi2bz.main(cmdargs)


def cmd_git2bz(cmdargs):
    import peebz.git2bz
    peebz.git2bz.main(cmdargs)


def cmd_cron(cmdargs):
    cstart = int(time.time())
    logger.info('--- Start cron ---')
    logger.info('--- Running bz2pi ---')
    cmd_bz2pi(cmdargs)
    logger.info('--- Running pi2bz ---')
    cmd_pi2bz(cmdargs)
    logger.info('--- Running git2bz ---')
    cmd_git2bz(cmdargs)
    celapsed = int(time.time()) - cstart
    logger.info('--- End cron (elapsed: %s s) ---', celapsed)


def cmd_bzdump(cmdargs):
    import json
    from pygments import highlight, lexers, formatters
    if cmdargs.bug_id:
        rdata = peebz.bz_get_bug(cmdargs.bug_id, resolve_dupes=cmdargs.resolve_dupes)
    elif cmdargs.username:
        rdata = peebz.bz_get_user(cmdargs.username)
    elif cmdargs.quicksearch:
        rdata = peebz.bz_quicksearch_bugs(query=cmdargs.quicksearch)
    elif cmdargs.attachment_id:
        rdata = peebz.bz_get_attachment_by_aid(int(cmdargs.attachment_id))
    else:
        sys.exit(1)

    jdata = json.dumps(rdata, sort_keys=True, indent=4)
    colorized = highlight(jdata, lexers.JsonLexer(), formatters.TerminalFormatter())
    print(colorized)


def setup_parser() -> argparse.ArgumentParser:
    # noinspection PyTypeChecker
    parser = argparse.ArgumentParser(
        prog='peebz',
        description='A tool to bridge public-inbox collections with bugzilla',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    )
    parser.add_argument('--version', action='version', version=peebz.__VERSION__)
    parser.add_argument('-d', '--debug', action='store_true', default=False,
                        help='Add more debugging info to the output')
    parser.add_argument('-q', '--quiet', action='store_true', default=False,
                        help='Output critical information only')
    parser.add_argument('-c', '--config', required=True,
                        help='config.toml to use')
    parser.add_argument('--dry-run', action='store_true', default=False,
                        help='Dry run, do not make any changes')

    subparsers = parser.add_subparsers(help='sub-command help', dest='subcmd')
    # parse : process RFC2822 messages passed on stdin (testing mode)
    sp_parse = subparsers.add_parser('parse', help='Parse messages passed via stdin')
    sp_parse.add_argument('--product', help='Force this product instead of guessing by recipient')
    sp_parse.add_argument('--component', help='Force this component instead of guessing by recipient')
    sp_parse.set_defaults(func=cmd_parse)

    # pi2bz : query public-inbox to find the latest treads that interest us
    sp_pi2bz = subparsers.add_parser('pi2bz', help='Query public-inbox sources for updates')
    sp_pi2bz.add_argument('--product', help='Only run queries for this product')
    sp_pi2bz.add_argument('--component', help='Only run queries for this component')
    sp_pi2bz.set_defaults(func=cmd_pi2bz)

    # git2bz : query git repositories to find commits that interest us
    sp_git2bz = subparsers.add_parser('git2bz', help='Query git repos for bug mentioning commits')
    sp_git2bz.add_argument('--product', help='Only run queries for this product')
    sp_git2bz.add_argument('--component', help='Only run queries for this component')
    sp_git2bz.set_defaults(func=cmd_git2bz)

    # bz2pi: query bugzilla and sends out any mail updates
    sp_bz2pi = subparsers.add_parser('bz2pi', help='Send emails about bugzilla-originated changes')
    sp_bz2pi.set_defaults(func=cmd_bz2pi)

    sp_cron = subparsers.add_parser('cron', help='Run all actions defined in the config ("cron mode")')
    sp_cron.set_defaults(func=cmd_cron)

    # show  : command to show REST raw REST output
    sp_bzdump = subparsers.add_parser('bzdump', help='Show colorized raw REST output from bugzilla API')
    sp_bzdump.add_argument('-b', '--bug-id', type=int, help='Bug to show')
    sp_bzdump.add_argument('-c', '--comment-id', help='Comment to show')
    sp_bzdump.add_argument('-a', '--attachment-id', help='Attachment to show')
    sp_bzdump.add_argument('-u', '--username', help='User to show')
    sp_bzdump.add_argument('-q', '--quicksearch', help='Quicksearch query to run')

    sp_bzdump.add_argument('--resolve-dupes', action='store_true', help='Resolve dupes')
    sp_bzdump.set_defaults(func=cmd_bzdump)

    return parser


def cmd():
    parser = setup_parser()
    cmdargs = parser.parse_args()
    logger.setLevel(logging.DEBUG)

    ch = logging.StreamHandler()
    formatter = logging.Formatter('%(message)s')
    ch.setFormatter(formatter)

    if cmdargs.quiet:
        ch.setLevel(logging.CRITICAL)
    elif cmdargs.debug:
        ch.setLevel(logging.DEBUG)
    else:
        ch.setLevel(logging.INFO)

    logger.addHandler(ch)

    if 'func' not in cmdargs:
        parser.print_help()
        sys.exit(1)

    with open(cmdargs.config, 'rb') as fh:
        try:
            import tomllib  # noqa
            peebz.CONFIG = tomllib.load(fh)
        except ModuleNotFoundError:
            import tomli  # noqa
            peebz.CONFIG = tomli.load(fh)

    try:
        logfile = peebz.CONFIG['logging']['logfile']
        flh = logging.handlers.WatchedFileHandler(logfile)
        fmt = '[%(process)d] %(asctime)s - ' + cmdargs.subcmd + ': %(message)s'
        flh.setFormatter(logging.Formatter(fmt))
        loglevel = peebz.CONFIG['logging'].get('loglevel', 'info')
        if loglevel == 'debug':
            flh.setLevel(logging.DEBUG)
        else:
            flh.setLevel(logging.INFO)
        logger.addHandler(flh)
    except KeyError:
        # No file logging for you
        pass

    cmdargs.func(cmdargs)


if __name__ == '__main__':
    import os
    # noinspection PyBroadException
    try:
        if peebz.__VERSION__.endswith('-dev'):
            base = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
            dotgit = os.path.join(base, '.git')
            lines = b4.git_get_command_lines(dotgit, ['rev-parse', '--short', 'HEAD'])
            if lines:
                peebz.__VERSION__ = '%s-%.5s' % (peebz.__VERSION__, lines[0].strip())
    except Exception as ex:
        pass
    cmd()