Debian Codegraph @

behave4cmd0/command_shell.py

raw
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 """
4 Provide a behave shell to simplify creation of feature files
5 and running features, etc.
6
7 context.command_result = behave_shell.behave(cmdline, cwd=context.workdir)
8 behave_shell.create_scenario(scenario_text, cwd=context.workdir)
9 behave_shell.create_step_definition(context.text, cwd=context.workdir)
10 context.command_result = behave_shell.run_feature_with_formatter(
11 context.features[0], formatter=formatter, cwd=context.workdir)
12
13 """
14
15 from __future__ import absolute_import, print_function, with_statement
16 from behave4cmd0.__setup import TOP
17 from behave.textutil import text as _text
18 import os.path
19 import six
20 import subprocess
21 import sys
22 import shlex
23 if six.PY2:
24 import codecs
25
26
27 # HERE = os.path.dirname(__file__)
28 # TOP = os.path.join(HERE, "..")
29
30 # -----------------------------------------------------------------------------
31 # CLASSES:
32 # -----------------------------------------------------------------------------
33 class CommandResult(object):
34 """
35 ValueObject to store the results of a subprocess command call.
36 """
37 def __init__(self, **kwargs):
38 self.command = kwargs.pop("command", None)
39 self.returncode = kwargs.pop("returncode", 0)
40 self.stdout = kwargs.pop("stdout", "")
41 self.stderr = kwargs.pop("stderr", "")
42 self._output = None
43 if kwargs:
44 names = ", ".join(kwargs.keys())
45 raise ValueError("Unexpected: %s" % names)
46
47 @property
48 def output(self):
49 if self._output is None:
50 output = self.stdout
51 if self.stderr:
52 if self.stdout:
53 output += "\n"
54 output += self.stderr
55 self._output = output
56 return self._output
57
58 @property
59 def failed(self):
60 return self.returncode != 0
61
62 def clear(self):
63 self.command = None
64 self.returncode = 0
65 self.stdout = ""
66 self.stderr = ""
67 self._output = None
68
69
70 class Command(object):
71 """
72 Helper class to run commands as subprocess,
73 collect their output and subprocess returncode.
74 """
75 DEBUG = False
76 COMMAND_MAP = {
77 "behave": os.path.normpath("{0}/bin/behave".format(TOP))
78 }
79 PREPROCESSOR_MAP = {}
80 POSTPROCESSOR_MAP = {}
81 USE_SHELL = sys.platform.startswith("win")
82
83 @staticmethod
84 def preprocess_command(preprocessors, cmdargs, command=None, cwd="."):
85 if not os.path.isdir(cwd):
86 return cmdargs
87 elif not command:
88 command = " ".join(cmdargs)
89
90 for preprocess in preprocessors:
91 cmdargs = preprocess(command, cmdargs, cwd)
92 return cmdargs
93
94 @staticmethod
95 def postprocess_command(postprocessors, command_result):
96 for postprocess in postprocessors:
97 command_result = postprocess(command_result)
98 return command_result
99
100 @classmethod
101 def run(cls, command, cwd=".", **kwargs):
102 """
103 Make a subprocess call, collect its output and returncode.
104 Returns CommandResult instance as ValueObject.
105 """
106 assert isinstance(command, six.string_types)
107 command_result = CommandResult()
108 command_result.command = command
109 use_shell = cls.USE_SHELL
110 if "shell" in kwargs:
111 use_shell = kwargs.pop("shell")
112
113 # -- BUILD COMMAND ARGS:
114 if six.PY2 and isinstance(command, six.text_type):
115 # -- PREPARE-FOR: shlex.split()
116 # In PY2, shlex.split() requires bytes string (non-unicode).
117 # In PY3, shlex.split() accepts unicode string.
118 command = codecs.encode(command, "utf-8")
119 cmdargs = shlex.split(command)
120
121 # -- TRANSFORM COMMAND (optional)
122 command0 = cmdargs[0]
123 real_command = cls.COMMAND_MAP.get(command0, None)
124 if real_command:
125 cmdargs0 = real_command.split()
126 cmdargs = cmdargs0 + cmdargs[1:]
127 preprocessors = cls.PREPROCESSOR_MAP.get(command0)
128 if preprocessors:
129 cmdargs = cls.preprocess_command(preprocessors, cmdargs, command, cwd)
130
131
132 # -- RUN COMMAND:
133 try:
134 process = subprocess.Popen(cmdargs,
135 stdout=subprocess.PIPE,
136 stderr=subprocess.PIPE,
137 universal_newlines=True,
138 shell=use_shell,
139 cwd=cwd, **kwargs)
140 out, err = process.communicate()
141 if six.PY2: # py3: we get unicode strings, py2 not
142 # default_encoding = "UTF-8"
143 out = _text(out, process.stdout.encoding)
144 err = _text(err, process.stderr.encoding)
145 process.poll()
146 assert process.returncode is not None
147 command_result.stdout = out
148 command_result.stderr = err
149 command_result.returncode = process.returncode
150 if cls.DEBUG:
151 print("shell.cwd={0}".format(kwargs.get("cwd", None)))
152 print("shell.command: {0}".format(" ".join(cmdargs)))
153 print("shell.command.output:\n{0};".format(command_result.output))
154 except OSError as e:
155 command_result.stderr = u"OSError: %s" % e
156 command_result.returncode = e.errno
157 assert e.errno != 0
158
159 postprocessors = cls.POSTPROCESSOR_MAP.get(command0)
160 if postprocessors:
161 command_result = cls.postprocess_command(postprocessors, command_result)
162 return command_result
163
164
165 # -----------------------------------------------------------------------------
166 # PREPROCESSOR:
167 # -----------------------------------------------------------------------------
168 def path_glob(command, cmdargs, cwd="."):
169 import glob
170 if not glob.has_magic(command):
171 return cmdargs
172
173 assert os.path.isdir(cwd)
174 try:
175 current_cwd = os.getcwd()
176 os.chdir(cwd)
177 new_cmdargs = []
178 for cmdarg in cmdargs:
179 if not glob.has_magic(cmdarg):
180 new_cmdargs.append(cmdarg)
181 continue
182
183 more_args = glob.glob(cmdarg)
184 if more_args:
185 new_cmdargs.extend(more_args)
186 else:
187 # -- BAD-CASE: Require at least one match.
188 # Otherwise, restore original arg.
189 new_cmdargs.append(cmdarg)
190
191 cmdargs = new_cmdargs
192 finally:
193 os.chdir(current_cwd)
194 return cmdargs
195
196 # -----------------------------------------------------------------------------
197 # FUNCTIONS:
198 # -----------------------------------------------------------------------------
199 def run(command, cwd=".", **kwargs):
200 return Command.run(command, cwd=cwd, **kwargs)
201
202 def behave(cmdline, cwd=".", **kwargs):
203 """
204 Run behave as subprocess command and return process/shell instance
205 with results (collected output, returncode).
206 """
207 assert isinstance(cmdline, six.string_types)
208 return run("behave " + cmdline, cwd=cwd, **kwargs)
209
210 # -----------------------------------------------------------------------------
211 # TEST MAIN:
212 # -----------------------------------------------------------------------------
213 if __name__ == "__main__":
214 command = " ".join(sys.argv[1:])
215 output = Command.run(sys.argv[1:])
216 print("command: {0}\n{1}\n".format(command, output))