Passed
Push — develop ( 4aa5dc...175d36 )
by Jace
01:30
created

doorstop/cli/main.py (2 issues)

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