Passed
Pull Request — master (#559)
by Konstantin
02:34
created

ocrd.cli.resmgr   A

Complexity

Total Complexity 25

Size/Duplication

Total Lines 126
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 25
eloc 95
dl 0
loc 126
rs 10
c 0
b 0
f 0

5 Functions

Rating   Name   Duplication   Size   Complexity  
A resmgr_cli() 0 6 1
A list_installed() 0 10 2
A list_available() 0 9 2
A print_resources() 0 5 2
F download() 0 67 18
1
import sys
2
from os import getcwd
3
from os.path import join
4
from pathlib import Path
5
import requests
6
7
import click
8
9
from ocrd_utils import (
10
    initLogging,
11
    getLogger,
12
    VIRTUAL_ENV,
13
    RESOURCE_LOCATIONS,
14
    XDG_CACHE_HOME,
15
    XDG_CONFIG_HOME,
16
    XDG_DATA_HOME
17
)
18
from ocrd_validators import OcrdZipValidator
19
20
from ..resource_manager import OcrdResourceManager
21
from ..config import load_config_file
22
23
config = load_config_file()
24
25
def print_resources(executable, reslist):
26
    print('%s' % executable)
27
    for resdict in reslist:
28
        print('- %s (%s)\n  %s' % (resdict['name'], resdict['url'], resdict['description']))
29
    print()
30
31
@click.group("resmgr")
32
def resmgr_cli():
33
    """
34
    Managing processor resources
35
    """
36
    initLogging()
37
38
@resmgr_cli.command('list-available')
39
@click.option('-e', '--executable', help='Show only resources for executable EXEC', metavar='EXEC')
40
def list_available(executable=None):
41
    """
42
    List available resources
43
    """
44
    resmgr = OcrdResourceManager()
45
    for executable, reslist in resmgr.list_available(executable):
46
        print_resources(executable, reslist)
47
48
@resmgr_cli.command('list-installed')
49
@click.option('-e', '--executable', help='Show only resources for executable EXEC', metavar='EXEC')
50
def list_installed(executable=None):
51
    """
52
    List installed resources
53
    """
54
    resmgr = OcrdResourceManager()
55
    ret = []
56
    for executable, reslist in resmgr.list_installed(executable):
57
        print_resources(executable, reslist)
58
59
@resmgr_cli.command('download')
60
@click.option('-n', '--any-url', help='Allow downloading/copying unregistered resources', is_flag=True)
61
@click.option('-o', '--overwrite', help='Overwrite existing resources', is_flag=True)
62
@click.option('-l', '--location', help='Where to store resources', type=click.Choice(RESOURCE_LOCATIONS), default=config.resource_location, show_default=True)
63
@click.argument('executable', required=True)
64
@click.argument('url_or_name', required=True)
65
def download(any_url, overwrite, location, executable, url_or_name):
66
    """
67
    Download resource URL_OR_NAME for processor EXECUTABLE.
68
69
    URL_OR_NAME can either be the ``name`` or ``url`` of a registered resource.
70
71
    If URL_OR_NAME is '*' (asterisk), download all known resources for this processor
72
73
    If ``--any-url`` is given, also accepts URL or filenames of non-registered resources for ``URL_OR_NAME``.
74
    """
75
    log = getLogger('ocrd.cli.resmgr')
76
    resmgr = OcrdResourceManager()
77
    basedir = resmgr.get_resource_dir(location)
78
    is_url = url_or_name.startswith('https://') or url_or_name.startswith('http://')
79
    is_filename = Path(url_or_name).exists()
80
    find_kwargs = {'executable': executable}
81
    if url_or_name != '*':
82
        find_kwargs['url' if is_url else 'name'] = url_or_name
83
    reslist = resmgr.find_resources(**find_kwargs)
84
    if not reslist:
85
        log.info("No resources found in registry")
86
        if any_url and (is_url or is_filename):
87
            log.info("%s unregistered resource %s" % ("Downloading" if is_url else "Copying", url_or_name))
88
            if is_url:
89
                with requests.get(url_or_name, stream=True) as r:
90
                    content_length = int(r.headers.get('content-length'))
91
            else:
92
                url_or_name = str(Path(url_or_name).resolve())
93
                content_length = Path(url_or_name).stat().st_size
94
            with click.progressbar(length=content_length, label="Downloading" if is_url else "Copying") as bar:
95
                fpath = resmgr.download(
96
                    executable,
97
                    url_or_name,
98
                    overwrite=overwrite,
99
                    basedir=basedir,
100
                    progress_cb=lambda delta: bar.update(delta))
101
            log.info("%s resource '%s' (%s) not a known resource, creating stub in %s'" % (executable, fpath.name, url_or_name, resmgr.user_list))
102
            resmgr.add_to_user_database(executable, fpath, url_or_name)
103
            log.info("%s %s to %s" % ("Downloaded" if is_url else "Copied", url_or_name, fpath))
104
            log.info("Use in parameters as '%s'" % fpath.name)
105
        else:
106
            sys.exit(1)
107
    else:
108
        for _, resdict in reslist:
109
            if resdict['url'] == '???':
110
                log.info("Cannot download user resource %s" % (resdict['name'])),
111
                continue
112
            log.info("Downloading resource %s" % resdict)
113
            with click.progressbar(length=resdict['size']) as bar:
114
                fpath = resmgr.download(
115
                    executable,
116
                    resdict['url'],
117
                    name=resdict['name'],
118
                    resource_type=resdict['type'],
119
                    path_in_archive=resdict.get('path_in_archive', '.'),
120
                    overwrite=overwrite,
121
                    basedir=basedir,
122
                    progress_cb=lambda delta: bar.update(delta)
123
                )
124
            log.info("Downloaded %s to %s" % (resdict['url'], fpath))
125
            log.info("Use in parameters as '%s'" % resmgr.parameter_usage(resdict['name'], usage=resdict['parameter_usage']))
126
127