Completed
Push — master ( 4feb28...7535fa )
by Makoto
55s
created

tumdlr.first_run()   B

Complexity

Conditions 2

Size

Total Lines 30

Duplication

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