Skip to content

Commit af65672

Browse files
committed
Added man.py
1 parent bd02f0f commit af65672

File tree

1 file changed

+93
-0
lines changed

1 file changed

+93
-0
lines changed

man.py

+93
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
#!/usr/bin/env python
2+
"""
3+
Ghetto man replacement for GnuWin32.
4+
5+
"""
6+
import os
7+
import sys
8+
import string
9+
from subprocess import call, Popen, PIPE
10+
from optparse import OptionParser
11+
12+
__author__ = 'setrofim'
13+
__version__ = '0.1'
14+
15+
16+
tp = Popen('uname', stdout=PIPE, stderr=PIPE, shell=True)
17+
out, err = tp.communicate()
18+
if out.startswith('MINGW32'):
19+
os.sep = '/'
20+
21+
22+
GNUWIN32 = os.getenv('GNUWIN32') or r'C:\Apps\GnuWin32'
23+
DEFAULT_MAN_PAGES_PATH = os.path.join(GNUWIN32, 'man')
24+
FIND = os.path.join(GNUWIN32, 'bin', 'find.exe')
25+
MAN_PAGES_PATH = os.getenv('MAN_PAGES_PATH') or DEFAULT_MAN_PAGES_PATH
26+
PAGER = os.getenv('PAGER') or os.path.join(GNUWIN32, 'bin', 'less_.exe')
27+
28+
29+
def check_environment():
30+
for path in [GNUWIN32, DEFAULT_MAN_PAGES_PATH, FIND]:
31+
if not os.path.exists(path):
32+
raise Exception("Can't find {0}; is GNUWIN32 set correctly?".format(path))
33+
34+
35+
def error(message):
36+
sys.stderr.write('ERROR: {0}\n'.format(message))
37+
parser.print_help()
38+
sys.exit(1)
39+
40+
41+
def process_arguments(parser):
42+
opts, args = parser.parse_args()
43+
if len(args) == 2:
44+
category = args[0]
45+
if not(len(category) <= 2 and category[0] in string.digits):
46+
raise Exception('Invalid category: {0}'.format(category))
47+
item = args[1]
48+
elif len(args) == 1:
49+
category = '*'
50+
item = args[0]
51+
else:
52+
raise Exception('Incorrect number of arguments.')
53+
return category, item, opts
54+
55+
56+
if __name__ == '__main__':
57+
parser = OptionParser(usage='Usage: man.py [options] [CATEGORY] PROGRAM')
58+
parser.add_option('-a', dest='all', action='store_true',
59+
help='Display all matching entries (by default, only the first one).')
60+
parser.add_option('-i', dest='nocase', action='store_true',
61+
help='Case insensitive search.')
62+
try:
63+
check_environment()
64+
category, item, opts = process_arguments(parser)
65+
except Exception, e:
66+
error(str(e))
67+
68+
namepred = opts.nocase and 'iname' or 'name'
69+
70+
command = '{0} {4}{5}cat{1} -{2} {3}.{1}.txt'.format(FIND,
71+
category,
72+
namepred,
73+
item,
74+
MAN_PAGES_PATH,
75+
os.sep)
76+
p = Popen(command, stdout=PIPE, stderr=PIPE, shell=True)
77+
out, err = p.communicate()
78+
if err:
79+
error(err)
80+
paths = [ p.rstrip('\r\n') for p in out.split('\n') if p.rstrip('\r\n')]
81+
82+
if paths:
83+
if opts.all:
84+
args = [PAGER]
85+
args.extend(paths)
86+
call(args, shell=True)
87+
else:
88+
call([PAGER, paths[0]], shell=True)
89+
else:
90+
sys.stderr.write('Could not find {0}.\n'.format(item))
91+
sys.exit(2)
92+
93+

0 commit comments

Comments
 (0)