summaryrefslogtreecommitdiff
path: root/bibtool/cli.py
blob: 3356d1658646f7137ff37f211e4efa6629215295 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# Copyright (C) 2018 Robin Krahl <robin.krahl@ireas.org>
# SPDX-License-Identifier: MIT

import os
import os.path
import shutil

import bibtexparser
import bibtool.extract
import click


TYPE_FILE = click.Path(exists=True, file_okay=True, dir_okay=False)
TYPE_DIR = click.Path(exists=True, file_okay=False, dir_okay=True)


@click.group()
def cli():
    pass


@cli.command('import')
@click.argument('filename', type=TYPE_FILE)
@click.option('--directory', type=TYPE_DIR, default=os.getcwd())
def _import(filename, directory):
    bibtex_data = bibtool.extract.get_bibtex_data(filename)

    if not bibtex_data.entries:
        raise Exception('Did not find any Bibtex entry.')
    if len(bibtex_data.entries) > 1:
        raise Exception('Found more than one Bibtex entries.')

    entry = bibtex_data.entries[0]
    click.echo('Found one Bibtex entry: ' + entry['ID'])
    if click.confirm('Do you want to edit the entry?'):
        edited_data = click.edit(bibtexparser.dumps(bibtex_data))
        if edited_data:
            bibtex_data = bibtexparser.loads(edited_data)
            if len(bibtex_data.entries) != 1:
                raise Exception('The edited data must contain exactly one Bibtex entry.')
            entry = bibtex_data.entries[0]

    click.confirm('Add {} to the repository?'.format(entry['ID']),
                  default=True, abort=True)

    bibfilename = os.path.join(directory, entry['ID'] + '.bib')
    outfileext = os.path.splitext(filename)[1]
    outfilename = os.path.join(directory, entry['ID'] + outfileext)
    
    if os.path.exists(bibfilename) or os.path.exists(outfilename):
        click.confirm('There is already a document with this ID in the '
                      'repository. Continue anyway?', abort=True)

    with open(bibfilename, 'w') as f:
        bibtexparser.dump(bibtex_data, f)
    shutil.copy(filename, outfilename)

    click.echo('Added {} to the repository.'.format(entry['ID']))