Completed
Push — master ( 9f2dd9...961eb6 )
by Makoto
53s
created

tumdlr.first_run()   A

Complexity

Conditions 2

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 2
dl 0
loc 17
rs 9.4285
1
import logging
2
import os
3
import pkgutil
4
5
from subprocess import call
6
7
import click
8
9
from tumdlr.config import load_config
10
11
12
CONTEXT_SETTINGS = dict(auto_envvar_prefix='TUMDLR', max_content_width=100)
13
14
15
class Context(object):
16
    """
17
    CLI Context
18
    """
19
    def __init__(self):
20
        self.cookiejar      = None
21
        self.config         = load_config('tumdlr')
22
        self.config_path    = None
23
        self.log            = None
24
        self.cache          = True
25
        self.database       = NotImplemented
26
27
28
class CommandLine(click.MultiCommand):
29
30
    def list_commands(self, ctx):
31
        """
32
        Get a list of all available commands
33
34
        Args:
35
            ctx: Context
36
37
        Returns:
38
            list
39
        """
40
        commands_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'commands')
41
        command_list = [name for __, name, ispkg in pkgutil.iter_modules([commands_path]) if not ispkg]
42
        command_list.sort()
43
        return command_list
44
45
    def get_command(self, ctx, name):
46
        """
47
        Fetch a command module
48
49
        Args:
50
            ctx:        Context
51
            name(str):  Command name
52
        """
53
        try:
54
            mod = pkgutil.importlib.import_module('tumdlr.commands.{name}'.format(name=name))
55
            return mod.cli
56
        except (ImportError, AttributeError):
57
            raise
58
59
60
pass_context = click.make_pass_decorator(Context, ensure=True)
61
62
63
# noinspection PyIncorrectDocstring
64
@click.command(cls=CommandLine, context_settings=CONTEXT_SETTINGS)
65
@click.option('-c', '--config', type=click.Path(dir_okay=False, resolve_path=True), envvar='TUMDLR_CONFIG_PATH',
66
              default='~/.config/tumdlr/tumdlr.conf',
67
              help='Path to the TumDLR configuration file (currently does nothing)')
68
@click.option('-q', '--quiet', help='Silence all output except for fatal errors', is_flag=True)
69
@click.option('-d', '--debug', help='Output information used for debugging', is_flag=True)
70
@pass_context
71
def cli(ctx, config, quiet, debug):
72
    """
73
    Tumblr Downloader CLI utility
74
    """
75
    # Logging setup
76
    if debug:
77
        log_level = logging.DEBUG
78
    else:
79
        log_level = logging.CRITICAL if quiet else logging.WARN
80
81
    ctx.log = logging.getLogger('tumdlr')
82
    ctx.log.setLevel(log_level)
83
84
    ch = logging.StreamHandler()
85
    ch.setLevel(log_level)
86
    ch.setFormatter(logging.Formatter('[%(levelname)s] %(name)s: %(message)s'))
87
    ctx.log.addHandler(ch)
88
89
    # First run?
90
    if not ctx.config['Development'].getboolean('AgreedToTerms'):
91
        first_run(ctx)
92
93
94
def first_run(ctx):
95
    """
96
    Run the setup and other tasks for first-time use
97
98
    Args:
99
        ctx(Context)
100
    """
101
    terms_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data', 'TERMS.rst')
102
103
    # Display the welcome message / terms and conditions agreement
104
    if os.name == 'nt':
105
        call(['more', terms_path])
106
    else:
107
        call(['less', terms_path])
108
109
    # Run the setup command
110
    ctx.invoke('setup')
111
112
113
if __name__ == '__main__':
114
    cli()
115