Completed
Push — 0.5.3 ( 1f0802...ed73f0 )
by Felipe A.
01:02
created

ExcludeAction.__init__()   A

Complexity

Conditions 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
#!/usr/bin/env python
2
# -*- coding: utf-8 -*-
3
4
import re
5
import sys
6
import os
7
import os.path
8
import argparse
9
import warnings
10
11
import flask
12
13
from . import app, compat
14
from .compat import PY_LEGACY, getdebug
15
from .transform.glob import translate
16
17
18
class PluginAction(argparse.Action):
19
    def __call__(self, parser, namespace, value, option_string=None):
20
        warned = '%s_warning' % self.dest
21
        if ',' in value and not getattr(namespace, warned, False):
22
            setattr(namespace, warned, True)
23
            warnings.warn(
24
                'Comma-separated --plugin value is deprecated, '
25
                'use multiple --plugin options instead.'
26
                )
27
        values = value.split(',')
28
        prev = getattr(namespace, self.dest, None)
29
        if isinstance(prev, list):
30
            values = prev + values
31
        setattr(namespace, self.dest, values)
32
33
34
class ArgParse(argparse.ArgumentParser):
35
    default_directory = os.path.abspath(compat.getcwd())
36
    default_host = os.getenv('BROWSEPY_HOST', '127.0.0.1')
37
    default_port = os.getenv('BROWSEPY_PORT', '8080')
38
    plugin_action_class = PluginAction
39
40
    description = 'extendable web file browser'
41
42
    def __init__(self, sep=os.sep):
43
        super(ArgParse, self).__init__(description=self.description)
44
45
        self.add_argument(
46
            'host', nargs='?',
47
            default=self.default_host,
48
            help='address to listen (default: %(default)s)')
49
        self.add_argument(
50
            'port', nargs='?', type=int,
51
            default=self.default_port,
52
            help='port to listen (default: %(default)s)')
53
        self.add_argument(
54
            '--directory', metavar='PATH', type=self._directory,
55
            default=self.default_directory,
56
            help='base serving directory (default: current path)')
57
        self.add_argument(
58
            '--initial', metavar='PATH', type=self._directory,
59
            help='initial directory (default: same as --directory)')
60
        self.add_argument(
61
            '--removable', metavar='PATH', type=self._directory,
62
            default=None,
63
            help='base directory for remove (default: none)')
64
        self.add_argument(
65
            '--upload', metavar='PATH', type=self._directory,
66
            default=None,
67
            help='base directory for upload (default: none)')
68
        self.add_argument(
69
            '--exclude', metavar='PATTERN',
70
            action='append',
71
            default=[],
72
            help='exclude paths by pattern (multiple allowed)')
73
        self.add_argument(
74
            '--plugin', metavar='MODULE',
75
            action=self.plugin_action_class,
76
            default=[],
77
            help='load plugin module (multiple allowed)')
78
        self.add_argument('--debug', action='store_true', help='debug mode')
79
80
    def _directory(self, arg):
81
        if not arg:
82
            return None
83
        if PY_LEGACY and hasattr(sys.stdin, 'encoding'):
84
            encoding = sys.stdin.encoding or sys.getdefaultencoding()
85
            arg = arg.decode(encoding)
86
        if os.path.isdir(arg):
87
            return os.path.abspath(arg)
88
        self.error('%s is not a valid directory' % arg)
89
90
91
def create_exclude_fnc(patterns, base):
92
    if patterns:
93
        regex = '|'.join(
94
            translate(pattern, base=base)
95
            for pattern in patterns
96
            )
97
        print(patterns, regex)
98
        return re.compile(regex).match
99
    return None
100
101
102
def main(argv=sys.argv[1:], app=app, parser=ArgParse, run_fnc=flask.Flask.run):
103
    plugin_manager = app.extensions['plugin_manager']
104
    args = plugin_manager.load_arguments(argv, parser())
105
    if args.debug:
106
        os.environ['DEBUG'] = 'true'
107
    app.config.update(
108
        directory_base=args.directory,
109
        directory_start=args.initial or args.directory,
110
        directory_remove=args.removable,
111
        directory_upload=args.upload,
112
        plugin_modules=args.plugin,
113
        exclude_fnc=create_exclude_fnc(args.exclude, args.directory)
114
        )
115
    plugin_manager.reload()
116
    run_fnc(
117
        app,
118
        host=args.host,
119
        port=args.port,
120
        debug=getdebug(),
121
        use_reloader=False,
122
        threaded=True
123
        )
124
125
126
if __name__ == '__main__':
127
    main()
128