Debian Codegraph @

tasks/_inv/shell.py

raw symbols SCIP
1 # -*- coding: ascii -*-
2 #
3 # Copyright 2007 - 2025
4 # Andr\xe9 Malo or his licensors, as applicable
5 #
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
17 """
18 =================
19 Shell utilities
20 =================
21
22 Shell utilities.
23 """
24 from __future__ import absolute_import
25
26 __author__ = "Andr\xe9 Malo"
27
28 import contextlib as _contextlib
29 import errno as _errno
30 import fnmatch as _fnmatch
31 import functools as _ft
32 import glob as _glob
33 import os as _os
34 import re as _re
35 import shutil as _shutil
36 import sys as _sys
37 import tempfile as _tempfile
38
39 from . import util as _util
40
41 root = _os.path.dirname(
42 _os.path.dirname(_os.path.dirname(_os.path.abspath(__file__)))
43 )
44
45
46 @_contextlib.contextmanager
47 def root_dir():
48 """ Context manager to change into the root directory """
49 assert root is not None
50
51 old = _os.getcwd()
52 try:
53 _os.chdir(root)
54 yield root
55 finally:
56 _os.chdir(old)
57
58
59 def _make_split_command():
60 """
61 Make split_command function
62
63 The command splitter splits between tokens. Tokens are non-whitespace
64 sequences or double quoted strings. Inside those double quotes can be
65 escaped with a backslash. So have to be backslashes.
66
67 Stolen from <http://opensource.perlig.de/svnmailer/>.
68
69 Returns:
70 callable: Parser for generic commandlines
71 """
72 argre = r'[^"\s]\S*|"[^\\"]*(?:\\[\\"][^\\"]*)*"'
73 check = _re.compile(
74 r'\s*(?:%(arg)s)(?:\s+(?:%(arg)s))*\s*$' % dict(arg=argre)
75 ).match
76 split = _re.compile(argre).findall
77 strip = _ft.partial(_re.compile(r'\\([\\"])').sub, r'\1')
78
79 def split_command(command): # pylint: disable = redefined-outer-name
80 """
81 Split generic commandline into single arguments
82
83 The command splitter splits between tokens. Tokens are non-whitespace
84 sequences or double quoted strings. Inside those double quotes can be
85 escaped with a backslash. So have to be backslashes.
86
87 Stolen from <http://opensource.perlig.de/svnmailer/>.
88
89 Parameters:
90 command (str or iterable):
91 The command string to split. If it's not a string, it's taken as a
92 generic iterable and returned as a list.
93
94 Returns:
95 list: Command splitted parts
96 """
97 if not isinstance(command, _util.basestring_):
98 return list(command)
99
100 if not check(command):
101 raise ValueError("Invalid command string %r" % (command,))
102
103 return [
104 strip(arg[1:-1]) if arg.startswith('"') else arg
105 for arg in split(command)
106 ]
107
108 return split_command
109
110 split_command = _make_split_command() # noqa
111
112
113 def _make_formatter(*args, **kwargs):
114 """
115 Make args / kwargs formatter
116
117 Either args or kwargs or neither of them can be set. There cannot be set
118 both of them.
119
120 Returns:
121 callable: Formatter, using either args or kwargs
122 """
123 # pylint: disable = no-else-return
124
125 assert not (args and kwargs)
126
127 if args:
128 # tuples are given for the whole command string but applied per token.
129 # We need to supply only the tuples which are needed for the current
130 # token.
131 args = list(args[::-1])
132 pcents = _re.compile(r'%[^%]').findall
133
134 def formatter(value):
135 """ Tuple formatter """
136 count = len(pcents(value))
137 torepl = []
138 while len(torepl) < count:
139 torepl.append(args.pop())
140 return value % tuple(torepl)
141 return formatter
142
143 elif kwargs:
144 return lambda x: x % kwargs
145
146 return lambda x: x
147
148
149 def _make_win32_command():
150 r"""
151 Make win32_command function
152
153 >>> x = win32_command(r'''
154 ... command arg "arg 2" "" "arg %3"
155 ... "malic'ious argument\\\"&whoami"
156 ... ''')
157 >>> print(x[:42])
158 command arg ^"arg^ 2^" ^"^" ^"arg^ ^%3^" ^
159 >>> print(x[41:])
160 ^"malic'ious^ argument\\\^"^&whoami^"
161
162 """
163 wsp, meta = r'\r\n\t\x0b\x0c\x08 ', r'()%!^"<>&|'
164 slashsub = _ft.partial(_re.compile(r'(\\+)("|$)').sub, r'\1\1\2')
165 metasub = _ft.partial(_re.compile(r'([%s%s])' % (wsp, meta)).sub, r'^\1')
166 qsearch = _re.compile(r'[%s"]' % (wsp,)).search
167 needq = lambda x: not x or qsearch(x) # noqa pylint: disable = unnecessary-lambda-assignment
168
169 def win32_command(command, *args, **kwargs):
170 """
171 Return a win32/cmd.exe suitable commandline
172
173 :See: https://blogs.msdn.microsoft.com/twistylittlepassagesallalike/
174 2011/04/23/everyone-quotes-command-line-arguments-the-wrong-way/
175
176 Either args or kwargs or neither of them can be set. There cannot be
177 set both of them.
178
179 Parameters:
180 command (str):
181 Generic commandline, possibly containing substitutions, filled by
182 args or kwargs. See `split_command` for generic commandline
183 syntax.
184
185 *args:
186 Substitution positional arguments
187
188 **kwargs
189 Substitution keyword arguments
190
191 Returns:
192 str: Strictly quoted shell commandline for ``cmd.exe``
193 """
194 # pylint: disable = redefined-outer-name
195 return ' '.join([metasub(
196 '"%s"' % (slashsub(token).replace('"', '\\"'),)
197 if needq(token) else token
198 ) for token in map(_make_formatter(*args, **kwargs),
199 split_command(command))])
200
201 return win32_command
202
203 win32_command = _make_win32_command() # noqa
204
205
206 def _make_posix_command():
207 r"""
208 Make posix_command function
209
210 >>> x = posix_command(r'''
211 ... command arg "arg 2" "" "arg $3"
212 ... "malic'ious argument\\\"&whoami"
213 ... ''')
214 >>> print(x)
215 command arg 'arg 2' '' 'arg $3' 'malic'\''ious argument\"&whoami'
216
217 """
218 qsearch = _re.compile(r'[^a-zA-Z\d_./-]').search
219 needq = lambda x: not x or qsearch(x) # noqa pylint: disable = unnecessary-lambda-assignment
220
221 def posix_command(command, *args, **kwargs):
222 """
223 Return a POSIX shell suitable commandline
224
225 Either args or kwargs or neither of them can be set. There cannot be
226 set both of them.
227
228 Parameters:
229 command (str):
230 Generic commandline, possibly containing substitutions, filled by
231 args or kwargs. See `split_command` for generic commandline
232 syntax.
233
234 *args:
235 Substitution positional arguments
236
237 **kwargs
238 Substitution keyword arguments
239
240 Returns:
241 str: Strictly quoted shell commandline for POSIX shells
242 """
243 # pylint: disable = redefined-outer-name
244 return ' '.join([
245 "'%s'" % (token.replace("'", "'\\''")) if needq(token) else token
246 for token in map(_make_formatter(*args, **kwargs),
247 split_command(command))
248 ])
249 return posix_command
250
251 posix_command = _make_posix_command() # noqa
252
253 command = win32_command if _sys.platform.lower() == 'win32' else posix_command
254
255
256 def native(path):
257 """
258 Convert slash path to native
259
260 Parameters:
261 path (str):
262 Path relative to the checkout root
263
264 Returns:
265 str: The native path
266 """
267 path = _os.path.sep.join(path.split('/'))
268 return _os.path.normpath(_os.path.join(root, path))
269
270
271 def relative(path):
272 """
273 Convert native path into root-relative
274
275 Parameters:
276 path (str):
277 Path relative to the checkout root
278
279 Returns:
280 str: The relative path - with slashes
281 """
282 return "/".join(pathparts(_os.path.relpath(native(path), native(root))))
283
284
285 def cp(src, dest):
286 """
287 Copy src to dest
288
289 Parameters:
290 src (str):
291 Source path, relative to the checkout root
292
293 dest (str):
294 Dest path, relative to the checkout root
295 """
296 _shutil.copy2(native(src), native(dest))
297
298
299 def cp_r(src, dest, ignore=None):
300 """
301 Copy -r src to dest
302
303 Parameters:
304 src (str):
305 Source path, relative to the checkout root
306
307 dest (str):
308 Dest path, relative to the checkout root
309
310 ignore (callable):
311 Ignore callback
312 """
313 _shutil.copytree(native(src), native(dest), ignore=ignore)
314
315
316 def rm(*dest):
317 """
318 Remove one or more files, ENOENT is not considered an error
319
320 Parameters:
321 *dest:
322 Files to remove
323 """
324 if len(dest) == 1 and not isinstance(dest[0], _util.basestring_):
325 dest = dest[0]
326
327 for name in dest:
328 try:
329 _os.unlink(native(name))
330 except OSError as e:
331 if _errno.ENOENT != e.errno:
332 raise
333
334
335 def rm_rf(*dest):
336 """
337 Remove one or more trees
338
339 :Parameters:
340 *dest:
341 Paths to remove
342 """
343 if len(dest) == 1 and not isinstance(dest[0], _util.basestring_):
344 dest = dest[0]
345
346 for name in dest:
347 name = native(name)
348 if _os.path.islink(name):
349 _os.unlink(name)
350
351 elif _os.path.isfile(name):
352 rm(name)
353
354 elif _os.path.exists(name):
355 for path in files(name, '*'):
356 if not _os.path.islink(native(path)):
357 _os.chmod(native(path), 0o644)
358 _shutil.rmtree(name)
359
360
361 def mkdir_p(*dirnames):
362 """
363 Create one or more directories
364
365 Parameters:
366 *dirnames:
367 Directory names (the leaf directory)
368 """
369 if len(dirnames) == 1 and not isinstance(dirnames[0], _util.basestring_):
370 dirnames = dirnames[0]
371
372 for dirname in dirnames:
373 try:
374 _os.makedirs(dirname)
375 except OSError as e:
376 # makedirs throws OSError if the last dir segment exists
377 if e.errno != _errno.EEXIST:
378 raise
379
380
381 mkstemp = _tempfile.mkstemp
382 walk = _os.walk
383
384
385 def glob(*pattern, **kwargs):
386 """
387 glob(*pattern, prune=None, prune_base=('.git', '.svn', 'CVS')):
388
389 Find files or directories with glob pattern (python 3.6+)
390
391 Parameters:
392 *pattern:
393 Glob to match against
394
395 prune (iterable):
396 List of directory basenames to ignore.
397 Default: None. Can be empty or ``None`` (meaning not to prune anything
398 except prune_base)
399
400 prune_base (iterable):
401 Extra list of directory basenames to ignore.
402 Default: ('.git', '.svn', 'CVS'). Can be empty or ``None`` (meaning
403 not to prune anything except prune)
404
405 Returns:
406 iterable: Iterator over matching pathnames
407 """
408 for single in pattern:
409 # pylint: disable = use-yield-from
410 for item in _glob_single(single, **kwargs):
411 yield item
412
413
414 def glob_escape(value):
415 """
416 Escape string for use in glob pattern (python 3.6+)
417
418 Parameters:
419 value (str):
420 value to escape
421
422 Returns:
423 str: The escaped value
424 """
425 return _glob.escape(value)
426
427
428 def _glob_single(pattern, prune=None, prune_base=('.git', '.svn', 'CVS')):
429 """
430 Find files or directories with glob pattern (python 3.6+)
431
432 Parameters:
433 pattern (str):
434 Glob to match against
435
436 prune (iterable):
437 List of directory basenames to ignore.
438 Default: None. Can be empty or ``None`` (meaning not to prune anything
439 except prune_base)
440
441 prune_base (iterable):
442 Extra list of directory basenames to ignore.
443 Default: ('.git', '.svn', 'CVS'). Can be empty or ``None`` (meaning
444 not to prune anything except prune)
445
446 Returns:
447 iterable: Iterator over matching pathnames
448 """
449 normroot = native(root + "/")
450 pattern = _os.path.join(_glob.escape(normroot), pattern)
451 toprune = set(prune or ()) | set(prune_base or ())
452
453 for found in _glob.iglob(pattern, recursive=True):
454 assert found.startswith(normroot)
455 parts = pathparts(found[len(normroot):])
456 if set(parts) & toprune:
457 continue
458 yield "/".join(parts)
459
460
461 def pathparts(path):
462 """
463 Return path parts
464
465 If the path ends with a slash the last part will be an empty string
466
467 Parameters:
468 path (str):
469 The path to split into parts
470
471 Returns:
472 list: The path parts
473 """
474 aslist = []
475 head, tail = _os.path.split(path)
476 if not tail:
477 aslist.append(tail)
478 head, tail = _os.path.split(head)
479 while tail:
480 aslist.append(tail)
481 head, tail = _os.path.split(head)
482 aslist.reverse()
483 return aslist
484
485
486 def files(base, wildcard='[!.]*', recursive=1, prune=None,
487 prune_base=('.git', '.svn', 'CVS')):
488 """
489 Determine a filelist
490
491 Parameters:
492 base (str):
493 Base path to start from
494
495 wildcard (str):
496 Glob to match against
497
498 recursive (bool):
499 Deep walk into the tree? Default: true
500
501 prune (iterable):
502 List of directory basenames to ignore.
503 Default: None. Can be empty or ``None`` (meaning not to prune anything
504 except prune_base)
505
506 prune_base (iterable):
507 Extra list of directory basenames to ignore.
508 Default: ('.git', '.svn', 'CVS'). Can be empty or ``None`` (meaning
509 not to prune anything except prune)
510
511 Returns:
512 iterable: Iterator over matching pathnames
513 """
514 prune = tuple(prune_base or ()) + tuple(prune or ())
515 for dirpath, dirnames, filenames in walk(native(base)):
516 for item in prune:
517 if item in dirnames:
518 dirnames.remove(item)
519
520 filenames.sort()
521 for name in _fnmatch.filter(filenames, wildcard):
522 dest = _os.path.join(dirpath, name)
523 if dest.startswith(root):
524 dest = dest.replace(root, '', 1)
525 yield '/'.join(pathparts(dest))
526
527 if not recursive:
528 break
529 dirnames.sort()
530
531
532 def dirs(base, wildcard='[!.]*', recursive=1, prune=None,
533 prune_base=('.git', '.svn', 'CVS')):
534 """
535 Determine a directory list
536
537 Parameters:
538 base (str):
539 Base path to start from
540
541 wildcard (str):
542 Glob to match against
543
544 recursive (bool):
545 Deep walk into the tree? Default: true
546
547 prune (iterable):
548 List of directory basenames to ignore.
549 Default: None. Can be empty or ``None`` (meaning not to prune anything
550 except prune_base)
551
552 prune_base (iterable):
553 Extra list of directory basenames to ignore.
554 Default: ('.git', '.svn', 'CVS'). Can be empty or ``None`` (meaning
555 not to prune anything except prune)
556
557 Returns:
558 iterable: Iterator over matching pathnames
559 """
560 prune = tuple(prune_base or ()) + tuple(prune or ())
561 for dirpath, dirnames, _ in walk(native(base)):
562 for item in prune:
563 if item in dirnames:
564 dirnames.remove(item)
565
566 dirnames.sort()
567 for name in _fnmatch.filter(dirnames, wildcard):
568 dest = _os.path.join(dirpath, name)
569 if dest.startswith(root):
570 dest = dest.replace(root, '', 1)
571 yield '/'.join(pathparts(dest))
572
573 if not recursive:
574 break
575
576
577 def frompath(executable):
578 """
579 Find executable in PATH
580
581 Parameters:
582 executable (str):
583 Command to search for
584
585 Returns:
586 str: Full path or ``None``
587 """
588 # Based on distutils.spawn.find_executable.
589 path = _os.environ.get('PATH', '')
590 paths = [
591 _os.path.expanduser(item)
592 for item in path.split(_os.pathsep)
593 ]
594 ext = _os.path.splitext(executable)[1]
595 exts = ['']
596 if _sys.platform == 'win32' or _os.name == 'os2':
597 eext = ['.exe', '.bat', '.py']
598 if ext not in eext:
599 exts.extend(eext)
600
601 for ext in exts:
602 if not _os.path.isfile(executable + ext):
603 for path in paths:
604 fname = _os.path.join(path, executable + ext)
605 if _os.path.isfile(fname):
606 # the file exists, we have a shot at spawn working
607 return fname
608 else:
609 return executable + ext
610
611 return None