-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandy
executable file
·85 lines (66 loc) · 2.02 KB
/
handy
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
#!/usr/bin/env python
from sys import exit, argv
from os import access, R_OK, system
from os.path import isfile
def usage():
print 'handy v1.0'
print 'handy [<handyfile> [<copy program> [<command number>]]]'
def check_can_read_file(filename):
if not (isfile(filename) and access(filename, R_OK)):
print 'Cannot read from hanyfile: ' + filename
exit(1)
def parse_file(filename):
output_lines = []
commands = []
directives = {}
command_number = 1
def format_title(title):
return '\033[1;31m=== ' + title + ' ===\033[0;0m'
def format_command(cmd, n):
return str(n) + '. ' + cmd
for line in open(filename).read().splitlines():
if line.startswith('-'):
output_lines.append(format_title(line[1:].strip()))
if line.startswith('$'):
cmd = line[1:].strip()
output_lines.append(format_command(cmd, command_number))
commands.append(cmd)
command_number += 1
if line.startswith('*'):
directives[line[1:].strip()] = True
return (output_lines, commands, directives)
def get_user_number():
try:
return int(raw_input('enter command number: '))
except ValueError:
print 'Must enter a valid number.'
exit(1)
except:
print ''
exit(0)
def escape(cmd):
cmd = cmd.replace("'", "\\'")
cmd = cmd.replace('"', '\\"')
cmd = cmd.replace('%', '%%')
return cmd
def handy(handyfile, copyprogram=None, cmdnum=None):
check_can_read_file(handyfile)
output_lines, commands, directives = parse_file(handyfile)
if cmdnum is None:
for line in output_lines:
print line
if directives.get('wait-for-input', False):
cmdnum = get_user_number()
else:
exit(0)
cmdnum = int(cmdnum)
if copyprogram is not None and cmdnum > 0 and cmdnum <= len(commands):
shell = "printf $'" + escape(commands[cmdnum - 1]) + "' | " + copyprogram
system(shell)
else:
print 'Invalid command number or no copy-program specified'
if __name__ == '__main__':
if len(argv) > 1 and len(argv) < 5:
handy(*argv[1:])
else:
usage()