This file is indexed.

/usr/share/pyshared/nipype/utils/docparse.py is in python-nipype 0.5.3-2wheezy2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Utilities to pull in documentation from command-line tools.

Examples
--------

# Instantiate bet object
from nipype.interfaces import fsl
from nipype.utils import docparse
better = fsl.Bet()
docstring = docparse.get_doc(better.cmd, better.opt_map)

"""

import subprocess
from nipype.interfaces.base import CommandLine
from nipype.utils.misc import is_container

def grab_doc(cmd, trap_error=True):
    """Run cmd without args and grab documentation.

    Parameters
    ----------
    cmd : string
        Command line string
    trap_error : boolean
        Ensure that returncode is 0

    Returns
    -------
    doc : string
        The command line documentation
    """

    proc = subprocess.Popen(cmd,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE,
                            shell=True)
    stdout, stderr = proc.communicate()

    if trap_error and proc.returncode:
        msg = 'Attempting to run %s. Returned Error: %s'%(cmd,stderr)
        raise IOError(msg)

    if stderr:
        # A few programs, like fast and fnirt, send their help to
        # stderr instead of stdout.
        # XXX: Test for error vs. doc in stderr
        return stderr
    return stdout

def reverse_opt_map(opt_map):
    """Reverse the key/value pairs of the option map in the interface classes.

    Parameters
    ----------
    opt_map : dict
        Dictionary mapping the attribute name to a command line flag.
        Each interface class defines these for the command it wraps.

    Returns
    -------
    rev_opt_map : dict
       Dictionary mapping the flags to the attribute name.
    """

    # For docs, we only care about the mapping from our attribute
    # names to the command-line flags.  The 'v.split()[0]' below
    # strips off the string format characters.
    # if (k != 'flags' and v) , key must not be flags as it is generic,
    # v must not be None or it cannot be parsed by this line
    revdict = {}
    for key, value in opt_map.items():
        if is_container(value):
            # The value is a tuple where the first element is the
            # format string and the second element is a docstring.
            value = value[0]
        if (key != 'flags' and value is not None):
            revdict[value.split()[0]] = key
    return revdict


def format_params(paramlist, otherlist=None):
    """Format the parameters according to the nipy style conventions.

    Since the external programs do not conform to any conventions, the
    resulting docstrings are not ideal.  But at a minimum the
    Parameters section is reasonably close.

    Parameters
    ----------
    paramlist : list
        List of strings where each list item matches exactly one
        parameter and it's description.  These items will go into the
        'Parameters' section of the docstring.
    otherlist : list
        List of strings, similar to paramlist above.  These items will
        go into the 'Other Parameters' section of the docstring.

    Returns
    -------
    doc : string
        The formatted docstring.
    """

    hdr = 'Parameters'
    delim = '----------'
    paramlist.insert(0, delim)
    paramlist.insert(0, hdr)
    params = '\n'.join(paramlist)
    otherparams = []
    doc = ''.join(params)
    if otherlist:
        hdr = 'Others Parameters'
        delim = '-----------------'
        otherlist.insert(0, delim)
        otherlist.insert(0, hdr)
        otherlist.insert(0, '\n')
        otherparams = '\n'.join(otherlist)
        doc = ''.join([doc, otherparams])
    return doc

def insert_doc(doc, new_items):
    """Insert ``new_items`` into the beginning of the ``doc``

    Docstrings in ``new_items`` will be inserted right after the
    *Parameters* header but before the existing docs.

    Parameters
    ----------
    doc : str
        The existing docstring we're inserting docmentation into.
    new_items : list
        List of strings to be inserted in the ``doc``.

    Examples
    --------
    >>> from nipype.utils.docparse import insert_doc
    >>> doc = '''Parameters
    ... ----------
    ... outline :
    ...     something about an outline'''

    >>> new_items = ['infile : str', '    The name of the input file']
    >>> new_items.extend(['outfile : str', '    The name of the output file'])
    >>> newdoc = insert_doc(doc, new_items)
    >>> print newdoc
    Parameters
    ----------
    infile : str
        The name of the input file
    outfile : str
        The name of the output file
    outline :
        something about an outline

    """

    # Insert new_items after the Parameters header
    doclist = doc.split('\n')
    tmpdoc = doclist[:2]
    # Add new_items
    tmpdoc.extend(new_items)
    # Add rest of documents
    tmpdoc.extend(doclist[2:])
    # Insert newlines
    newdoc = []
    for line in tmpdoc:
        newdoc.append(line)
        newdoc.append('\n')
    # We add one too many newlines, remove it.
    newdoc.pop(-1)
    return ''.join(newdoc)


def build_doc(doc, opts):
    """Build docstring from doc and options

    Parameters
    ----------
    rep_doc : string
        Documentation string
    opts : dict
        Dictionary of option attributes and keys.  Use reverse_opt_map
        to reverse flags and attrs from opt_map class attribute.

    Returns
    -------
    newdoc : string
        The docstring with flags replaced with attribute names and
        formated to match nipy standards (as best we can).

    """

    # Split doc into line elements.  Generally, each line is an
    # individual flag/option.
    doclist = doc.split('\n')
    newdoc = []
    flags_doc = []
    for line in doclist:
        linelist = line.split()
        if not linelist:
            # Probably an empty line
            continue
        # For lines we care about, the first item is the flag
        if ',' in linelist[0]: #sometimes flags are only seperated by comma
            flag = linelist[0].split(',')[0]
        else:
            flag = linelist[0]
        attr = opts.get(flag)
        if attr is not None:
            #newline = line.replace(flag, attr)
            # Replace the flag with our attribute name
            linelist[0] = '%s :' % str(attr)
            # Add some line formatting
            linelist.insert(1, '\n    ')
            newline = ' '.join(linelist)
            newdoc.append(newline)
        else:
            if line[0].isspace():
                # For all the docs I've looked at, the flags all have
                # indentation (spaces) at the start of the line.
                # Other parts of the docs, like 'usage' statements
                # start with alpha-numeric characters.  We only care
                # about the flags.
                flags_doc.append(line)
    return format_params(newdoc, flags_doc)

def get_doc(cmd, opt_map, help_flag=None, trap_error=True):
    """Get the docstring from our command and options map.

    Parameters
    ----------
    cmd : string
        The command whose documentation we are fetching
    opt_map : dict
        Dictionary of flags and option attributes.
    help_flag : string
        Provide additional help flag. e.g., -h
    trap_error : boolean
        Override if underlying command returns a non-zero returncode

    Returns
    -------
    doc : string
        The formated docstring

    """
    res = CommandLine('which %s' % cmd.split(' ')[0]).run()
    cmd_path = res.runtime.stdout.strip()
    if cmd_path == '':
        raise Exception('Command %s not found'%cmd.split(' ')[0])
    if help_flag:
        cmd = ' '.join((cmd,help_flag))
    doc = grab_doc(cmd,trap_error)
    opts = reverse_opt_map(opt_map)
    return build_doc(doc, opts)

def _parse_doc(doc, style=['--']):
    """Parses a help doc for inputs

    Parameters
    ----------
    doc : string
        Documentation string
    style : string default ['--']
        The help command style (--, -)

    Returns
    -------
    optmap : dict of input parameters
    """

    # Split doc into line elements.  Generally, each line is an
    # individual flag/option.
    doclist = doc.split('\n')
    optmap = {}
    if isinstance(style,str):
        style = [style]
    for line in doclist:
        linelist = line.split()
        flag =[item for i,item in enumerate(linelist) if i<2 and \
                   any([item.startswith(s) for s in style]) and \
                   len(item)>1]
        if flag:
            if len(flag)==1:
                style_idx = [flag[0].startswith(s) for s in style].index(True)
                flag = flag[0]
            else:
                style_idx = []
                for f in flag:
                    for i,s in enumerate(style):
                        if f.startswith(s):
                            style_idx.append(i)
                            break
                flag = flag[style_idx.index(min(style_idx))]
                style_idx = min(style_idx)
            optmap[flag.split(style[style_idx])[1]] = '%s %%s'%flag
    return optmap

def get_params_from_doc(cmd, style='--', help_flag=None, trap_error=True):
    """Auto-generate option map from command line help

    Parameters
    ----------
    cmd : string
        The command whose documentation we are fetching
    style : string default ['--']
        The help command style (--, -). Multiple styles can be provided in a
        list e.g. ['--','-'].
    help_flag : string
        Provide additional help flag. e.g., -h
    trap_error : boolean
        Override if underlying command returns a non-zero returncode

    Returns
    -------
    optmap : dict
        Contains a mapping from input to command line variables

    """
    res = CommandLine('which %s' % cmd.split(' ')[0]).run()
    cmd_path = res.runtime.stdout.strip()
    if cmd_path == '':
        raise Exception('Command %s not found'%cmd.split(' ')[0])
    if help_flag:
        cmd = ' '.join((cmd,help_flag))
    doc = grab_doc(cmd,trap_error)
    return _parse_doc(doc,style)

def replace_opts(rep_doc, opts):
    """Replace flags with parameter names.

    This is a simple operation where we replace the command line flags
    with the attribute names.

    Parameters
    ----------
    rep_doc : string
        Documentation string
    opts : dict
        Dictionary of option attributes and keys.  Use reverse_opt_map
        to reverse flags and attrs from opt_map class attribute.

    Returns
    -------
    rep_doc : string
        New docstring with flags replaces with attribute names.

    Examples
    --------
    doc = grab_doc('bet')
    opts = reverse_opt_map(fsl.Bet.opt_map)
    rep_doc = replace_opts(doc, opts)

    """

    # Replace flags with attribute names
    for key, val in opts.items():
        rep_doc = rep_doc.replace(key, val)
    return rep_doc