Completed
Pull Request — develop (#227)
by
unknown
13:55
created

_edit()   B

Complexity

Conditions 1

Size

Total Lines 25

Duplication

Lines 21
Ratio 84 %

Code Coverage

Tests 13
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
c 0
b 0
f 0
dl 21
loc 25
ccs 13
cts 13
cp 1
crap 1
rs 8.8571
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
from doorstop.core import publisher, vcs, document
12 1
13
log = common.logger(__name__)
14
15 1
16
def main(args=None):  # pylint: disable=R0915
17 1
    """Process command-line arguments and run the program."""
18
    from doorstop import CLI, VERSION, DESCRIPTION
19
20 1
    # Shared options
21 1
    project = argparse.ArgumentParser(add_help=False)
22
    try:
23 1
        root = vcs.find_root(os.getcwd())
24
    except common.DoorstopInfo:
25 1
        root = None
26 1
    project.add_argument('-j', '--project', metavar='PATH',
27
                         help="path to the root of the project",
28 1
                         default=root)
29
    project.add_argument('--no-cache', action='store_true',
30 1
                         help=argparse.SUPPRESS)
31
    server = argparse.ArgumentParser(add_help=False)
32 1
    server.add_argument('--server', metavar='HOST',
33 1
                        help="IP address or hostname for a running server",
34 1
                        default=settings.SERVER_HOST)
35 1
    server.add_argument('--port', metavar='NUMBER', type=int,
36
                        help="use a custom port for the server",
37 1
                        default=settings.SERVER_PORT)
38
    server.add_argument('-f', '--force', action='store_true',
39 1
                        help="perform the action without the server")
40
    debug = argparse.ArgumentParser(add_help=False)
41
    debug.add_argument('-V', '--version', action='version', version=VERSION)
42
    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 1
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")
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (81/80).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
65 1
    parser.add_argument('-S', '--no-suspect-check', action='store_true',
66
                        help="do not check for suspect links")
67
    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 1
                        help="skip a document during validation")
71 1
    parser.add_argument('-w', '--warn-all', action='store_true',
72 1
                        help="display all info-level issues as warnings")
73 1
    parser.add_argument('-e', '--error-all', action='store_true',
74 1
                        help="display all warning-level issues as errors")
75 1
76 1
    # 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
    _reorder(subs, shared)
84
    _link(subs, shared)
85 1
    _unlink(subs, shared)
86
    _clear(subs, shared)
87
    _review(subs, shared)
88 1
    _import(subs, shared)
89
    _export(subs, shared)
90
    _publish(subs, shared)
91 1
92
    # Parse arguments
93
    args = parser.parse_args(args=args)
94 1
95 1
    # Configure logging
96 1
    utilities.configure_logging(args.verbose)
97 1
98 1
    # Configure settings
99 1
    utilities.configure_settings(args)
100 1
101 1
    # Run the program
102 1
    function = commands.get(args.command)
103 1
    try:
104 1
        success = function(args, os.getcwd(), parser.error)
105
    except common.DoorstopFileError as exc:
106 1
        log.error(exc)
107 1
        success = False
108
    except KeyboardInterrupt:
109
        log.debug("command cancelled")
110 1
        success = False
111
    if success:
112 1
        log.debug("command succeeded")
113 1
    else:
114
        log.debug("command failed")
115 1
        sys.exit(1)
116 1
117 1
118 1
def _create(subs, shared):
119
    """Configure the `doorstop create` subparser."""
120
    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
    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 1
130
def _delete(subs, shared):
131 1
    """Configure the `doorstop delete` subparser."""
132 1
    info = "delete a document directory"
133
    sub = subs.add_parser('delete', description=info.capitalize() + '.',
134 1
                          help=info, **shared)
135
    sub.add_argument('prefix', help="prefix of document to delete")
136 1
137 1
138
def _add(subs, shared):
139
    """Configure the `doorstop add` subparser."""
140
    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 1
                     help="document prefix for the new item")
145
    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 1
150
def _remove(subs, shared):
151 1
    """Configure the `doorstop remove` subparser."""
152 1
    info = "remove an item file from a document directory"
153
    sub = subs.add_parser('remove', description=info.capitalize() + '.',
154 1 View Code Duplication
                          help=info, **shared)
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
155
    sub.add_argument('uid', help="item UID to remove from its document")
156 1
157 1
158
def _edit(subs, shared):
159 1
    """Configure the `doorstop edit` subparser."""
160
    info = "open an existing item or document for editing"
161 1
    sub = subs.add_parser('edit', description=info.capitalize() + '.',
162 1
                          help=info, **shared)
163
    sub.add_argument('label',
164 1
                     help="item UID or document prefix to open for editing")
165
    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
    group.add_argument('-y', '--yaml', action='store_true',
172
                       help="edit document as exported YAML (default)")
173
    group.add_argument('-c', '--csv', action='store_true',
174 1
                       help="edit document as exported CSV")
175
    group.add_argument('-t', '--tsv', action='store_true',
176 1
                       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 1
                          help="text editor to open the document item",
182
                          required=True)
183 1
184
185 1
def _reorder(subs, shared):
186
    """Configure the `doorstop reorder` subparser."""
187
    info = "organize the outline structure of a document"
188
    sub = subs.add_parser('reorder', description=info.capitalize() + '.',
189 1
                          help=info, **shared)
190
    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
    required = sub.add_argument_group('required arguments')
197
    required.add_argument('-T', '--tool', metavar='PROGRAM',
198
                          help="text editor to open the document index",
199
                          required=True)
200 1
201
202 1
def _link(subs, shared):
203 1
    """Configure the `doorstop link` subparser."""
204
    info = "add a new link between two items"
205 1
    sub = subs.add_parser('link', description=info.capitalize() + '.',
206
                          help=info, **shared)
207 1
    sub.add_argument('child',
208
                     help="child item UID to link to the parent")
209
    sub.add_argument('parent',
210
                     help="parent item UID to link from the child")
211 1
212
213 1
def _unlink(subs, shared):
214 1
    """Configure the `doorstop unlink` subparser."""
215
    info = "remove a link between two items"
216 1
    sub = subs.add_parser('unlink', description=info.capitalize() + '.',
217 1
                          help=info, **shared)
218 1
    sub.add_argument('child',
219
                     help="child item UID to unlink from parent")
220 1
    sub.add_argument('parent',
221
                     help="parent item UID child is linked to")
222
223
224 1
def _clear(subs, shared):
225
    """Configure the `doorstop clear` subparser."""
226 1
    info = "absolve items of their suspect link status"
227 1
    sub = subs.add_parser('clear', description=info.capitalize() + '.',
228
                          help=info, **shared)
229 1
    sub.add_argument('label', help="item UID, document prefix, or 'all'")
230 1
    group = sub.add_mutually_exclusive_group()
231 1
    group.add_argument('-i', '--item', action='store_true',
232
                       help="indicates the 'label' is an item UID")
233 1
    group.add_argument('-d', '--document', action='store_true',
234
                       help="indicates the 'label' is a document prefix")
235
236
237 1
def _review(subs, shared):
238
    """Configure the `doorstop review` subparser."""
239 1
    info = "absolve items of their unreviewed status"
240 1
    sub = subs.add_parser('review', description=info.capitalize() + '.',
241
                          help=info, **shared)
242 1
    sub.add_argument('label', help="item UID, document prefix, or 'all'")
243
    group = sub.add_mutually_exclusive_group()
244 1
    group.add_argument('-i', '--item', action='store_true',
245 1
                       help="indicates the 'label' is an item UID")
246 1 View Code Duplication
    group.add_argument('-d', '--document', action='store_true',
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
247
                       help="indicates the 'label' is a document prefix")
248 1
249
250 1
def _import(subs, shared):
251
    """Configure the `doorstop import` subparser."""
252 1
    info = "import an existing document or item"
253
    sub = subs.add_parser('import', description=info.capitalize() + '.',
254 1
                          help=info, **shared)
255
    sub.add_argument('path', nargs='?',
256
                     help="path to previously exported document file")
257
    sub.add_argument('prefix', nargs='?', help="prefix of document for import")
258 1
    group = sub.add_mutually_exclusive_group()
259
    group.add_argument('-d', '--document', nargs=2, metavar='ARG',
260 1
                       help="import an existing document by: PREFIX PATH")
261 1
    group.add_argument('-i', '--item', nargs=2, metavar='ARG',
262
                       help="import an existing item by: PREFIX UID")
263 1
    sub.add_argument('-p', '--parent', metavar='PREFIX',
264 1
                     help="parent document prefix for imported document")
265
    sub.add_argument('-a', '--attrs', metavar='DICT',
266 1
                     help="dictionary of item attributes to import")
267 1
    sub.add_argument('-m', '--map', metavar='DICT',
268
                     help="dictionary of custom item attribute names")
269 1
270
271 1
def _export(subs, shared):
272
    """Configure the `doorstop export` subparser."""
273 1
    info = "export a document as YAML or another format"
274
    sub = subs.add_parser('export', description=info.capitalize() + '.',
275 1
                          help=info, **shared)
276
    sub.add_argument('prefix', help="prefix of document to export or 'all'")
277
    sub.add_argument('path', nargs='?',
278
                     help="path to exported file or directory for 'all'")
279 1
    group = sub.add_mutually_exclusive_group()
280
    group.add_argument('-y', '--yaml', action='store_true',
281 1
                       help="output YAML (default when no path)")
282 1
    group.add_argument('-c', '--csv', action='store_true',
283
                       help="output CSV (default for 'all')")
284 1
    group.add_argument('-t', '--tsv', action='store_true',
285 1
                       help="output TSV")
286
    group.add_argument('-x', '--xlsx', action='store_true',
287 1
                       help="output XLSX")
288 1
    sub.add_argument('-w', '--width', type=int,
289
                     help="limit line width on text output")
290 1
291
292 1
def _publish(subs, shared):
293
    """Configure the `doorstop publish` subparser."""
294 1
    info = "publish a document as text or another format"
295
    sub = subs.add_parser('publish', description=info.capitalize() + '.',
296 1
                          help=info, **shared)
297
    sub.add_argument('prefix', help="prefix of document to publish or 'all'")
298 1
    sub.add_argument('path', nargs='?',
299
                     help="path to published file or directory for 'all'")
300
    group = sub.add_mutually_exclusive_group()
301 1
    group.add_argument('-t', '--text', action='store_true',
302
                       help="output text (default when no path)")
303
    group.add_argument('-m', '--markdown', action='store_true',
304
                       help="output Markdown")
305
    group.add_argument('-H', '--html', action='store_true',
306
                       help="output HTML (default for 'all')")
307
    sub.add_argument('-w', '--width', type=int,
308
                     help="limit line width on text output")
309
    sub.add_argument('-C', '--no-child-links', action='store_true',
310
                     help="do not include child links on items")
311
    sub.add_argument('-L', '--no-body-levels', action='store_true',
312
                     default=None,
313
                     help="do not include levels on non-heading items")
314
    sub.add_argument('--no-levels', choices=['all', 'body'],
315
                     help="do not include levels on heading and non-heading or non-heading items")
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (98/80).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
316
    sub.add_argument('--template', help="template file", default=publisher.HTMLTEMPLATE)
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (88/80).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
317
318
if __name__ == '__main__':  # pragma: no cover (manual test)
319
    main()
320