]> scripts.mit.edu Git - wizard.git/blob - lib/wizard/shell.py
More refactoring, fix broken wizard migrate.
[wizard.git] / lib / wizard / shell.py
1 import subprocess
2 import sys
3
4 class CalledProcessError(subprocess.CalledProcessError):
5     pass
6
7 class Shell(object):
8     """An advanced shell, with the ability to do dry-run and log commands"""
9     def __init__(self, logger = False, dry = False):
10         """ `logger`    The logger
11             `dry`       Whether or not to not run any commands, and just print"""
12         self.logger = logger
13         self.dry = dry
14     def call(self, *args):
15         if self.dry or self.logger:
16             self.logger.info("$ " + ' '.join(args))
17         if self.dry: return
18         proc = None
19         if self.logger:
20             if hasattr(self.logger, "verbose"):
21                 # this is a special short-circuit to make redrawing
22                 # output from Git work
23                 proc = subprocess.Popen(args, stdout=sys.stdout, stderr=sys.stderr)
24             else:
25                 proc = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
26         else:
27             proc = subprocess.Popen(args)
28         stdout, _ = proc.communicate()
29         if self.logger and stdout: self.logger.info(stdout)
30         if proc.returncode:
31             raise CalledProcessError(proc.returncode, args)
32