1"""Utility for changing directories and execution of commands in a subshell."""
2from __future__ import print_function
3
4import os
5import shlex
6import subprocess
7
8# Store the previous working directory for the 'cd -' command.
9
10
11class Holder:
12    """Holds the _prev_dir_ class attribute for chdir() function."""
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(
47        args,
48        stdout=subprocess.PIPE,
49        stderr=subprocess.PIPE)
50    output, error = process.communicate()
51    retcode = process.poll()
52    if output and error:
53        print("stdout=>\n", output)
54        print("stderr=>\n", error)
55    elif output:
56        print(output)
57    elif error:
58        print(error)
59    print("retcode:", retcode)
60