forked from datalad/datalad
-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpers.py
277 lines (242 loc) · 10.1 KB
/
helpers.py
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
# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-
# ex: set sts=4 ts=4 sw=4 et:
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the datalad package for the
# copyright and license terms.
#
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
"""CONFIRMED TO BE UNIQUE TO THE CLI
"""
__docformat__ = 'restructuredtext'
import argparse
import os
import re
import sys
import gzip
import textwrap
from textwrap import wrap
from datalad import __version__
# delay?
from datalad.support.exceptions import CapturedException
from datalad.ui.utils import get_console_width
from datalad.utils import is_interactive
from platformdirs import AppDirs
dirs = AppDirs("datalad", "datalad.org")
from logging import getLogger
lgr = getLogger('datalad.cli.helpers')
class HelpAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
# Lets use the manpage on mature systems but only for subcommands --
# --help should behave similar to how git does it:
# regular --help for "git" but man pages for specific commands.
# It is important since we do discover all subcommands from entry
# points at run time and thus any static manpage would like be out of
# date
interactive = is_interactive()
if interactive \
and option_string == '--help' \
and ' ' in parser.prog: # subcommand
self._try_manpage(parser)
if option_string == '-h':
helpstr = self._get_short_help(parser)
else:
helpstr = self._get_long_help(parser)
# normalize capitalization to what we "always" had
helpstr = f'Usage:{helpstr[6:]}'
if interactive and option_string == '--help':
import pydoc
pydoc.pager(helpstr)
else:
print(helpstr)
sys.exit(0)
def _get_long_help(self, parser):
helpstr = parser.format_help()
if ' ' in parser.prog: # subcommand
# in case of a subcommand there is no need to pull the
# list of top-level subcommands
return helpstr
helpstr = re.sub(
r'^[uU]sage: .*?\n\s*\n',
'Usage: datalad [global-opts] command [command-opts]\n\n',
helpstr,
flags=re.MULTILINE | re.DOTALL)
# split into preamble and options
preamble = []
options = []
in_options = False
for line in helpstr.splitlines():
if line == 'optional arguments:':
in_options = True
continue
(options if in_options else preamble).append(line)
intf = self._get_all_interfaces()
from datalad.interface.base import (
get_cmd_doc,
load_interface,
)
from .interface import (
get_cmdline_command_name,
alter_interface_docs_for_cmdline,
)
preamble = get_description_with_cmd_summary(
# produce a mapping of command groups to
# [(cmdname, description), ...]
{
i[0]: [(
get_cmdline_command_name(c),
# alter_interface_docs_for_cmdline is only needed, because
# some commands use sphinx markup in their summary line
# stripping that takes 10-30ms for a typical datalad
# installation with some extensions
alter_interface_docs_for_cmdline(
# we only take the first line
get_cmd_doc(
# we must import the interface class
# this will engage @build_doc -- unavoidable right
# now
load_interface(c)
).split('\n', maxsplit=1)[0]))
for c in i[2]]
for i in intf
},
intf,
'\n'.join(preamble),
)
return '{}\n\n*Global options*\n{}\n'.format(
preamble,
'\n'.join(options),
)
def _get_short_help(self, parser):
usage = parser.format_usage()
hint = "Use '--help' to get more comprehensive information."
if ' ' in parser.prog: # subcommand
# in case of a subcommand there is no need to pull the
# list of top-level subcommands
return f"{usage}\n{hint}"
# get the list of commands and format them like
# argparse would present subcommands
commands = get_commands_from_groups(self._get_all_interfaces())
indent = usage.splitlines()[-1]
indent = indent[:-len(indent.lstrip())] + ' '
usage += f'{indent[1:]}{{'
usage += '\n'.join(wrap(
', '.join(sorted(c.strip() for c in commands)),
break_on_hyphens=False,
subsequent_indent=indent))
usage += f'}}\n{indent[1:]}...\n'
return f"{usage}\n{hint}"
def _get_all_interfaces(self):
# load all extensions and command specs
# this does not fully tune all the command docs
from datalad.interface.base import get_interface_groups
interface_groups = get_interface_groups()
add_entrypoints_to_interface_groups(interface_groups)
return interface_groups
def _try_manpage(self, parser):
try:
import subprocess
# get the datalad manpage to use
manfile = os.environ.get('MANPATH', '/usr/share/man') \
+ '/man1/{0}.1.gz'.format(parser.prog.replace(' ', '-'))
# extract version field from the manpage
if not os.path.exists(manfile):
raise IOError("manfile is not found")
with gzip.open(manfile) as f:
man_th = [line for line in f if line.startswith(b".TH")][0]
man_version = man_th.split(b' ')[-1].strip(b" '\"\t\n").decode('utf-8')
# don't show manpage if man_version not equal to current datalad_version
if __version__ != man_version:
raise ValueError
subprocess.check_call(
'man %s 2> /dev/null' % manfile,
shell=True)
sys.exit(0)
except (subprocess.CalledProcessError, IOError, OSError, IndexError, ValueError) as e:
ce = CapturedException(e)
lgr.debug("Did not use manpage since %s", ce)
class LogLevelAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
from datalad.log import LoggerHelper
LoggerHelper().set_level(level=values)
#
# Some logic modules extracted from main.py to de-spagetify
#
def add_entrypoints_to_interface_groups(interface_groups):
from datalad.support.entrypoints import iter_entrypoints
for name, _, spec in iter_entrypoints('datalad.extensions', load=True):
if len(spec) < 2 or not spec[1]:
# entrypoint identity was logged by the iterator already
lgr.debug('Extension does not provide a command suite')
continue
interface_groups.append((name, spec[0], spec[1]))
def get_commands_from_groups(groups):
"""Get a dictionary of command: interface_spec"""
from .interface import get_cmdline_command_name
return {
get_cmdline_command_name(_intfspec): _intfspec
for _, _, _interfaces in groups
for _intfspec in _interfaces
}
def _fix_datalad_ri(s):
"""Fixup argument if it was a DataLadRI and had leading / removed
See gh-2643
"""
if s.startswith('//') and (len(s) == 2 or (len(s) > 2 and s[2] != '/')):
lgr.info(
"Changing %s back to /%s as it was probably changed by MINGW/MSYS, "
"see http://www.mingw.org/wiki/Posix_path_conversion", s, s)
return "/" + s
return s
def get_description_with_cmd_summary(grp_short_descriptions, interface_groups,
parser_description):
from .interface import (
dedent_docstring,
)
from datalad.interface.base import get_cmd_summaries
lgr.debug("Generating detailed description for the parser")
console_width = get_console_width()
cmd_summary = get_cmd_summaries(grp_short_descriptions, interface_groups,
width=console_width)
# we need one last formal section to not have the trailed be
# confused with the last command group
cmd_summary.append('\n*General information*\n')
detailed_description = '{}{}\n{}\n'.format(
parser_description,
'\n'.join(cmd_summary),
textwrap.fill(dedent_docstring("""\
Detailed usage information for individual commands is
available via command-specific --help, i.e.:
datalad <command> --help"""),
console_width - 5,
initial_indent='',
subsequent_indent=''))
return detailed_description
def _parse_overrides_from_cmdline(cmdlineargs):
"""parse config overrides provided in command line
Might exit(3) the entire process if value is not assigned"""
# this expression is deliberately loose as gitconfig offers
# quite some flexibility -- this is just meant to catch stupid
# errors: we need a section, a variable, and a value at minimum
# otherwise we break our own config parsing helpers
# https://github.com/datalad/datalad/issues/3451
assign_expr = re.compile(r'[^\s]+\.[^\s]+=[\S]+')
unset_expr = re.compile(r':[^\s]+\.[^\s=]+')
noassign = [
o
for o in cmdlineargs.cfg_overrides
if not (assign_expr.match(o) or unset_expr.match(o))
]
if noassign:
lgr.error(
"Configuration override without section/variable "
"or unset marker or value assignment "
"(must be '(:section.variable|section.variable=value)'): %s",
noassign)
sys.exit(3)
overrides = dict(
[o[1:], None] if o.startswith(':')
else o.split('=', 1)
for o in cmdlineargs.cfg_overrides
)
return overrides