Passed
Push — master ( 135acb...fd797a )
by Konstantin
01:11 queued 12s
created

ocrd.cli.workspace.rename_group()   A

Complexity

Conditions 1

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 8
dl 0
loc 11
rs 10
c 0
b 0
f 0
cc 1
nop 3
1
import os
2
from os import getcwd
3
from os.path import relpath, exists, join, isabs, dirname, basename, abspath
4
from pathlib import Path
5
import sys
6
from glob import glob   # XXX pathlib.Path.glob does not support absolute globs
7
import re
8
9
import click
10
11
from ocrd import Resolver, Workspace, WorkspaceValidator, WorkspaceBackupManager
12
from ocrd_utils import getLogger, initLogging, pushd_popd, EXT_TO_MIME
13
from . import command_with_replaced_help
14
15
16
class WorkspaceCtx():
17
18
    def __init__(self, directory, mets_url, mets_basename, automatic_backup):
19
        self.log = getLogger('ocrd.cli.workspace')
20
        if mets_basename and mets_url:
21
            raise ValueError("Use either --mets or --mets-basename, not both")
22
        if mets_basename and not mets_url:
23
            self.log.warning(DeprecationWarning("--mets-basename is deprecated. Use --mets/--directory instead"))
24
        mets_basename = mets_basename if mets_basename else 'mets.xml'
25
        if directory and mets_url:
26
            directory = abspath(directory)
27
            if not abspath(mets_url).startswith(directory):
28
                raise ValueError("--mets has a directory part inconsistent with --directory")
29
        elif not directory and mets_url:
30
            if mets_url.startswith('http') or mets_url.startswith('https:'):
31
                raise ValueError("--mets is an http(s) URL but no --directory was given")
32
            directory = dirname(abspath(mets_url)) or getcwd()
33
        elif directory and not mets_url:
34
            directory = abspath(directory)
35
            mets_url = join(directory, mets_basename)
36
        else:
37
            directory = getcwd()
38
            mets_url = join(directory, mets_basename)
39
        self.directory = directory
40
        self.resolver = Resolver()
41
        self.mets_url = mets_url
42
        self.automatic_backup = automatic_backup
43
44
pass_workspace = click.make_pass_decorator(WorkspaceCtx)
45
46
# ----------------------------------------------------------------------
47
# ocrd workspace
48
# ----------------------------------------------------------------------
49
50
@click.group("workspace")
51
@click.option('-d', '--directory', envvar='WORKSPACE_DIR', type=click.Path(file_okay=False), metavar='WORKSPACE_DIR', help='Changes the workspace folder location [default: METS_URL directory or .]"')
52
@click.option('-M', '--mets-basename', default=None, help='METS file basename. Deprecated, use --mets/--directory')
53
@click.option('-m', '--mets', default=None, help='The path/URL of the METS file [default: WORKSPACE_DIR/mets.xml]', metavar="METS_URL")
54
@click.option('--backup', default=False, help="Backup mets.xml whenever it is saved.", is_flag=True)
55
@click.pass_context
56
def workspace_cli(ctx, directory, mets, mets_basename, backup):
57
    """
58
    Working with workspace
59
    """
60
    initLogging()
61
    ctx.obj = WorkspaceCtx(directory, mets_url=mets, mets_basename=mets_basename, automatic_backup=backup)
62
63
# ----------------------------------------------------------------------
64
# ocrd workspace validate
65
# ----------------------------------------------------------------------
66
67
@workspace_cli.command('validate', cls=command_with_replaced_help(
68
    (r' \[METS_URL\]', ''))) # XXX deprecated argument
69
@pass_workspace
70
@click.option('-a', '--download', is_flag=True, help="Download all files")
71
@click.option('-s', '--skip', help="Tests to skip", default=[], multiple=True, type=click.Choice(['imagefilename', 'dimension', 'mets_unique_identifier', 'mets_file_group_names', 'mets_files', 'pixel_density', 'page', 'page_xsd', 'mets_xsd', 'url']))
72
@click.option('--page-textequiv-consistency', '--page-strictness', help="How strict to check PAGE multi-level textequiv consistency", type=click.Choice(['strict', 'lax', 'fix', 'off']), default='strict')
73
@click.option('--page-coordinate-consistency', help="How fierce to check PAGE multi-level coordinate consistency", type=click.Choice(['poly', 'baseline', 'both', 'off']), default='poly')
74
@click.argument('mets_url', default=None, required=False)
75
def workspace_validate(ctx, mets_url, download, skip, page_textequiv_consistency, page_coordinate_consistency):
76
    """
77
    Validate a workspace
78
    
79
    METS_URL can be a URL, an absolute path or a path relative to $PWD.
80
    If not given, use --mets accordingly.
81
    
82
    Check that the METS and its referenced file contents
83
    abide by the OCR-D specifications.
84
    """
85
    LOG = getLogger('ocrd.cli.workspace.validate')
86
    if mets_url:
87
        LOG.warning(DeprecationWarning("Use 'ocrd workspace --mets METS init' instead of argument 'METS_URL' ('%s')" % mets_url))
88
    else:
89
        mets_url = ctx.mets_url
90
    report = WorkspaceValidator.validate(
91
        ctx.resolver,
92
        mets_url,
93
        src_dir=ctx.directory,
94
        skip=skip,
95
        download=download,
96
        page_strictness=page_textequiv_consistency,
97
        page_coordinate_consistency=page_coordinate_consistency
98
    )
99
    print(report.to_xml())
100
    if not report.is_valid:
101
        sys.exit(128)
102
103
# ----------------------------------------------------------------------
104
# ocrd workspace clone
105
# ----------------------------------------------------------------------
106
107
@workspace_cli.command('clone', cls=command_with_replaced_help(
108
    (r' \[WORKSPACE_DIR\]', ''))) # XXX deprecated argument
109
@click.option('-f', '--clobber-mets', help="Overwrite existing METS file", default=False, is_flag=True)
110
@click.option('-a', '--download', is_flag=True, help="Download all files and change location in METS file after cloning")
111
@click.argument('mets_url')
112
# XXX deprecated
113
@click.argument('workspace_dir', default=None, required=False)
114
@pass_workspace
115
def workspace_clone(ctx, clobber_mets, download, mets_url, workspace_dir):
116
    """
117
    Create a workspace from METS_URL and return the directory
118
119
    METS_URL can be a URL, an absolute path or a path relative to $PWD.
120
    If METS_URL is not provided, use --mets accordingly.
121
    METS_URL can also be an OAI-PMH GetRecord URL wrapping a METS file.
122
    """
123
    LOG = getLogger('ocrd.cli.workspace.clone')
124
    if workspace_dir:
125
        LOG.warning(DeprecationWarning("Use 'ocrd workspace --directory DIR clone' instead of argument 'WORKSPACE_DIR' ('%s')" % workspace_dir))
126
        ctx.directory = workspace_dir
127
128
    workspace = ctx.resolver.workspace_from_url(
129
        mets_url,
130
        dst_dir=os.path.abspath(ctx.directory),
131
        mets_basename=basename(ctx.mets_url),
132
        clobber_mets=clobber_mets,
133
        download=download,
134
    )
135
    workspace.save_mets()
136
    print(workspace.directory)
137
138
# ----------------------------------------------------------------------
139
# ocrd workspace init
140
# ----------------------------------------------------------------------
141
142
@workspace_cli.command('init', cls=command_with_replaced_help(
143
    (r' \[DIRECTORY\]', ''))) # XXX deprecated argument
144
@click.option('-f', '--clobber-mets', help="Clobber mets.xml if it exists", is_flag=True, default=False)
145
# XXX deprecated
146
@click.argument('directory', default=None, required=False)
147
@pass_workspace
148
def workspace_init(ctx, clobber_mets, directory):
149
    """
150
    Create a workspace with an empty METS file in --directory.
151
152
    """
153
    LOG = getLogger('ocrd.cli.workspace.init')
154
    if directory:
155
        LOG.warning(DeprecationWarning("Use 'ocrd workspace --directory DIR init' instead of argument 'DIRECTORY' ('%s')" % directory))
156
        ctx.directory = directory
157
    workspace = ctx.resolver.workspace_from_nothing(
158
        directory=os.path.abspath(ctx.directory),
159
        mets_basename=basename(ctx.mets_url),
160
        clobber_mets=clobber_mets
161
    )
162
    workspace.save_mets()
163
    print(workspace.directory)
164
165
# ----------------------------------------------------------------------
166
# ocrd workspace add
167
# ----------------------------------------------------------------------
168
169
@workspace_cli.command('add')
170
@click.option('-G', '--file-grp', help="fileGrp USE", required=True)
171
@click.option('-i', '--file-id', help="ID for the file", required=True)
172
@click.option('-m', '--mimetype', help="Media type of the file", required=True)
173
@click.option('-g', '--page-id', help="ID of the physical page")
174
@click.option('-C', '--check-file-exists', help="Whether to ensure FNAME exists", is_flag=True, default=False)
175
@click.option('--ignore', help="Do not check whether file exists.", default=False, is_flag=True)
176
@click.option('--force', help="If file with ID already exists, replace it. No effect if --ignore is set.", default=False, is_flag=True)
177
@click.argument('fname', required=True)
178
@pass_workspace
179
def workspace_add_file(ctx, file_grp, file_id, mimetype, page_id, ignore, check_file_exists, force, fname):
180
    """
181
    Add a file or http(s) URL FNAME to METS in a workspace.
182
    If FNAME is not an http(s) URL and is not a workspace-local existing file, try to copy to workspace.
183
    """
184
    workspace = Workspace(ctx.resolver, directory=ctx.directory, mets_basename=basename(ctx.mets_url), automatic_backup=ctx.automatic_backup)
185
186
    kwargs = {'fileGrp': file_grp, 'ID': file_id, 'mimetype': mimetype, 'pageId': page_id, 'force': force, 'ignore': ignore}
187
    log = getLogger('ocrd.cli.workspace.add')
188
    log.debug("Adding '%s' (%s)", fname, kwargs)
189
    if not (fname.startswith('http://') or fname.startswith('https://')):
190
        if not fname.startswith(ctx.directory):
191
            if not isabs(fname) and exists(join(ctx.directory, fname)):
192
                fname = join(ctx.directory, fname)
193
            else:
194
                log.debug("File '%s' is not in workspace, copying", fname)
195
                try:
196
                    fname = ctx.resolver.download_to_directory(ctx.directory, fname, subdir=file_grp)
197
                except FileNotFoundError:
198
                    if check_file_exists:
199
                        log.error("File '%s' does not exist, halt execution!" % fname)
200
                        sys.exit(1)
201
        if check_file_exists and not exists(fname):
202
            log.error("File '%s' does not exist, halt execution!" % fname)
203
            sys.exit(1)
204
        if fname.startswith(ctx.directory):
205
            fname = relpath(fname, ctx.directory)
206
        kwargs['local_filename'] = fname
207
208
    kwargs['url'] = fname
209
    workspace.mets.add_file(**kwargs)
210
    workspace.save_mets()
211
212
# ----------------------------------------------------------------------
213
# ocrd workspace add-bulk
214
# ----------------------------------------------------------------------
215
216
# pylint: disable=broad-except
217
@workspace_cli.command('bulk-add')
218
@click.option('-r', '--regex', help="Regular expression matching the FILE_GLOB filesystem paths to define named captures usable in the other parameters", required=True)
219
@click.option('-m', '--mimetype', help="Media type of the file. If not provided, guess from filename", required=False)
220
@click.option('-g', '--page-id', help="physical page ID of the file", required=False)
221
@click.option('-i', '--file-id', help="ID of the file", required=True)
222
@click.option('-u', '--url', help="local filesystem path in the workspace directory (copied from source file if different)", required=True)
223
@click.option('-G', '--file-grp', help="File group USE of the file", required=True)
224
@click.option('-n', '--dry-run', help="Don't actually do anything to the METS or filesystem, just preview", default=False, is_flag=True)
225
@click.option('-I', '--ignore', help="Disable checking for existing file entries (faster)", default=False, is_flag=True)
226
@click.option('-f', '--force', help="Replace existing file entries with the same ID (no effect when --ignore is set, too)", default=False, is_flag=True)
227
@click.option('-s', '--skip', help="Skip files not matching --regex (instead of failing)", default=False, is_flag=True)
228
@click.argument('file_glob', nargs=-1, required=True)
229
@pass_workspace
230
def workspace_cli_bulk_add(ctx, regex, mimetype, page_id, file_id, url, file_grp, dry_run, file_glob, ignore, force, skip):
231
    r"""
232
    Add files in bulk to an OCR-D workspace.
233
234
    FILE_GLOB can either be a shell glob expression or a list of files.
235
236
    --regex is applied to the absolute path of every file in FILE_GLOB and can
237
    define named groups that can be used in --page-id, --file-id, --mimetype, --url and
238
    --file-grp by referencing the named group 'grp' in the regex as '{{ grp }}'.
239
240
    \b
241
    Example:
242
        ocrd workspace bulk-add \\
243
                --regex '^.*/(?P<fileGrp>[^/]+)/page_(?P<pageid>.*)\.(?P<ext>[^\.]*)$' \\
244
                --file-id 'FILE_{{ fileGrp }}_{{ pageid }}' \\
245
                --page-id 'PHYS_{{ pageid }}' \\
246
                --file-grp "{{ fileGrp }}" \\
247
                --url '{{ fileGrp }}/FILE_{{ pageid }}.{{ ext }}' \\
248
                path/to/files/*/*.*
249
250
    """
251
    log = getLogger('ocrd.cli.workspace.bulk-add') # pylint: disable=redefined-outer-name
252
    workspace = Workspace(ctx.resolver, directory=ctx.directory, mets_basename=basename(ctx.mets_url), automatic_backup=ctx.automatic_backup)
253
254
    try:
255
        pat = re.compile(regex)
256
    except Exception as e:
257
        log.error("Invalid regex: %s" % e)
258
        sys.exit(1)
259
260
    file_paths = []
261
    for fglob in file_glob:
262
        file_paths += [Path(x).resolve() for x in glob(fglob)]
263
264
    for i, file_path in enumerate(file_paths):
265
        log.info("[%4d/%d] %s" % (i, len(file_paths), file_path))
266
267
        # match regex
268
        m = pat.match(str(file_path))
269
        if not m:
270
            if skip:
271
                continue
272
            log.error("File not matched by regex: '%s'" % file_path)
273
            sys.exit(1)
274
        group_dict = m.groupdict()
275
276
        # set up file info
277
        file_dict = {'url': url, 'mimetype': mimetype, 'ID': file_id, 'pageId': page_id, 'fileGrp': file_grp}
278
279
        # guess mime type
280
        if not file_dict['mimetype']:
281
            try:
282
                file_dict['mimetype'] = EXT_TO_MIME[file_path.suffix]
283
            except KeyError:
284
                log.error("Cannot guess mimetype from extension '%s' for '%s'. Set --mimetype explicitly" % (file_path.suffix, file_path))
285
286
        # expand templates
287
        for param_name in file_dict:
288
            for group_name in group_dict:
289
                file_dict[param_name] = file_dict[param_name].replace('{{ %s }}' % group_name, group_dict[group_name])
290
291
        # copy files
292
        if file_dict['url']:
293
            urlpath = Path(workspace.directory, file_dict['url'])
294
            if not urlpath.exists():
295
                log.info("cp '%s' '%s'", file_path, urlpath)
296
                if not dry_run:
297
                    if not urlpath.parent.is_dir():
298
                        urlpath.parent.mkdir()
299
                    urlpath.write_bytes(file_path.read_bytes())
300
301
        # Add to workspace (or not)
302
        fileGrp = file_dict.pop('fileGrp')
303
        if dry_run:
304
            log.info('workspace.add_file(%s)' % file_dict)
305
        else:
306
            workspace.add_file(fileGrp, ignore=ignore, force=force, **file_dict)
307
308
    # save changes to disk
309
    workspace.save_mets()
310
311
312
# ----------------------------------------------------------------------
313
# ocrd workspace find
314
# ----------------------------------------------------------------------
315
316
@workspace_cli.command('find')
317
@click.option('-G', '--file-grp', help="fileGrp USE", metavar='FILTER')
318
@click.option('-m', '--mimetype', help="Media type to look for", metavar='FILTER')
319
@click.option('-g', '--page-id', help="Page ID", metavar='FILTER')
320
@click.option('-i', '--file-id', help="ID", metavar='FILTER')
321
@click.option('-k', '--output-field', help="Output field. Repeat for multiple fields, will be joined with tab",
322
        default=['url'],
323
        multiple=True,
324
        type=click.Choice([
325
            'url',
326
            'mimetype',
327
            'pageId',
328
            'ID',
329
            'fileGrp',
330
            'basename',
331
            'basename_without_extension',
332
            'local_filename',
333
        ]))
334
@click.option('--download', is_flag=True, help="Download found files to workspace and change location in METS file ")
335
@pass_workspace
336
def workspace_find(ctx, file_grp, mimetype, page_id, file_id, output_field, download):
337
    """
338
    Find files.
339
340
    (If any ``FILTER`` starts with ``//``, then its remainder
341
     will be interpreted as a regular expression.)
342
    """
343
    modified_mets = False
344
    ret = list()
345
    workspace = Workspace(ctx.resolver, directory=ctx.directory, mets_basename=basename(ctx.mets_url))
346
    for f in workspace.mets.find_files(
347
            ID=file_id,
348
            fileGrp=file_grp,
349
            mimetype=mimetype,
350
            pageId=page_id,
351
        ):
352
        if download and not f.local_filename:
353
            workspace.download_file(f)
354
            modified_mets = True
355
        ret.append([f.ID if field == 'pageId' else getattr(f, field) or ''
356
                    for field in output_field])
357
    if modified_mets:
358
        workspace.save_mets()
359
    if 'pageId' in output_field:
360
        idx = output_field.index('pageId')
361
        fileIds = list(map(lambda fields: fields[idx], ret))
0 ignored issues
show
introduced by
The variable idx does not seem to be defined in case 'pageId' in output_field on line 359 is False. Are you sure this can never be the case?
Loading history...
362
        pages = workspace.mets.get_physical_pages(for_fileIds=fileIds)
363
        for fields, page in zip(ret, pages):
364
            fields[idx] = page or ''
365
    for fields in ret:
366
        print('\t'.join(fields))
367
368
# ----------------------------------------------------------------------
369
# ocrd workspace remove
370
# ----------------------------------------------------------------------
371
372
@workspace_cli.command('remove')
373
@click.option('-k', '--keep-file', help="Do not delete file from file system", default=False, is_flag=True)
374
@click.option('-f', '--force', help="Continue even if mets:file or file on file system does not exist", default=False, is_flag=True)
375
@click.argument('ID', nargs=-1)
376
@pass_workspace
377
def workspace_remove_file(ctx, id, force, keep_file):  # pylint: disable=redefined-builtin
378
    """
379
    Delete files (given by their ID attribute ``ID``).
380
    
381
    (If any ``ID`` starts with ``//``, then its remainder
382
     will be interpreted as a regular expression.)
383
    """
384
    workspace = Workspace(ctx.resolver, directory=ctx.directory, mets_basename=basename(ctx.mets_url), automatic_backup=ctx.automatic_backup)
385
    for i in id:
386
        workspace.remove_file(i, force=force, keep_file=keep_file)
387
    workspace.save_mets()
388
389
390
# ----------------------------------------------------------------------
391
# ocrd workspace rename-group
392
# ----------------------------------------------------------------------
393
394
@workspace_cli.command('rename-group')
395
@click.argument('OLD', nargs=1)
396
@click.argument('NEW', nargs=1)
397
@pass_workspace
398
def rename_group(ctx, old, new):
399
    """
400
    Rename fileGrp (USE attribute ``NEW`` to ``OLD``).
401
    """
402
    workspace = Workspace(ctx.resolver, directory=ctx.directory, mets_basename=basename(ctx.mets_url))
403
    workspace.rename_file_group(old, new)
404
    workspace.save_mets()
405
406
# ----------------------------------------------------------------------
407
# ocrd workspace remove-group
408
# ----------------------------------------------------------------------
409
410
@workspace_cli.command('remove-group')
411
@click.option('-r', '--recursive', help="Delete any files in the group before the group itself", default=False, is_flag=True)
412
@click.option('-f', '--force', help="Continue removing even if group or containing files not found in METS", default=False, is_flag=True)
413
@click.option('-k', '--keep-files', help="Do not delete files from file system", default=False, is_flag=True)
414
@click.argument('GROUP', nargs=-1)
415
@pass_workspace
416
def remove_group(ctx, group, recursive, force, keep_files):
417
    """
418
    Delete fileGrps (given by their USE attribute ``GROUP``).
419
    
420
    (If any ``GROUP`` starts with ``//``, then its remainder
421
     will be interpreted as a regular expression.)
422
    """
423
    workspace = Workspace(ctx.resolver, directory=ctx.directory, mets_basename=basename(ctx.mets_url))
424
    for g in group:
425
        workspace.remove_file_group(g, recursive=recursive, force=force, keep_files=keep_files)
426
    workspace.save_mets()
427
428
# ----------------------------------------------------------------------
429
# ocrd workspace prune-files
430
# ----------------------------------------------------------------------
431
432
@workspace_cli.command('prune-files')
433
@click.option('-G', '--file-grp', help="fileGrp USE", metavar='FILTER')
434
@click.option('-m', '--mimetype', help="Media type to look for", metavar='FILTER')
435
@click.option('-g', '--page-id', help="Page ID", metavar='FILTER')
436
@click.option('-i', '--file-id', help="ID", metavar='FILTER')
437
@pass_workspace
438
def prune_files(ctx, file_grp, mimetype, page_id, file_id):
439
    """
440
    Removes mets:files that point to non-existing local files
441
442
    (If any ``FILTER`` starts with ``//``, then its remainder
443
     will be interpreted as a regular expression.)
444
    """
445
    workspace = Workspace(ctx.resolver, directory=ctx.directory, mets_basename=basename(ctx.mets_url), automatic_backup=ctx.automatic_backup)
446
    with pushd_popd(workspace.directory):
447
        for f in workspace.mets.find_files(
448
            ID=file_id,
449
            fileGrp=file_grp,
450
            mimetype=mimetype,
451
            pageId=page_id,
452
        ):
453
            try:
454
                if not f.local_filename or not exists(f.local_filename):
455
                    workspace.mets.remove_file(f.ID)
456
            except Exception as e:
457
                ctx.log.exception("Error removing %f: %s", f, e)
458
                raise(e)
459
        workspace.save_mets()
460
461
# ----------------------------------------------------------------------
462
# ocrd workspace list-group
463
# ----------------------------------------------------------------------
464
465
@workspace_cli.command('list-group')
466
@pass_workspace
467
def list_groups(ctx):
468
    """
469
    List fileGrp USE attributes
470
    """
471
    workspace = Workspace(ctx.resolver, directory=ctx.directory, mets_basename=basename(ctx.mets_url))
472
    print("\n".join(workspace.mets.file_groups))
473
474
# ----------------------------------------------------------------------
475
# ocrd workspace list-pages
476
# ----------------------------------------------------------------------
477
478
@workspace_cli.command('list-page')
479
@pass_workspace
480
def list_pages(ctx):
481
    """
482
    List physical page IDs
483
    """
484
    workspace = Workspace(ctx.resolver, directory=ctx.directory, mets_basename=basename(ctx.mets_url))
485
    print("\n".join(workspace.mets.physical_pages))
486
487
# ----------------------------------------------------------------------
488
# ocrd workspace get-id
489
# ----------------------------------------------------------------------
490
491
@workspace_cli.command('get-id')
492
@pass_workspace
493
def get_id(ctx):
494
    """
495
    Get METS id if any
496
    """
497
    workspace = Workspace(ctx.resolver, directory=ctx.directory, mets_basename=basename(ctx.mets_url))
498
    ID = workspace.mets.unique_identifier
499
    if ID:
500
        print(ID)
501
502
# ----------------------------------------------------------------------
503
# ocrd workspace set-id
504
# ----------------------------------------------------------------------
505
506
@workspace_cli.command('set-id')
507
@click.argument('ID')
508
@pass_workspace
509
def set_id(ctx, id):   # pylint: disable=redefined-builtin
510
    """
511
    Set METS ID.
512
513
    If one of the supported identifier mechanisms is used, will set this identifier.
514
515
    Otherwise will create a new <mods:identifier type="purl">{{ ID }}</mods:identifier>.
516
    """
517
    workspace = Workspace(ctx.resolver, directory=ctx.directory, mets_basename=basename(ctx.mets_url), automatic_backup=ctx.automatic_backup)
518
    workspace.mets.unique_identifier = id
519
    workspace.save_mets()
520
521
# ----------------------------------------------------------------------
522
# ocrd workspace backup
523
# ----------------------------------------------------------------------
524
525
@workspace_cli.group('backup')
526
@click.pass_context
527
def workspace_backup_cli(ctx): # pylint: disable=unused-argument
528
    """
529
    Backing and restoring workspaces - dev edition
530
    """
531
532
@workspace_backup_cli.command('add')
533
@pass_workspace
534
def workspace_backup_add(ctx):
535
    """
536
    Create a new backup
537
    """
538
    backup_manager = WorkspaceBackupManager(Workspace(ctx.resolver, directory=ctx.directory, mets_basename=basename(ctx.mets_url), automatic_backup=ctx.automatic_backup))
539
    backup_manager.add()
540
541
@workspace_backup_cli.command('list')
542
@pass_workspace
543
def workspace_backup_list(ctx):
544
    """
545
    List backups
546
    """
547
    backup_manager = WorkspaceBackupManager(Workspace(ctx.resolver, directory=ctx.directory, mets_basename=basename(ctx.mets_url), automatic_backup=ctx.automatic_backup))
548
    for b in backup_manager.list():
549
        print(b)
550
551
@workspace_backup_cli.command('restore')
552
@click.option('-f', '--choose-first', help="Restore first matching version if more than one", is_flag=True)
553
@click.argument('bak') #, type=click.Path(dir_okay=False, readable=True, resolve_path=True))
554
@pass_workspace
555
def workspace_backup_restore(ctx, choose_first, bak):
556
    """
557
    Restore backup BAK
558
    """
559
    backup_manager = WorkspaceBackupManager(Workspace(ctx.resolver, directory=ctx.directory, mets_basename=basename(ctx.mets_url), automatic_backup=ctx.automatic_backup))
560
    backup_manager.restore(bak, choose_first)
561
562
@workspace_backup_cli.command('undo')
563
@pass_workspace
564
def workspace_backup_undo(ctx):
565
    """
566
    Restore the last backup
567
    """
568
    backup_manager = WorkspaceBackupManager(Workspace(ctx.resolver, directory=ctx.directory, mets_basename=basename(ctx.mets_url), automatic_backup=ctx.automatic_backup))
569
    backup_manager.undo()
570