/
mirpyhelp.py
executable file
·258 lines (207 loc) · 8.12 KB
/
mirpyhelp.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
#! /usr/bin/env python
# -*- python -*-
# Copyright 2009-2012 Peter Williams
#
# This file is part of miriad-python.
#
# Miriad-python is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# Miriad-python is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with miriad-python. If not, see <http://www.gnu.org/licenses/>.
"""= mirpyhelp.py - Provide Miriad help with support for Python tasks.
& pkgw
: Tools
+
This script pages documentation for standard Miriad tasks as well as
Python tasks.
Usage:
mirpyhelp.py [name1] [name2] [...]
If no names are specified, the documentation to mirpyhelp.py (this
text) is printed.
Each name is checked to see if it corresponds to a file in the
standard Miriad documentation directories, $MIRPDOC and $MIRSDOC. If
so, that documentation file is fed through the lowlevel "doc" command
and paged (via the program named in $PAGER or "more" if $PAGER is
unset). If "name" is not in one of those directories, the directories
listed in $PATH are searched for a file with the specified name. If
such a file exists, and it appears to be a Python file, a special
Miriad docstring is read from the file, processed with the "doc"
command, and paged as above.
This process is repeated for each name on the commandline.
This script can be used similarly to the script "mir.help" (which is
usually known as "mirhelp"), but it is not an identical drop-in
replacement. It is suggested that "mirhelp" be re-aliased to this
script and that the true script name, "mir.help", be used if certain
features found in that script are needed.
--
"""
import sys, os
from subprocess import Popen, PIPE
from os.path import join, exists
from tempfile import mkdtemp
def findExeFile (stem):
exepath = os.environ['PATH'].split (os.pathsep)
for d in exepath:
full = join (d, stem)
if exists (full): return d, full
return None, None
def printKeywordDoc (keyword, dest):
if 'MIRCAT' not in os.environ:
print >>dest, ' [$MIRCAT not defined! Unable to look up'
print >>dest, 'standard keyword documentation.]'
return
kwfile = join (os.environ['MIRCAT'], 'keywords.kdoc')
if not exists (kwfile):
print >>dest, ' [No standard keyword docfile %s]' % kwfile
return
match = '%N ' + keyword
inKeyword = False
for l in file (kwfile, 'r'):
if inKeyword:
if l.startswith ('%N'): break
# I don't get the point of these lines in keywords.kdoc.
if l[0] == '>': continue
# normalize the indentation by stripping.
print >>dest, '#', l.strip ()
else:
if l.startswith (match):
print >>dest, '#@', keyword
inKeyword = True
def printDocSection (name, full, dest):
# We can't import the file as a module since that will execute
# the task. (We don't want to have to write every task inside some big
# function with "if __name__ == '__main__': doit ()" at the bottom of
# the file.) So read the file ourselves and look for a
# specially-formatted docstring.
inString = False
for line in file (full, 'r'):
if not inString:
if line.startswith ('"""='):
inString = True
# 'line' still has the trailing newline so use the
# finishing comma with print
print >>dest, '#' + line[3:],
else:
if line.startswith ('"""'): break
if line[0] != '<':
# As above.
print >>dest, '#' + line,
continue
# We have a standard-keyword line. 'doc' won't substitute
# those for us because we're a -e file, so do it manually.
keyword = line[1:].strip ()
printKeywordDoc (keyword, dest)
if not inString:
print >>dest, """#= %s - Undocumented
#& Unknown
#: Unknown
#+
#
# No documentation string has been written for this task.
# This is a serious omission on the part of its author.
#
#--
""" % name
def showDoc (name, pdoc, sdoc):
from glob import glob1
hits = glob1 (pdoc, name + '.*') + glob1 (sdoc, name + '.*')
if len (hits) > 1:
print >>sys.stderr, 'Multiple matches for', name
print >>sys.stderr, 'FIXME: add disambiguation.'
return True
if len (hits) == 1:
isPython = False
full = join (pdoc, hits[0])
if not exists (full):
full = join (sdoc, hits[0])
else:
dirname, full = findExeFile (name)
if dirname is None:
print >>sys.stderr, 'No matches for', name, 'and couldn\'t find it in $PATH.'
print >>sys.stderr, '(Note that exact filename matches are required.)'
return True
fcheck = file (full, 'r')
start = fcheck.read (32)
if 'mirpymodtask' in start:
# This script is a wrapper; look for a Python module
# with the same name and use that for the docs.
try:
modobj = __import__ (name)
full = modobj.__file__
if full.endswith ('.pyc'): full = full[:-1]
except Exception, e:
print >>sys.stderr, 'error: The task', name, 'seems to be a Python module'
print >>sys.stderr, ' but I can\'t successfully load the module to get its'
print >>sys.stderr, ' docs.'
print >>sys.stderr, ' Exception:', e
return True
elif 'python' not in start:
print >>sys.stderr, 'No standard entry for', name, 'and it doesn\'t appear'
print >>sys.stderr, ' to be a Python file.'
return True
isPython = True
tmpdir = tmpin = None
try:
# If python, we have the pipeline:
#
# [our extracted docstring] |doc [args] |$PAGER
#
# Fool 'doc' into printing out the right pathname for the task ...
if isPython:
tmpdir = mkdtemp ()
tmpin = join (tmpdir, name)
os.symlink ('/dev/stdin', tmpin)
pager_cmd = os.environ.get ('PAGER') or 'more'
pager = None
try:
pager = Popen (pager_cmd, stdin=PIPE,
shell=True, close_fds=True)
try:
doc = None
if isPython:
doc_cmd = ['doc', '-e', '-o', dirname, tmpin]
doc = Popen (doc_cmd, stdin=PIPE,
stdout=pager.stdin, shell=False,
close_fds=True)
printDocSection (name, full, doc.stdin)
else:
doc_cmd = ['doc', full]
doc = Popen (doc_cmd, stdin=file (os.devnull, 'r'),
stdout=pager.stdin, shell=False,
close_fds=True)
finally:
if doc is not None:
if isPython: doc.stdin.close ()
doc.wait ()
finally:
pager.stdin.close ()
pager.wait ()
finally:
if tmpin is not None: os.unlink (tmpin)
if tmpdir is not None: os.rmdir (tmpdir)
return False
def cmdline (args):
if 'MIRPDOC' not in os.environ:
print >>sys.stderr, 'error: Environment variable $MIRPDOC not defined.'
print >>sys.stderr, ' Unable to look up documentation.'
sys.exit (1)
pdoc = os.environ['MIRPDOC']
sdoc = os.environ['MIRSDOC']
if len (args) == 1:
failures = showDoc ('mirpyhelp.py', pdoc, sdoc)
else:
failures = False
for arg in args[1:]:
failures = failures or showDoc (arg, pdoc, sdoc)
if failures: return 1
return 0
if __name__ == '__main__':
sys.exit (cmdline (sys.argv))