1
|
|
|
"""Utilities to call shell programs.""" |
2
|
|
|
|
3
|
1 |
|
import os |
4
|
1 |
|
import subprocess |
5
|
1 |
|
import logging |
6
|
|
|
|
7
|
1 |
|
from . import common |
8
|
1 |
|
from .exceptions import ShellError |
9
|
|
|
|
10
|
1 |
|
CMD_PREFIX = "$ " |
11
|
1 |
|
OUT_PREFIX = "> " |
12
|
|
|
|
13
|
1 |
|
log = logging.getLogger(__name__) |
14
|
|
|
|
15
|
|
|
|
16
|
1 |
|
def call(name, *args, _show=True, _ignore=False): |
17
|
|
|
"""Call a shell program with arguments. |
18
|
|
|
|
19
|
|
|
:param name: name of program to call |
20
|
|
|
:param args: list of command-line arguments |
21
|
|
|
:param _show: display the call on stdout |
22
|
|
|
:param _ignore: ignore non-zero return codes |
23
|
|
|
|
24
|
|
|
""" |
25
|
1 |
|
program = CMD_PREFIX + ' '.join([name, *args]) |
26
|
1 |
|
if _show: |
27
|
1 |
|
common.show(program) |
28
|
|
|
else: |
29
|
1 |
|
log.debug(program) |
30
|
|
|
|
31
|
1 |
|
if name == 'cd': |
32
|
1 |
|
return os.chdir(args[0]) # 'cd' has no effect in a subprocess |
33
|
|
|
|
34
|
1 |
|
command = subprocess.run( |
|
|
|
|
35
|
|
|
[name, *args], universal_newlines=True, |
36
|
|
|
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, |
37
|
|
|
) |
38
|
|
|
|
39
|
1 |
|
for line in command.stdout.splitlines(): |
40
|
1 |
|
log.debug(OUT_PREFIX + line.strip()) |
41
|
|
|
|
42
|
1 |
|
if command.returncode == 0: |
43
|
1 |
|
return command.stdout.strip() |
44
|
|
|
|
45
|
1 |
|
elif _ignore: |
46
|
1 |
|
log.debug("Ignored error from call to '%s'", program) |
47
|
|
|
|
48
|
|
|
else: |
49
|
1 |
|
message = ( |
50
|
|
|
"An external program call failed." + "\n\n" |
51
|
|
|
"In working directory: " + os.getcwd() + "\n\n" |
52
|
|
|
"The following command produced a non-zero return code:" + "\n\n" + |
53
|
|
|
program + "\n" + |
54
|
|
|
command.stdout |
55
|
|
|
) |
56
|
1 |
|
raise ShellError(message) |
57
|
|
|
|
58
|
|
|
|
59
|
1 |
|
def mkdir(path): |
60
|
1 |
|
call('mkdir', '-p', path) |
61
|
|
|
|
62
|
|
|
|
63
|
1 |
|
def cd(path, _show=True): |
64
|
1 |
|
call('cd', path, _show=_show) |
65
|
|
|
|
66
|
|
|
|
67
|
1 |
|
def ln(source, target): |
68
|
1 |
|
dirpath = os.path.dirname(target) |
69
|
1 |
|
if not os.path.isdir(dirpath): |
70
|
1 |
|
mkdir(dirpath) |
71
|
1 |
|
call('ln', '-s', source, target) |
72
|
|
|
|
73
|
|
|
|
74
|
1 |
|
def rm(path): |
75
|
|
|
call('rm', '-rf', path) |
76
|
|
|
|
This check looks for calls to members that are non-existent. These calls will fail.
The member could have been renamed or removed.