-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommandparser.py
185 lines (138 loc) · 4.42 KB
/
commandparser.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
"""
commandparser.py: process commands.
this will eventually have support for pipes, but not yet.
"""
__author__ = 'Michael Gill <[email protected]>'
__version__ = '0.1a'
__all__ = ['CommandParser']
import re
import commands
import os
import sys
import subprocess
from stdabsorb import StdAbsorber, StdinSender
PATHEXT = os.environ['pathext'].split(';')
PATH = os.environ['path'].split(';') + [os.getcwd()]
def _rm_ext(fname):
d = fname.split('.')[:-1]
return '.'.join(d)
def _get_path():
d = []
for path in PATH:
if os.path.isdir(path):
d += os.listdir(path)
else:
d += [path]
# print(len(d))
# print(tuple(os.getenv('pathext').split(';')))
return d
def _get_path_from_str(cmd):
"""
find the path for the executable given along path.
"""
cmd = cmd.upper()
for path in PATH:
if os.path.isdir(path):
for i in os.listdir(path):
i = i.upper()
if _rm_ext(i) == _rm_ext(cmd) and i.endswith(tuple(PATHEXT)):
return os.path.join(path, i).lower()
else:
if path.upper().split('\\')[-1].startswith(cmd) and \
path.upper().split('\\')[-1].endswith(tuple(PATHEXT)):
return path
PATH_CMDS = list(
filter(
lambda x: x.upper().endswith(tuple(os.getenv('pathext').split(';'))),
_get_path()))
ALL_CMDS = commands.__all__ + PATH_CMDS
PATH_CMDS = [i.upper() for i in PATH_CMDS]
class _PathCmds:
base = PATH_CMDS
def __contains__(self, item):
item = item.upper()
for i in PATHEXT:
if item + i in self.base or item in self.base:
return True
return False
def __iter__(self):
for i in self.base:
yield i
def __getitem__(self, item):
item = item.upper()
for i in PATHEXT:
if item + i in self.base:
print(item + i)
return item + i
elif item in self.base:
print(item)
return item
PATH_CMDS = _PathCmds()
class _ExecutableCommand:
def __init__(self, path, args=()):
self.path = path
self.args = args
def __call__(self, stdout=None, stdin=None, stderr=None):
proc = subprocess.run(
[self.path] + list(self.args),
stdout=subprocess.PIPE if stdout is not None else None,
stderr=subprocess.PIPE if stderr is not None else None,
input=stdin,
)
returncode = proc.returncode
output = proc.stdout
return [returncode, output]
class CallableStdCommand:
def __init__(self, item):
self.item = item
def __call__(self, stdout=False, stdin=None):
if stdout:
StdAbsorber('stdout').set_file()
if stdin:
StdinSender(self.stdin).set()
toreturn = [self.item(), None]
if stdin:
sys.stdin.reset()
if stdout:
toreturn[1] = sys.stdout.read()
sys.stdout.reset()
return toreturn
class CommandParser:
def __init__(self, cmdstr):
self.cmdstr = cmdstr
self.args = self.repl_env_vars()
def rm_strings(self):
stringsplit = re.split(r'(".*")|\s|(\'.*\')', self.cmdstr)
lst = filter(None, stringsplit)
return list(lst)
def repl_env_vars(self):
lst = self.rm_strings()
new_list = []
regex = re.compile(r'\$[a-zA-Z1-9_]+')
for i in lst:
if regex.match(i):
try:
new_list.append(os.environ[i.strip('$')])
except KeyError:
new_list.append(i)
else:
new_list.append(i)
return new_list
def get_program(self):
# print(self.args[0])
cmd = None
if self.args[0] in commands.__all__:
# built-in command
# print('found command in commands.__all__')
cmd_f = getattr(commands, self.args[0])
def cmd_x():
return cmd_f(self.args[1:])
cmd = CallableStdCommand(cmd_x)
elif self.args[0] in commands.ALIAS:
# alias
cmd = commands.ALIAS[self.args[0]]
elif self.args[0] in PATH_CMDS:
cmd = _ExecutableCommand(PATH_CMDS[self.args[0]], self.args[1:])
if cmd == None:
raise TypeError('Command ')
return cmd