]> scripts.mit.edu Git - wizard.git/blobdiff - wizard/command/__init__.py
Use CLI installer for MediaWiki 1.17.0 and later.
[wizard.git] / wizard / command / __init__.py
index e4de0cfaa38ab7e4fd33c3ea8c3618e10cbd5052..8d5e14c3c434b922db807dffc7214c4ceb4aab0c 100644 (file)
@@ -9,30 +9,18 @@ import shutil
 import cStringIO
 
 import wizard
-from wizard import util
+from wizard import util, shell
 
-logging_setup = False
-
-def boolish(val):
-    """
-    Parse the contents of an environment variable as a boolean.
-    This recognizes more values as ``False`` than :func:`bool` would.
+def chdir_to_production():
+    if os.path.exists(".git/WIZARD_UPGRADE_VERSION"): # XXX do something more robust
+        util.chdir(shell.eval("git", "config", "remote.origin.url"))
+        return True
+    return False
 
-        >>> boolish("0")
-        False
-        >>> boolish("no")
-        False
-        >>> boolish("1")
-        True
-    """
-    try:
-        return bool(int(val))
-    except (ValueError, TypeError):
-        if val == "No" or val == "no" or val == "false" or val == "False":
-            return False
-        return bool(val)
+logging_setup = False
+debug = True # This will get overwritten with the real value early on
 
-def makeLogger(options, numeric_args):
+def setup_logger(options, numeric_args):
     global logging_setup
     if logging_setup: return logging.getLogger()
     logger = logging.getLogger()
@@ -40,23 +28,22 @@ def makeLogger(options, numeric_args):
     logger.setLevel(logging.INFO)
     stderr = logging.StreamHandler(sys.stderr)
     stderr.setFormatter(logging.Formatter('%(levelname)s: %(message)s'))
-    if not options.quiet: logger.addHandler(stderr)
-    else: logger.addHandler(NullLogHandler()) # prevent default
-    if options.log_file: addFileLogger(options.log_file, options.debug)
+    if not options.quiet:
+        logger.addHandler(stderr)
+    else:
+        logger.addHandler(NullLogHandler()) # prevent default
+    if options.log_file:
+        setup_file_logger(options.log_file, options.debug)
     if options.debug:
         logger.setLevel(logging.DEBUG)
     else:
         stderr.setLevel(logging.WARNING)
         if options.verbose:
             stderr.setLevel(logging.INFO)
-    def our_excepthook(type, value, tb):
-        logging.error("".join(traceback.format_exception(type,value,tb)))
-        sys.exit(1)
-    sys.excepthook = our_excepthook
     logging_setup = True
     return logger
 
-def addFileLogger(log_file, debug):
+def setup_file_logger(log_file, debug):
     logger = logging.getLogger()
     file = logging.FileHandler(log_file)
     logformatter = logging.Formatter("%(asctime)s %(levelname)s: %(message)s", "%Y-%m-%d %H:%M")
@@ -66,7 +53,7 @@ def addFileLogger(log_file, debug):
         file.setLevel(logging.INFO)
     return file
 
-def makeBaseArgs(options, **grab):
+def make_base_args(options, **grab):
     """Takes parsed options, and breaks them back into a command
     line string that we can pass into a subcommand"""
     args = []
@@ -89,6 +76,8 @@ def security_check_homedir(location):
     This protects against malicious mountpoints, and is roughly equivalent
     to the suexec checks.
     """
+    # XXX: this is a smidge unfriendly to systems who haven't setup
+    # nswitch.
     try:
         uid = util.get_dir_uid(location)
         real = os.path.realpath(location)
@@ -128,63 +117,6 @@ def create_logdir(log_dir):
         #    # XXX: update last symlink
     os.chmod(log_dir, 0o777)
 
-class Report(object):
-    #: Set of indices that should be skipped
-    skip = None
-    def __init__(self, names, fobjs, skip):
-        self.skip = skip
-        for name, fobj in zip(names, fobjs):
-            setattr(self, name, fobj)
-
-def report_files(log_dir, names):
-    return [os.path.join(os.path.join(log_dir, "%s.txt" % x)) for x in names]
-
-def read_reports(log_dir, names):
-    """
-    Reads a number of reports files.  The return value is a :class:`Report`
-    object with attributes that are open file objects that correspond to ``names``.
-    """
-    return Report(names, [(os.path.exists(f) and open(f, "r") or cStringIO.StringIO()) for f in report_files(log_dir, names)], set())
-
-def open_reports(log_dir, names=('warnings', 'errors'), redo=False, append_names=()):
-    """
-    Returns a :class:`Report` object configured appropriately for the
-    parameters passed.  This object has attributes names + append_names which
-    contain file objects opened as "w".  ``names`` report files are cleared unconditionally
-    when they are opened (i.e. are not preserved from run to run.)  ``append_names``
-    report files are not cleared unless ``redo`` is True, and persist over
-    runs: assuming the convention that [0001] is the index of the deployment,
-    the ``skip`` attribute on the returned report object contains indexes that
-    should be skipped.
-    """
-    skip = set()
-    if not redo:
-        rr = read_reports(log_dir, append_names)
-        def build_set(skip, fobj):
-            skip |= set(int(l[1:5]) for l in fobj.read().splitlines())
-            fobj.close()
-        for name in append_names:
-            build_set(skip, getattr(rr, name))
-    else:
-        names += append_names
-        append_names = ()
-    files = report_files(log_dir, names)
-    append_files = report_files(log_dir, append_names)
-    # backup old reports
-    old_reports = os.path.join(log_dir, "old-reports")
-    rundir = os.path.join(old_reports, "run")
-    if not os.path.exists(old_reports):
-        os.mkdir(old_reports)
-    else:
-        util.safe_unlink(rundir)
-    for f in files:
-        if os.path.exists(f):
-            os.rename(f, rundir)
-    for f in append_files:
-        if os.path.exists(f):
-            shutil.copy(f, rundir)
-    return Report(names + append_names, [open(f, "w") for f in files] + [open(f, "a") for f in append_files], skip)
-
 class NullLogHandler(logging.Handler):
     """Log handler that doesn't do anything"""
     def emit(self, record):
@@ -192,23 +124,33 @@ class NullLogHandler(logging.Handler):
 
 class WizardOptionParser(optparse.OptionParser):
     """Configures some default user-level options"""
+    store_help = False
     def __init__(self, *args, **kwargs):
         kwargs["add_help_option"] = False
+        if "store_help" in kwargs:
+            self.store_help = kwargs["store_help"]
+            del kwargs["store_help"]
         optparse.OptionParser.__init__(self, *args, **kwargs)
-    def parse_all(self, argv):
-        self.add_option("-h", "--help", action="help", help=optparse.SUPPRESS_HELP)
+    def parse_all(self, *args, **kwargs):
+        if self.store_help:
+            self.add_option("-h", "--help", action="store_true", default=False, dest="help", help=optparse.SUPPRESS_HELP)
+        else:
+            self.add_option("-h", "--help", action="help", help=optparse.SUPPRESS_HELP)
         group = optparse.OptionGroup(self, "Common Options")
         group.add_option("-v", "--verbose", dest="verbose", action="store_true",
-                default=boolish(os.getenv("WIZARD_VERBOSE")), help="Turns on verbose output.  Envvar is WIZARD_VERBOSE")
+                default=util.boolish(os.getenv("WIZARD_VERBOSE")), help="Turns on verbose output.  Envvar is WIZARD_VERBOSE")
         group.add_option("--debug", dest="debug", action="store_true",
-                default=boolish(os.getenv("WIZARD_DEBUG")), help="Turns on debugging output.  Envvar is WIZARD_DEBUG")
+                default=util.boolish(os.getenv("WIZARD_DEBUG")), help="Turns on debugging output.  Envvar is WIZARD_DEBUG")
         group.add_option("-q", "--quiet", dest="quiet", action="store_true",
-                default=boolish(os.getenv("WIZARD_QUIET")), help="Turns off output to stdout. Envvar is WIZARD_QUIET")
+                default=util.boolish(os.getenv("WIZARD_QUIET")), help="Turns off output to stdout. Envvar is WIZARD_QUIET")
         group.add_option("--log-file", dest="log_file", metavar="FILE",
-                default=None, help="Logs verbose output to file")
+                default=os.getenv("WIZARD_LOGFILE"), help="Logs verbose output to file")
+        group.add_option("--directory", dest="directory", metavar="PATH",
+                default=os.getenv("WIZARD_DIRECTORY", ".wizard"), help="Initialize this folder to store metadata.")
         self.add_option_group(group)
-        options, numeric_args = self.parse_args(argv)
-        makeLogger(options, numeric_args)
+        options, numeric_args = self.parse_args(*args, **kwargs)
+        setup_logger(options, numeric_args)
+        debug = options.debug
         # we're going to process the global --log-dir/--seen dependency here
         if hasattr(options, "seen") and hasattr(options, "log_dir"):
             if not options.seen and options.log_dir: