Passed
Push — master ( e41ba7...8dafba )
by Konstantin
01:57
created

ocrd.cli.workspace.set_id()   A

Complexity

Conditions 1

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

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