xref: /llvm-project/lldb/examples/customization/pwd-cd-and-system/utils.py (revision 2238dcc39358353cac21df75c3c3286ab20b8f53)
1"""Utility for changing directories and execution of commands in a subshell."""
2
3import os
4import shlex
5import subprocess
6
7# Store the previous working directory for the 'cd -' command.
8
9
10class Holder:
11    """Holds the _prev_dir_ class attribute for chdir() function."""
12
13    _prev_dir_ = None
14
15    @classmethod
16    def prev_dir(cls):
17        return cls._prev_dir_
18
19    @classmethod
20    def swap(cls, dir):
21        cls._prev_dir_ = dir
22
23
24def chdir(debugger, args, result, dict):
25    """Change the working directory, or cd to ${HOME}.
26    You can also issue 'cd -' to change to the previous working directory."""
27    new_dir = args.strip()
28    if not new_dir:
29        new_dir = os.path.expanduser("~")
30    elif new_dir == "-":
31        if not Holder.prev_dir():
32            # Bad directory, not changing.
33            print("bad directory, not changing")
34            return
35        else:
36            new_dir = Holder.prev_dir()
37
38    Holder.swap(os.getcwd())
39    os.chdir(new_dir)
40    print("Current working directory: %s" % os.getcwd())
41
42
43def system(debugger, command_line, result, dict):
44    """Execute the command (a string) in a subshell."""
45    args = shlex.split(command_line)
46    process = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
47    output, error = process.communicate()
48    retcode = process.poll()
49    if output and error:
50        print("stdout=>\n", output)
51        print("stderr=>\n", error)
52    elif output:
53        print(output)
54    elif error:
55        print(error)
56    print("retcode:", retcode)
57