]> glassweightruler.freedombox.rocks Git - waydroid.git/blob - tools/helpers/run.py
tools: Upver to 1.3.3
[waydroid.git] / tools / helpers / run.py
1 # Copyright 2021 Oliver Smith
2 # SPDX-License-Identifier: GPL-3.0-or-later
3 import shlex
4 import tools.helpers.run_core
5
6
7 def flat_cmd(cmd, working_dir=None, env={}):
8 """
9 Convert a shell command passed as list into a flat shell string with
10 proper escaping.
11
12 :param cmd: command as list, e.g. ["echo", "string with spaces"]
13 :param working_dir: when set, prepend "cd ...;" to execute the command
14 in the given working directory
15 :param env: dict of environment variables to be passed to the command, e.g.
16 {"JOBS": "5"}
17 :returns: the flat string, e.g.
18 echo 'string with spaces'
19 cd /home/pmos;echo 'string with spaces'
20 """
21 # Merge env and cmd into escaped list
22 escaped = []
23 for key, value in env.items():
24 escaped.append(key + "=" + shlex.quote(value))
25 for i in range(len(cmd)):
26 escaped.append(shlex.quote(cmd[i]))
27
28 # Prepend working dir
29 ret = " ".join(escaped)
30 if working_dir:
31 ret = "cd " + shlex.quote(working_dir) + ";" + ret
32
33 return ret
34
35
36 def user(args, cmd, working_dir=None, output="log", output_return=False,
37 check=None, env={}, sudo=False):
38 """
39 Run a command on the host system as user.
40
41 :param env: dict of environment variables to be passed to the command, e.g.
42 {"JOBS": "5"}
43
44 See tools.helpers.run_core.core() for a detailed description of all other
45 arguments and the return value.
46 """
47 # Readable log message (without all the escaping)
48 msg = "% "
49 for key, value in env.items():
50 msg += key + "=" + value + " "
51 if working_dir:
52 msg += "cd " + working_dir + "; "
53 msg += " ".join(cmd)
54
55 # Add environment variables and run
56 if env:
57 cmd = ["sh", "-c", flat_cmd(cmd, env=env)]
58 return tools.helpers.run_core.core(args, msg, cmd, working_dir, output,
59 output_return, check, sudo)
60
61
62 def root(args, cmd, working_dir=None, output="log", output_return=False,
63 check=None, env={}):
64 """
65 Run a command on the host system as root, with sudo.
66
67 :param env: dict of environment variables to be passed to the command, e.g.
68 {"JOBS": "5"}
69
70 See tools.helpers.run_core.core() for a detailed description of all other
71 arguments and the return value.
72 """
73 if env:
74 cmd = ["sh", "-c", flat_cmd(cmd, env=env)]
75 cmd = ["sudo"] + cmd
76
77 return user(args, cmd, working_dir, output, output_return, check, env,
78 True)