1 #!/usr/bin/env python2.7
3 # Copyright (c) 2016 ARM Limited
6 # The license below extends only to copyright in the software and shall
7 # not be construed as granting a license to any other intellectual
8 # property including but not limited to intellectual property relating
9 # to a hardware implementation of the functionality of the software
10 # licensed hereunder. You may use the software subject to the license
11 # terms below provided that you ensure that this notice is replicated
12 # unmodified and in its entirety in all distributions of the software,
13 # modified or unmodified, in source code or in binary form.
15 # Redistribution and use in source and binary forms, with or without
16 # modification, are permitted provided that the following conditions are
17 # met: redistributions of source code must retain the above copyright
18 # notice, this list of conditions and the following disclaimer;
19 # redistributions in binary form must reproduce the above copyright
20 # notice, this list of conditions and the following disclaimer in the
21 # documentation and/or other materials provided with the distribution;
22 # neither the name of the copyright holders nor the names of its
23 # contributors may be used to endorse or promote products derived from
24 # this software without specific prior written permission.
26 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
27 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
28 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
29 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
30 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
31 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
32 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
33 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
34 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
35 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
36 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38 # Authors: Andreas Sandberg
40 from __future__
import print_function
43 from threading
import Timer
47 class CallTimeoutException(Exception):
48 """Exception that indicates that a process call timed out"""
50 def __init__(self
, status
, stdout
, stderr
):
55 class ProcessHelper(subprocess
.Popen
):
56 """Helper class to run child processes.
58 This class wraps a subprocess.Popen class and adds support for
59 using it in a with block. When the process goes out of scope, it's
60 automatically terminated.
62 with ProcessHelper(["/bin/ls"], stdout=subprocess.PIPE) as p:
65 def __init__(self
, *args
, **kwargs
):
66 super(ProcessHelper
, self
).__init
__(*args
, **kwargs
)
68 def _terminate_nicely(self
, timeout
=5):
72 if self
.returncode
is not None:
73 return self
.returncode
75 timer
= Timer(timeout
, on_timeout
)
85 def __exit__(self
, exc_type
, exc_value
, traceback
):
86 if self
.returncode
is None:
87 self
._terminate
_nicely
()
89 def call(self
, timeout
=0):
93 self
._terminate
_nicely
()
95 status
, stdout
, stderr
= None, None, None
96 timer
= Timer(timeout
, on_timeout
)
100 stdout
, stderr
= self
.communicate()
106 self
._terminate
_nicely
()
107 raise CallTimeoutException(self
.returncode
, stdout
, stderr
)
109 return status
, stdout
, stderr
111 class FileIgnoreList(object):
112 """Helper class to implement file ignore lists.
114 This class implements ignore lists using plain string matching and
115 regular expressions. In the simplest use case, rules are created
116 statically upon initialization:
118 ignore_list = FileIgnoreList(name=("ignore_me.txt", ), rex=(r".*~", )
120 Ignores can be queried using in the same ways as normal Python
123 if file_name in ignore_list:
124 print "Ignoring %s" % file_name
127 New rules can be added at runtime by extending the list in the
130 ignore_list.rules.append(FileIgnoreList.simple("bar.txt"))
135 return lambda f
: f
== r
139 re_obj
= r
if hasattr(r
, "search") else re
.compile(r
)
140 return lambda name
: re_obj
.search(name
)
142 def __init__(self
, names
=(), rex
=()):
143 self
.rules
= [ FileIgnoreList
.simple(n
) for n
in names
] + \
144 [ FileIgnoreList
.rex(r
) for r
in rex
]
146 def __contains__(self
, name
):
147 for rule
in self
.rules
:
152 if __name__
== "__main__":
153 # Run internal self tests to ensure that the helpers are working
154 # properly. The expected output when running this script is
157 cmd_foo
= [ "/bin/echo", "-n", "foo" ]
158 cmd_sleep
= [ "/bin/sleep", "10" ]
160 # Test that things don't break if the process hasn't been started
161 with
ProcessHelper(cmd_foo
) as p
:
164 with
ProcessHelper(cmd_foo
, stdout
=subprocess
.PIPE
) as p
:
165 status
, stdout
, stderr
= p
.call()
166 assert stdout
== "foo"
170 with
ProcessHelper(cmd_sleep
) as p
:
171 status
, stdout
, stderr
= p
.call(timeout
=1)
172 assert False, "Timeout not triggered"
173 except CallTimeoutException
:
176 ignore_list
= FileIgnoreList(
177 names
=("ignore.txt", "foo/test.txt"),
178 rex
=(r
"~$", re
.compile("^#")))
180 assert "ignore.txt" in ignore_list
181 assert "bar.txt" not in ignore_list
182 assert "foo/test.txt" in ignore_list
183 assert "test.txt" not in ignore_list
184 assert "file1.c~" in ignore_list
185 assert "file1.c" not in ignore_list
186 assert "#foo" in ignore_list
187 assert "foo#" not in ignore_list
189 ignore_list
.rules
.append(FileIgnoreList
.simple("bar.txt"))
190 assert "bar.txt" in ignore_list