Completed
Push — main ( 963be5...3918f7 )
by Jochen
04:19
created

weitersager.argparser.parse_args()   B

Complexity

Conditions 1

Size

Total Lines 50
Code Lines 38

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 38
dl 0
loc 50
rs 8.968
c 0
b 0
f 0
cc 1
nop 0
1
"""
2
weitersager.argparser
3
~~~~~~~~~~~~~~~~~~~~~
4
5
Command line argument parsing
6
7
:Copyright: 2007-2020 Jochen Kupperschmidt
8
:License: MIT, see LICENSE for details.
9
"""
10
11
from argparse import ArgumentParser
12
13
from irc.bot import ServerSpec
14
15
16
DEFAULT_HTTP_IP_ADDRESS = '127.0.0.1'
17
DEFAULT_HTTP_PORT = 8080
18
DEFAULT_IRC_PORT = ServerSpec('').port
19
20
21
def parse_args():
22
    """Setup and apply the command line arguments parser."""
23
    parser = ArgumentParser()
24
25
    parser.add_argument(
26
        '--irc-nickname',
27
        dest='irc_nickname',
28
        default='Weitersager',
29
        help='the IRC nickname the bot should use',
30
        metavar='NICKNAME',
31
    )
32
33
    parser.add_argument(
34
        '--irc-realname',
35
        dest='irc_realname',
36
        default='Weitersager',
37
        help='the IRC realname the bot should use',
38
        metavar='REALNAME',
39
    )
40
41
    parser.add_argument(
42
        '--irc-server',
43
        dest='irc_server',
44
        type=parse_irc_server_arg,
45
        help='IRC server (host and, optionally, port) to connect to '
46
        + '[e.g. "irc.example.com" or "irc.example.com:6669"; '
47
        + f'default port: {DEFAULT_IRC_PORT:d}]',
48
        metavar='SERVER',
49
    )
50
51
    parser.add_argument(
52
        '--http-listen-ip-address',
53
        dest='http_ip_address',
54
        default=DEFAULT_HTTP_IP_ADDRESS,
55
        help='the IP address to listen on for HTTP requests '
56
        + f'[default: {DEFAULT_HTTP_IP_ADDRESS}]',
57
        metavar='IP_ADDRESS',
58
    )
59
60
    parser.add_argument(
61
        '--http-listen-port',
62
        dest='http_port',
63
        type=int,
64
        default=DEFAULT_HTTP_PORT,
65
        help='the port to listen on for HTTP requests '
66
        + f'[default: {DEFAULT_HTTP_PORT:d}]',
67
        metavar='PORT',
68
    )
69
70
    return parser.parse_args()
71
72
73
def parse_irc_server_arg(value):
74
    """Parse a hostname with optional port."""
75
    fragments = value.split(':', 1)
76
    if len(fragments) > 1:
77
        fragments[1] = int(fragments[1])
78
    return ServerSpec(*fragments)
79