Debian Codegraph @

jenkins_jobs/utils.py

raw
1 #!/usr/bin/env python
2 # Copyright (C) 2015 Hewlett-Packard Development Company, L.P.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 # License for the specific language governing permissions and limitations
14 # under the License.
15
16 # functions that don't fit in well elsewhere
17
18 import codecs
19 import fnmatch
20 import locale
21 import os.path
22 from six.moves import input
23
24
25 def wrap_stream(stream, encoding="utf-8"):
26
27 try:
28 stream_enc = stream.encoding
29 except AttributeError:
30 stream_enc = locale.getpreferredencoding()
31
32 if hasattr(stream, "buffer"):
33 stream = stream.buffer
34
35 if str(stream_enc).lower() == str(encoding).lower():
36 return stream
37
38 return codecs.EncodedFile(stream, encoding, stream_enc)
39
40
41 def recurse_path(root, excludes=None):
42 if excludes is None:
43 excludes = []
44
45 basepath = os.path.realpath(root)
46 pathlist = [basepath]
47
48 patterns = [e for e in excludes if os.path.sep not in e]
49 absolute = [e for e in excludes if os.path.isabs(e)]
50 relative = [e for e in excludes if os.path.sep in e and not os.path.isabs(e)]
51 for root, dirs, files in os.walk(basepath, topdown=True):
52 # sort in-place to ensure dirnames are visited in alphabetical order
53 # a predictable order makes it easier to use the retain_anchors option
54 dirs.sort()
55 dirs[:] = [
56 d
57 for d in dirs
58 if not any([fnmatch.fnmatch(d, pattern) for pattern in patterns])
59 if not any(
60 [
61 fnmatch.fnmatch(os.path.abspath(os.path.join(root, d)), path)
62 for path in absolute
63 ]
64 )
65 if not any(
66 [
67 fnmatch.fnmatch(os.path.relpath(os.path.join(root, d)), path)
68 for path in relative
69 ]
70 )
71 ]
72 pathlist.extend([os.path.join(root, path) for path in dirs])
73
74 return pathlist
75
76
77 def confirm(question):
78 answer = input("%s (Y/N): " % question).upper().strip()
79 return answer == "Y"