1 """Miscellaneous utility functions"""
2 from __future__
import absolute_import
, division
, print_function
, unicode_literals
16 random
.seed(hash(time
.time()))
19 def asint(obj
, default
=0):
20 """Make any value into an int, even if the cast fails"""
23 except (TypeError, ValueError):
28 def clamp(value
, lo
, hi
):
29 """Clamp a value to the specified range"""
30 return min(hi
, max(lo
, value
))
34 return int(time
.time() * 1000)
37 def add_parents(paths
):
38 """Iterate over each item in the set and add its parent directories."""
42 path
= path
.replace('//', '/')
45 parent_dir
= dirname(path
)
47 all_paths
.add(parent_dir
)
48 parent_dir
= dirname(parent_dir
)
52 def format_exception(e
):
53 exc_type
, exc_value
, exc_tb
= sys
.exc_info()
54 details
= traceback
.format_exception(exc_type
, exc_value
, exc_tb
)
55 details
= '\n'.join(map(core
.decode
, details
))
59 msg
= core
.decode(repr(e
))
64 """Subtracts list b from list a and returns the resulting list."""
65 # conceptually, c = a - b
76 def grep(pattern
, items
, squash
=True):
77 """Greps a list for items that match a pattern
79 :param squash: If only one item matches, return just that item
80 :returns: List of matching items
83 isdict
= isinstance(items
, dict)
84 if pattern
in __grep_cache
:
85 regex
= __grep_cache
[pattern
]
87 regex
= __grep_cache
[pattern
] = re
.compile(pattern
)
91 match
= regex
.match(item
)
94 groups
= match
.groups()
96 subitems
= match
.group(0)
101 subitems
= list(groups
)
103 matchdict
[item
] = items
[item
]
105 matched
.append(subitems
)
109 elif squash
and len(matched
) == 1:
119 An os.path.basename() implementation that always uses '/'
121 Avoid os.path.basename because git's output always
122 uses '/' regardless of platform.
125 return path
.rsplit('/', 1)[-1]
129 """Strip one level of directory"""
130 return path
.strip('/').split('/', 1)[-1]
133 def dirname(path
, current_dir
=''):
135 An os.path.dirname() implementation that always uses '/'
137 Avoid os.path.dirname because git's output always
138 uses '/' regardless of platform.
142 path
= path
.replace('//', '/')
143 path_dirname
= path
.rsplit('/', 1)[0]
144 if path_dirname
== path
:
146 return path
.rsplit('/', 1)[0]
150 """Split paths using '/' regardless of platform"""
151 return path
.split('/')
155 """Join paths using '/' regardless of platform"""
156 return '/'.join(paths
)
160 """Return all of the path components for the specified path
162 >>> pathset('foo/bar/baz') == ['foo', 'foo/bar', 'foo/bar/baz']
167 parts
= splitpath(path
)
170 result
.append(prefix
+ part
)
176 def select_directory(paths
):
177 """Return the first directory in a list of paths"""
185 return os
.path
.dirname(paths
[0])
188 def strip_prefix(prefix
, string
):
189 """Return string, without the prefix. Blow up if string doesn't
190 start with prefix."""
191 assert string
.startswith(prefix
)
192 return string
[len(prefix
) :]
196 """Removes shell metacharacters from a string."""
197 for c
in """ \t!@#$%^&*()\\;,<>"'[]{}~|""":
198 s
= s
.replace(c
, '_')
202 def tablength(word
, tabwidth
):
203 """Return length of a word taking tabs into account
205 >>> tablength("\\t\\t\\t\\tX", 8)
209 return len(word
.replace('\t', '')) + word
.count('\t') * tabwidth
212 def _shell_split_py2(s
):
213 """Python2 requires bytes inputs to shlex.split(). Returns [unicode]"""
215 result
= shlex
.split(core
.encode(s
))
217 result
= core
.encode(s
).strip().split()
218 # Decode to unicode strings
219 return [core
.decode(arg
) for arg
in result
]
222 def _shell_split_py3(s
):
223 """Python3 requires unicode inputs to shlex.split(). Converts to unicode"""
225 result
= shlex
.split(s
)
227 result
= core
.decode(s
).strip().split()
234 # Encode before calling split()
235 values
= _shell_split_py2(s
)
237 # Python3 does not need the encode/decode dance
238 values
= _shell_split_py3(s
)
242 def tmp_filename(label
, suffix
=''):
243 label
= 'git-cola-' + label
.replace('/', '-').replace('\\', '-')
244 fd
= tempfile
.NamedTemporaryFile(prefix
=label
+ '-', suffix
=suffix
)
250 """Is this a linux machine?"""
251 return sys
.platform
.startswith('linux')
256 return os
.path
.exists('/usr/bin/apt-get')
260 """Return True on OSX."""
261 return sys
.platform
== 'darwin'
265 """Return True on win32"""
266 return sys
.platform
== 'win32' or sys
.platform
== 'cygwin'
269 def expandpath(path
):
270 """Expand ~user/ and environment $variables"""
271 path
= os
.path
.expandvars(path
)
272 if path
.startswith('~'):
273 path
= os
.path
.expanduser(path
)
278 """Operate on a collection of objects as a single unit"""
280 def __init__(self
, *members
):
281 self
._members
= members
283 def __getattr__(self
, name
):
284 """Return a function that relays calls to the group"""
286 def relay(*args
, **kwargs
):
287 for member
in self
._members
:
288 method
= getattr(member
, name
)
289 method(*args
, **kwargs
)
291 setattr(self
, name
, relay
)
296 """Wrap an object and override attributes"""
298 def __init__(self
, obj
, **overrides
):
300 for k
, v
in overrides
.items():
303 def __getattr__(self
, name
):
304 return getattr(self
._obj
, name
)
307 def slice_fn(input_items
, map_fn
):
308 """Slice input_items and call map_fn over every slice
310 This exists because of "errno: Argument list too long"
313 # This comment appeared near the top of include/linux/binfmts.h
314 # in the Linux source tree:
317 # * MAX_ARG_PAGES defines the number of pages allocated for arguments
318 # * and envelope for the new program. 32 should suffice, this gives
319 # * a maximum env+arg of 128kB w/4KB pages!
321 # #define MAX_ARG_PAGES 32
323 # 'size' is a heuristic to keep things highly performant by minimizing
324 # the number of slices. If we wanted it to run as few commands as
325 # possible we could call "getconf ARG_MAX" and make a better guess,
326 # but it's probably not worth the complexity (and the extra call to
327 # getconf that we can't do on Windows anyways).
329 # In my testing, getconf ARG_MAX on Mac OS X Mountain Lion reported
330 # 262144 and Debian/Linux-x86_64 reported 2097152.
332 # The hard-coded max_arg_len value is safely below both of these
335 # 4K pages x 32 MAX_ARG_PAGES
336 max_arg_len
= (32 * 4096) // 4 # allow plenty of space for the environment
337 max_filename_len
= 256
338 size
= max_arg_len
// max_filename_len
344 items
= copy
.copy(input_items
)
346 stat
, out
, err
= map_fn(items
[:size
])
348 status
= min(stat
, status
)
350 status
= max(stat
, status
)
355 return (status
, '\n'.join(outs
), '\n'.join(errs
))
359 def __init__(self
, sequence
):
362 def index(self
, item
, default
=-1):
364 idx
= self
.seq
.index(item
)
369 def __getitem__(self
, idx
):