Passed
Pull Request — develop (#301)
by
unknown
01:43
created

_list()   A

Complexity

Conditions 1

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
c 0
b 0
f 0
dl 0
loc 7
rs 9.4285
ccs 3
cts 3
cp 1
crap 1
1
#!/usr/bin/env python
2
3 1
"""Command-line interface for Doorstop."""
4
5 1
import os
6 1
import sys
7 1
import argparse
8
9 1
from doorstop import common, settings
10 1
from doorstop.cli import utilities, commands
11 1
from doorstop.core import publisher, vcs, document
12
13 1
log = common.logger(__name__)
14
15
16 1
def main(args=None):  # pylint: disable=R0915
17
    """Process command-line arguments and run the program."""
18 1
    from doorstop import CLI, VERSION, DESCRIPTION
19
20
    # Shared options
21 1
    project = argparse.ArgumentParser(add_help=False)
22 1
    try:
23 1
        root = vcs.find_root(os.getcwd())
24 1
    except common.DoorstopError:
25 1
        root = None
26 1
    project.add_argument('-j', '--project', metavar='PATH',
27
                         help="path to the root of the project",
28
                         default=root)
29 1
    project.add_argument('--no-cache', action='store_true',
30
                         help=argparse.SUPPRESS)
31 1
    project.add_argument('-b', '--beta', nargs='*',
32 1
                         help="""enable beta features. Refer to documentation on available beta features. """)
33
    server = argparse.ArgumentParser(add_help=False)
34
    server.add_argument('--server', metavar='HOST',
35 1
                        help="IP address or hostname for a running server",
36
                        default=settings.SERVER_HOST)
37
    server.add_argument('--port', metavar='NUMBER', type=int,
38 1
                        help="use a custom port for the server",
39
                        default=settings.SERVER_PORT)
40 1
    server.add_argument('-f', '--force', action='store_true',
41 1
                        help="perform the action without the server")
42 1
    debug = argparse.ArgumentParser(add_help=False)
43 1
    debug.add_argument('-V', '--version', action='version', version=VERSION)
44
    group = debug.add_mutually_exclusive_group()
45 1
    group.add_argument('-v', '--verbose', action='count', default=0,
46
                       help="enable verbose logging")
47 1
    group.add_argument('-q', '--quiet', action='store_const', const=-1,
48
                       dest='verbose', help="only display errors and prompts")
49
    shared = {'formatter_class': common.HelpFormatter,
50
              'parents': [project, server, debug]}
51 1
52
    # Build main parser
53 1
    parser = argparse.ArgumentParser(prog=CLI, description=DESCRIPTION,
54
                                     **shared)
55 1
    parser.add_argument('-F', '--no-reformat', action='store_true',
56
                        help="do not reformat item files during validation")
57 1
    parser.add_argument('-r', '--reorder', action='store_true',
58
                        help="reorder document levels during validation")
59 1
    parser.add_argument('-L', '--no-level-check', action='store_true',
60
                        help="do not validate document levels")
61 1
    parser.add_argument('-R', '--no-ref-check', action='store_true',
62
                        help="do not validate external file references")
63 1
    parser.add_argument('-C', '--no-child-check', action='store_true',
64
                        help="do not validate child (reverse) links")
65 1
    parser.add_argument('-Z', '--strict-child-check', action='store_true',
66
                        help="require child (reverse) links from every document")
67 1
    parser.add_argument('-S', '--no-suspect-check', action='store_true',
68
                        help="do not check for suspect links")
69 1
    parser.add_argument('-W', '--no-review-check', action='store_true',
70
                        help="do not check item review status")
71 1
    parser.add_argument('-s', '--skip', metavar='PREFIX', action='append',
72
                        help="skip a document during validation")
73 1
    parser.add_argument('-w', '--warn-all', action='store_true',
74
                        help="display all info-level issues as warnings")
75
    parser.add_argument('-e', '--error-all', action='store_true',
76
                        help="display all warning-level issues as errors")
77 1
78 1
    # Build sub-parsers
79 1
    subs = parser.add_subparsers(help="", dest='command', metavar="<command>")
80 1
    _create(subs, shared)
81 1
    _list(subs, shared)
82 1
    _delete(subs, shared)
83 1
    _add(subs, shared)
84 1
    _remove(subs, shared)
85 1
    _edit(subs, shared)
86 1
    _reorder(subs, shared)
87 1
    _link(subs, shared)
88 1
    _unlink(subs, shared)
89 1
    _clear(subs, shared)
90 1
    _review(subs, shared)
91
    _import(subs, shared)
92
    _export(subs, shared)
93 1
    _publish(subs, shared)
94
95
    # Parse arguments
96 1
    args = parser.parse_args(args=args)
97
98
    # Configure logging
99 1
    utilities.configure_logging(args.verbose)
100
101
    # Configure settings
102 1
    utilities.configure_settings(args)
103 1
104 1
    # Run the program
105 1
    function = commands.get(args.command)
106 1
    try:
107 1
        success = function(args, os.getcwd(), parser.error)
108 1
    except common.DoorstopFileError as exc:
109 1
        log.error(exc)
110 1
        success = False
111 1
    except KeyboardInterrupt:
112 1
        log.debug("command cancelled")
113
        success = False
114 1
    if success:
115 1
        log.debug("command succeeded")
116
    else:
117
        log.debug("command failed")
118 1
        sys.exit(1)
119
120 1
121 1
def _create(subs, shared):
122
    """Configure the `doorstop create` subparser."""
123 1
    info = "create a new document directory"
124 1
    sub = subs.add_parser('create', description=info.capitalize() + '.',
125 1
                          help=info, **shared)
126 1
    sub.add_argument('prefix', help="document prefix for new item UIDs")
127
    sub.add_argument('path', help="path to a directory for item files")
128
    sub.add_argument('-p', '--parent', help="prefix of parent document")
129
    sub.add_argument('-d', '--digits', help="number of digits in item UIDs",
130 1
                     default=document.Document.DEFAULT_DIGITS)
131
132 1
133 1
def _list(subs, shared):
134
    """Configure the `doorstop list` subparser."""
135 1
    info = "list the document directories"
136
    sub = subs.add_parser('list', description=info.capitalize() + '.',
137
                          help=info, **shared)
138 1
    sub.add_argument('prefix', nargs='?', default=None,
139
                     help="document prefix for items to list, if not specified list the documents")
140 1
141 1
142
def _delete(subs, shared):
143 1
    """Configure the `doorstop delete` subparser."""
144
    info = "delete a document directory"
145 1
    sub = subs.add_parser('delete', description=info.capitalize() + '.',
146 1
                          help=info, **shared)
147
    sub.add_argument('prefix', help="prefix of document to delete")
148
149
150 1
def _add(subs, shared):
151
    """Configure the `doorstop add` subparser."""
152 1
    info = "create an item file in a document directory"
153 1
    sub = subs.add_parser('add', description=info.capitalize() + '.',
154
                          help=info, **shared)
155 1
    sub.add_argument('prefix',
156
                     help="document prefix for the new item")
157
    sub.add_argument('-l', '--level', help="desired item level (e.g. 1.2.3)")
158 1
    sub.add_argument('-c', '--count', default=1, type=utilities.positive_int,
159
                     help="number of items to create")
160 1
161 1
162
def _remove(subs, shared):
163 1
    """Configure the `doorstop remove` subparser."""
164
    info = "remove an item file from a document directory"
165 1
    sub = subs.add_parser('remove', description=info.capitalize() + '.',
166 1
                          help=info, **shared)
167
    sub.add_argument('uid', help="item UID to remove from its document")
168 1
169
170 1 View Code Duplication
def _edit(subs, shared):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
171 1
    """Configure the `doorstop edit` subparser."""
172
    info = "open an existing item or document for editing"
173 1
    sub = subs.add_parser('edit', description=info.capitalize() + '.',
174
                          help=info, **shared)
175 1
    sub.add_argument('label',
176
                     help="item UID or document prefix to open for editing")
177 1
    group = sub.add_mutually_exclusive_group()
178
    group.add_argument('-i', '--item', action='store_true',
179 1
                       help="indicates the 'label' is an item UID")
180 1
    group.add_argument('-d', '--document', action='store_true',
181
                       help="indicates the 'label' is a document prefix")
182
    group = sub.add_mutually_exclusive_group()
183
    group.add_argument('-y', '--yaml', action='store_true',
184
                       help="edit document as exported YAML (default)")
185 1
    group.add_argument('-c', '--csv', action='store_true',
186
                       help="edit document as exported CSV")
187 1
    group.add_argument('-t', '--tsv', action='store_true',
188 1
                       help="edit document as exported TSV")
189
    group.add_argument('-x', '--xlsx', action='store_true',
190 1
                       help="edit document as exported XLSX")
191 1
    required = sub.add_argument_group('required arguments')
192 1
    required.add_argument('-T', '--tool', metavar='PROGRAM',
193
                          help="text editor to open the document item",
194 1
                          required=True)
195
196 1
197
def _reorder(subs, shared):
198
    """Configure the `doorstop reorder` subparser."""
199
    info = "organize the outline structure of a document"
200 1
    sub = subs.add_parser('reorder', description=info.capitalize() + '.',
201
                          help=info, **shared)
202 1
    sub.add_argument('prefix', help="prefix of document to reorder")
203 1
    group = sub.add_mutually_exclusive_group()
204
    group.add_argument('-a', '--auto', action='store_true',
205 1
                       help="only perform automatic item reordering")
206
    group.add_argument('-m', '--manual', action='store_true',
207 1
                       help="do not automatically reorder the items")
208
    sub.add_argument('-T', '--tool', metavar='PROGRAM',
209
                     help="text editor to open the document index")
210
211 1
212
def _link(subs, shared):
213 1
    """Configure the `doorstop link` subparser."""
214 1
    info = "add a new link between two items"
215
    sub = subs.add_parser('link', description=info.capitalize() + '.',
216 1
                          help=info, **shared)
217
    sub.add_argument('child',
218 1
                     help="child item UID to link to the parent")
219
    sub.add_argument('parent',
220
                     help="parent item UID to link from the child")
221
222 1
223
def _unlink(subs, shared):
224 1
    """Configure the `doorstop unlink` subparser."""
225 1
    info = "remove a link between two items"
226
    sub = subs.add_parser('unlink', description=info.capitalize() + '.',
227 1
                          help=info, **shared)
228 1
    sub.add_argument('child',
229 1
                     help="child item UID to unlink from parent")
230
    sub.add_argument('parent',
231 1
                     help="parent item UID child is linked to")
232
233
234
def _clear(subs, shared):
235 1
    """Configure the `doorstop clear` subparser."""
236
    info = "absolve items of their suspect link status"
237 1
    sub = subs.add_parser('clear', description=info.capitalize() + '.',
238 1
                          help=info, **shared)
239
    sub.add_argument('label', help="item UID, document prefix, or 'all'")
240 1
    group = sub.add_mutually_exclusive_group()
241 1
    group.add_argument('-i', '--item', action='store_true',
242 1
                       help="indicates the 'label' is an item UID")
243
    group.add_argument('-d', '--document', action='store_true',
244 1
                       help="indicates the 'label' is a document prefix")
245
246
247
def _review(subs, shared):
248 1
    """Configure the `doorstop review` subparser."""
249
    info = "absolve items of their unreviewed status"
250 1
    sub = subs.add_parser('review', description=info.capitalize() + '.',
251 1
                          help=info, **shared)
252
    sub.add_argument('label', help="item UID, document prefix, or 'all'")
253 1
    group = sub.add_mutually_exclusive_group()
254
    group.add_argument('-i', '--item', action='store_true',
255 1
                       help="indicates the 'label' is an item UID")
256 1
    group.add_argument('-d', '--document', action='store_true',
257 1
                       help="indicates the 'label' is a document prefix")
258
259 1
260 View Code Duplication
def _import(subs, shared):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
261 1
    """Configure the `doorstop import` subparser."""
262
    info = "import an existing document or item"
263 1
    sub = subs.add_parser('import', description=info.capitalize() + '.',
264
                          help=info, **shared)
265 1
    sub.add_argument('path', nargs='?',
266
                     help="path to previously exported document file")
267
    sub.add_argument('prefix', nargs='?', help="prefix of document for import")
268
    group = sub.add_mutually_exclusive_group()
269 1
    group.add_argument('-d', '--document', nargs=2, metavar='ARG',
270
                       help="import an existing document by: PREFIX PATH")
271 1
    group.add_argument('-i', '--item', nargs=2, metavar='ARG',
272 1
                       help="import an existing item by: PREFIX UID")
273
    sub.add_argument('-p', '--parent', metavar='PREFIX',
274 1
                     help="parent document prefix for imported document")
275 1
    sub.add_argument('-a', '--attrs', metavar='DICT',
276
                     help="dictionary of item attributes to import")
277 1
    sub.add_argument('-m', '--map', metavar='DICT',
278 1
                     help="dictionary of custom item attribute names")
279
280 1
281
def _export(subs, shared):
282 1
    """Configure the `doorstop export` subparser."""
283
    info = "export a document as YAML or another format"
284 1
    sub = subs.add_parser('export', description=info.capitalize() + '.',
285
                          help=info, **shared)
286 1
    sub.add_argument('prefix', help="prefix of document to export or 'all'")
287
    sub.add_argument('path', nargs='?',
288
                     help="path to exported file or directory for 'all'")
289
    group = sub.add_mutually_exclusive_group()
290 1
    group.add_argument('-y', '--yaml', action='store_true',
291
                       help="output YAML (default when no path)")
292 1
    group.add_argument('-c', '--csv', action='store_true',
293 1
                       help="output CSV (default for 'all')")
294
    group.add_argument('-t', '--tsv', action='store_true',
295 1
                       help="output TSV")
296 1
    group.add_argument('-x', '--xlsx', action='store_true',
297
                       help="output XLSX")
298 1
    sub.add_argument('-w', '--width', type=int,
299 1
                     help="limit line width on text output")
300
301 1
302
def _publish(subs, shared):
303 1
    """Configure the `doorstop publish` subparser."""
304
    info = "publish a document as text or another format"
305 1
    sub = subs.add_parser('publish', description=info.capitalize() + '.',
306
                          help=info, **shared)
307 1
    sub.add_argument('prefix', help="prefix of document to publish or 'all'")
308
    sub.add_argument('path', nargs='?',
309 1
                     help="path to published file or directory for 'all'")
310
    group = sub.add_mutually_exclusive_group()
311
    group.add_argument('-t', '--text', action='store_true',
312 1
                       help="output text (default when no path)")
313
    group.add_argument('-m', '--markdown', action='store_true',
314 1
                       help="output Markdown")
315
    group.add_argument('-H', '--html', action='store_true',
316
                       help="output HTML (default for 'all')")
317
    sub.add_argument('-w', '--width', type=int,
318
                     help="limit line width on text output")
319
    sub.add_argument('-C', '--no-child-links', action='store_true',
320
                     help="do not include child links on items")
321
    sub.add_argument('-L', '--no-body-levels', action='store_true',
322
                     default=None,
323
                     help="do not include levels on non-heading items")
324
    sub.add_argument('--no-levels', choices=['all', 'body'],
325
                     help="do not include levels on heading and non-heading or non-heading items")
326
    sub.add_argument('--template', help="template file", default=publisher.HTMLTEMPLATE)
327
328
329
if __name__ == '__main__':  # pragma: no cover (manual test)
330
    main()
331