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
|
1 |
|
program = CMD_PREFIX + ' '.join([name, *args]) |
19
|
1 |
|
if _show: |
20
|
1 |
|
common.show(program) |
21
|
|
|
else: |
22
|
1 |
|
log.debug(program) |
23
|
|
|
|
24
|
1 |
|
if name == 'cd': |
25
|
1 |
|
assert len(args) == 1, "'cd' takes a single argument" |
26
|
1 |
|
return os.chdir(args[0]) |
27
|
|
|
|
28
|
1 |
|
command = subprocess.run( |
|
|
|
|
29
|
|
|
[name, *args], |
30
|
|
|
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, |
31
|
|
|
universal_newlines=True, |
32
|
|
|
) |
33
|
1 |
|
for line in command.stdout.splitlines(): |
34
|
1 |
|
log.debug(OUT_PREFIX + line.strip()) |
35
|
|
|
|
36
|
1 |
|
if command.returncode == 0: |
37
|
1 |
|
return command.stdout.strip() |
38
|
|
|
|
39
|
1 |
|
elif _ignore: |
40
|
1 |
|
log.debug("Ignored error from call to '%s'", program) |
41
|
|
|
|
42
|
|
|
else: |
43
|
1 |
|
msg = ( |
44
|
|
|
"An external program call failed." + "\n\n" |
45
|
|
|
"In worikng directory: " + os.getcwd() + "\n\n" |
46
|
|
|
"Execution produced a non-zero return code:" + "\n\n" + |
47
|
|
|
program + "\n" + |
48
|
|
|
command.stdout |
49
|
|
|
) |
50
|
1 |
|
raise ShellError(msg) |
51
|
|
|
|
52
|
|
|
|
53
|
1 |
|
def mkdir(path): |
54
|
1 |
|
call('mkdir', '-p', path) |
55
|
|
|
|
56
|
|
|
|
57
|
1 |
|
def cd(path, _show=True): |
58
|
|
|
|
59
|
1 |
|
call('cd', path, _show=_show) |
60
|
|
|
|
61
|
|
|
|
62
|
1 |
|
def ln(source, target): |
63
|
1 |
|
dirpath = os.path.dirname(target) |
64
|
1 |
|
if not os.path.isdir(dirpath): |
65
|
1 |
|
mkdir(dirpath) |
66
|
1 |
|
call('ln', '-s', source, target) |
67
|
|
|
|
68
|
|
|
|
69
|
1 |
|
def rm(path): |
70
|
|
|
call('rm', '-rf', path) |
71
|
|
|
|
This check looks for calls to members that are non-existent. These calls will fail.
The member could have been renamed or removed.