Completed
Pull Request — develop (#227)
by
unknown
18:55 queued 04:07
created

_edit()   B

Complexity

Conditions 1

Size

Total Lines 25

Duplication

Lines 25
Ratio 100 %

Code Coverage

Tests 13
CRAP Score 1

Importance

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