summaryrefslogtreecommitdiff
path: root/lesana/command.py
blob: 6d2a7532f8b2674e69a0e49444833f9133e81f8e (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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
import argparse
import logging
import os
import subprocess
import sys

import ruamel.yaml

from . import Collection, Entry, TemplatingError

logger = logging.getLogger(__name__)

def _get_first_docstring_line(obj):
    try:
        return obj.__doc__.split('\n')[1].strip()
    except (AttributeError, IndexError):
        return None


class MainCommand:
    commands = ()

    def _main(self, args):
        self.parser.print_help()

    def main(self):
        desc = _get_first_docstring_line(self)
        self.parser = argparse.ArgumentParser(description=desc)
        self.parser.add_argument('--verbose', '-v',
                                 action='store_true',
                                 help="Display debug messages")
        self.parser.set_defaults(func=self._main)
        self.subparsers = self.parser.add_subparsers()
        for name, sub in self.commands:
            sub_help = _get_first_docstring_line(sub)
            s_parser = self.subparsers.add_parser(
                name,
                help=sub_help,
                description=sub.__doc__,
            )
            for arg in sub.arguments:
                s_parser.add_argument(*arg[0], **arg[1])
            s_parser.set_defaults(func=sub._main)
        self.args = self.parser.parse_args()

        if self.args.verbose:
            logging.getLogger('lesana').setLevel(logging.DEBUG)

        self.args.func(self.args)


class Command:
    def __init__(self, collection_class=Collection, entry_class=Entry):
        self.collection_class = collection_class
        self.entry_class = entry_class

    def _main(self, args):
        self.args = args
        self.main()

    def edit_file_in_external_editor(self, filepath):
        # First we try to use $EDITOR
        editor = os.environ.get('EDITOR')
        if editor:
            try:
                subprocess.call([editor, filepath])
            except FileNotFoundError as e:
                if editor in str(e):
                    logger.info(
                        'Could not open file {} with $EDITOR (currently {})'
                        .format(
                            filepath, editor
                        )
                    )
                else:
                    logger.warning("Could not open file {}".format(filepath))
                    return False
            else:
                return True
        # then we try to use sensible-editor (which should be available on
        # debian and derivatives)
        try:
            subprocess.call(['sensible-editor', filepath])
        except FileNotFoundError as e:
            if 'sensible-editor' in e.strerror:
                logger.debug(
                    "Could not open file {} with editor: sensible-editor"
                    .format(filepath)
                )
            else:
                logger.warning("Could not open file {}".format(filepath))
                return False
        else:
            return True
        # and finally we fallback to vi, because ed is the standard editor,
        # but that would be way too cruel, and vi is also in posix
        try:
            subprocess.call(['vi', filepath])
        except FileNotFoundError as e:
            if 'vi' in e.strerror:
                logger.warning(
                    "Could not open file {} with any known editor".format(
                        filepath
                    )
                )
                return False
            else:
                logger.warning("Could not open file {}".format(filepath))
                return False
        else:
            return True


class New(Command):
    """
    Create a new entry
    """
    arguments = [
        (
            ['--collection', '-c'],
            dict(help='The collection to work on (default .)'),
        ),
        (
            ['--no-git'],
            dict(
                help="Don't add the new entry to git",
                action="store_false",
                dest='git',
            ),
        ),
    ]

    def main(self):
        collection = self.collection_class(self.args.collection)
        new_entry = self.entry_class(collection)
        collection.save_entries([new_entry])
        filepath = os.path.join(collection.itemdir, new_entry.fname)
        if self.edit_file_in_external_editor(filepath):
            collection.update_cache([filepath])
            if self.args.git:
                collection.git_add_files([filepath])
        saved_entry = collection.entry_from_eid(new_entry.eid)
        print(saved_entry)


class Edit(Command):
    """
    Edit a lesana entry
    """
    arguments = [
        (
            ['--collection', '-c'],
            dict(help='The collection to work on (default .)'),
        ),
        (
            ['--no-git'],
            dict(
                help="Don't add the new entry to git",
                action="store_false",
                dest='git',
            ),
        ),
        (['eid'], dict(help='eid of an entry to edit',)),
    ]

    def main(self):
        collection = self.collection_class(self.args.collection)
        entries = collection.entries_from_short_eid(self.args.eid)
        if len(entries) > 1:
            return "{} is not an unique eid".format(self.args.eid)
        if not entries:
            return "Could not find an entry with eid starting with: {}".format(
                self.args.eid
            )
        entry = entries[0]
        # update the entry before editing it
        entry.auto()
        collection.save_entries([entry])
        # and then edit the updated file
        filepath = os.path.join(collection.itemdir, entry.fname)
        if self.edit_file_in_external_editor(filepath):
            collection.update_cache([filepath])
            if self.args.git:
                collection.git_add_files([filepath])
        saved_entry = collection.entry_from_eid(entry.eid)
        print(saved_entry)


class Show(Command):
    """
    Show a lesana entry
    """
    arguments = [
        (
            ['--collection', '-c'],
            dict(help='The collection to work on (default .)'),
        ),
        (
            ['--template', '-t'],
            dict(help='Use the specified template to display results.',),
        ),
        (['eid'], dict(help='eid of an entry to edit',)),
    ]

    def main(self):
        collection = self.collection_class(self.args.collection)
        entries = collection.entries_from_short_eid(self.args.eid)
        if len(entries) > 1:
            return "{} is not an unique eid".format(self.args.eid)
        if not entries:
            return "Could not find an entry with eid starting with: {}".format(
                self.args.eid
            )
        entry = entries[0]
        if self.args.template:
            try:
                print(entry.render(self.args.template))
            except TemplatingError as e:
                logger.error("{}".format(e))
                sys.exit(1)
        else:
            print(entry.yaml_data)


class Index(Command):
    """
    Index entries in a lesana collection
    """
    arguments = [
        (
            ['--collection', '-c'],
            dict(help='The collection to work on (default .)'),
        ),
        (
            ['--reset'],
            dict(
                action='store_true',
                help='Delete the existing index and reindex from scratch.',
            ),
        ),
        (
            ['files'],
            dict(
                help='List of files to index (default: everything)',
                default=None,
                nargs='*',
            ),
        ),
    ]

    def main(self):
        collection = self.collection_class(self.args.collection)
        if self.args.files:
            files = (os.path.basename(f) for f in self.args.files)
        else:
            files = None
        indexed = collection.update_cache(
            fnames=files,
            reset=self.args.reset
        )
        print("Found and indexed {} entries".format(indexed))


class Search(Command):
    """
    Search for entries
    """
    arguments = [
        (
            ['--collection', '-c'],
            dict(help='The collection to work on (default .)'),
        ),
        (
            ['--template', '-t'],
            dict(help='Template to use when displaying results',),
        ),
        (['--offset'], dict(type=int,)),
        (['--pagesize'], dict(type=int,)),
        (
            ['--all'],
            dict(action='store_true', help='Return all available results'),
        ),
        (
            ['--sort'],
            dict(action='append', help='Sort results by a sortable field'),
        ),
        (
            ['query'],
            {
                'help': 'Xapian query to search in the collection',
                'nargs': '*',
                'default': '*',
            },
        ),
    ]

    def main(self):
        # TODO: implement "searching" for everything
        if self.args.offset:
            logger.warning(
                "offset exposes an internal knob and MAY BE REMOVED "
                + "from a future release of lesana"  # noqa: W503
            )
        if self.args.pagesize:
            logger.warning(
                "pagesize exposes an internal knob and MAY BE REMOVED "
                + "from a future release of lesana"  # noqa: W503
            )
        offset = self.args.offset or 0
        pagesize = self.args.pagesize or 12
        collection = self.collection_class(self.args.collection)
        # sorted results require a less efficient full search rather
        # than being able to use the list of all documents.
        if self.args.query == ['*'] and not (
            self.args.sort
            or getattr(collection.settings, 'default_sort', False)
        ):
            results = collection.get_all_documents()
        else:
            collection.start_search(
                ' '.join(self.args.query),
                sort_by=self.args.sort
            )
            if self.args.all:
                results = collection.get_all_search_results()
            else:
                results = collection.get_search_results(offset, pagesize)
        if self.args.template:
            try:
                template = collection.get_template(self.args.template)
                print(template.render(entries=results))
            except TemplatingError as e:
                logger.error("{}".format(e))
                sys.exit(1)
        else:
            for entry in results:
                print("{entry}".format(entry=entry,))


class GetValues(Command):
    """
    List all values for one field, with entry counts.
    """
    arguments = [
        (
            ['--collection', '-c'],
            {
                'help': 'The collection to work on (default .)'
            },
        ),
        (
            ['--field', '-f'],
            {
                'help': 'Name of the field',
                'required': True,
            },
        ),
        (
            ['--template', '-t'],
            {
                'help': 'Template to use when displaying results',
            },
        ),
        (
            ['query'],
            {
                'help': 'Xapian query to limit the count search " \
                      + "in the collection',
                'nargs': '*',
                'default': '*'
            },
        ),
    ]

    def main(self):
        collection = self.collection_class(self.args.collection)
        counts = collection.get_field_values(
            self.args.field,
            ' '.join(self.args.query)
        )
        if self.args.template:
            try:
                template = collection.get_template(self.args.template)
                print(template.render(counts=counts))
            except TemplatingError as e:
                logger.error("{}".format(e))
                sys.exit(1)
        else:
            for v in counts:
                print("{value}: {count}".format(
                    value=v['value'],
                    count=v['frequency']
                ))


class Export(Command):
    """
    Export entries to a different collection
    """
    arguments = [
        (
            ['--collection', '-c'],
            dict(help='The collection to work on (default .)'),
        ),
        (
            ['--query', '-q'],
            dict(help='Xapian query to search in the collection',),
        ),
        (['destination'], dict(help='The collection to export entries to')),
        (['template'], dict(help='Template to convert entries',)),
    ]

    def main(self):
        collection = self.collection_class(self.args.collection)
        destination = self.collection_class(self.args.destination)
        if not self.args.query:
            results = collection.get_all_documents()
        else:
            collection.start_search(' '.join(self.args.query))
            results = collection.get_all_search_results()
        for entry in results:
            try:
                template = collection.get_template(self.args.template)
                rendered = template.render(entry=entry, **entry.data)
            except TemplatingError as e:
                logger.error("Error converting entry: {}".format(entry))
                logger.error("{}".format(e))
                sys.exit(1)
            try:
                data = ruamel.yaml.load(rendered, ruamel.yaml.RoundTripLoader)
            except ruamel.yaml.YAMLError as e:
                logger.error("Error loading exported entry: {}".format(entry))
                logger.error("exported data was\n{}".format(rendered))
                logger.error("{}".format(e))
                sys.exit(1)
            e = self.entry_class(destination, data=data)
            destination.save_entries([e])


class Init(Command):
    """
    Initialize a lesana collection
    """
    arguments = [
        (
            ['--collection', '-c'],
            dict(help='The directory to work on (default .)', default='.'),
        ),
        (
            ['--no-git'],
            dict(
                help='Skip setting up git in this directory',
                action="store_false",
                dest='git',
            ),
        ),
    ]

    def main(self):
        self.collection_class.init(
            self.args.collection,
            git_enabled=self.args.git,
            edit_file=self.edit_file_in_external_editor,
        )


class Remove(Command):
    """
    Remove an entry from a collection
    """
    arguments = [
        (
            ['--collection', '-c'],
            dict(help='The collection to work on (default .)',),
        ),
        (['entries'], dict(help='List of entries to remove', nargs='+',)),
    ]

    def main(self):
        collection = self.collection_class(self.args.collection)
        collection.remove_entries(eids=self.args.entries)


class Update(Command):
    """
    Update a field in multiple entries
    """
    arguments = [
        (
            ['--collection', '-c'],
            dict(help='The collection to work on (default .)',),
        ),
        (['--field', '-f'], dict(help='The field to change',)),
        (['--value', '-t'], dict(help='The value to set',)),
        (
            ['query'],
            dict(help='Xapian query to search in the collection', nargs='+'),
        ),
    ]

    def main(self):
        collection = self.collection_class(self.args.collection)
        collection.update_field(
            ' '.join(self.args.query),
            field=self.args.field,
            value=self.args.value,
        )