# Part of the A-A-P recipe executive: printing messages

# Copyright (C) 2002 Stichting NLnet Labs
# Permission to copy and use this file is specified in the file COPYING.
# If this file is missing you can find it here: http://www.a-a-p.org/COPYING


# All messages are written into a log file.
# Only selected messages are printed.

# It's OK to import * from this file.

import string
import os
import os.path

import Global
from Error import *

msgt_warning = "warning"	# warning message
msgt_error = "error"		# error message
msgt_system = "system"		# executed system command
msgt_result = "result"		# result of :sys command
msgt_info = "info"		# informational message
msgt_extra = "extra"		# extra informational message
msgt_changedir = "changedir"	# changing directories
msgt_depend = "depend"		# message about dependencies
msgt_all = "all"		# all messages
msgt_print = "print"		# :print message

# File for logging message.  Is opened only after the main recipe is located.
logfile = None

# Full path of the file used for logging.
logname = None

def msg_startlog(recdict):
    """Open the logfile.  Can only be done after locating the main recipe file
       and changing to it's directory."""
    # First need the "AAPDIR" directory.
    from Util import assert_aap_dir, in_aap_dir
    if not assert_aap_dir(recdict):
	return

    # Rename the old files if aap/log already exists.  log8 -> log9, log7 ->
    # log8, ..., log1 -> log2, log -> log1
    log_name = in_aap_dir("log")
    if os.path.exists(log_name):
	i = 8
	while i >= 0:
	    if i == 0:
		src = log_name
	    else:
		src = in_aap_dir("log%d" % i)
	    if os.path.exists(src):
		dst = in_aap_dir("log%d" % (i + 1))
		# May have to delete the destination file log9.
		if i == 8:
		    try:
			os.remove(dst)
		    except:
			pass
		try:
		    os.rename(src, dst)
		except StandardError, e:
		    print _('Warning: Could not rename "%s" to "%s"') % (src, dst)
		    break
	    i = i - 1

    # Open aap/log
    global logfile
    try:
	logfile = open(log_name, "w")
    except StandardError, e:
	print _("Warning: Cannot open log file for writing: "), str(e)
    else:
	# Turn into an absolute name, we may use chdir.
	global logname
	logname = os.path.abspath(log_name)


def msg_logname():
    """Return the name of the log file."""
    return logname


def msg_stoplog():
    """Stop using a logfile.  Used just before finishing the work."""
    global logfile, logname
    logfile.close()
    logfile = None
    logname = None


def msg_msg(recdict, msg, type):
    """Generic function to print a message "msg" of type "type".
       All messages are written in the log file (if it exists).
       A message is displayed if its type is in the MESSAGE variable."""
    if (not recdict
	    or recdict.get("MESSAGE") is None
	    or string.find(recdict["MESSAGE"], type) >= 0
	    or string.find(recdict["MESSAGE"], msgt_all) >= 0):
	print "Aap: " + msg
    msg_log(msg, type)

def msg_log(msg, type):
    if logfile:
	try:
	    logfile.write("%s:\t%s\n" % (type, msg))
	except IOError, e:
	    raise UserError, _('Error while writing to log file: ') + str(e)

def msg_warning(recdict, msg):
    """Print a warning message."""
    msg_msg(recdict, msg, msgt_warning)

def msg_error(recdict, msg):
    """Print an error message."""
    msg_msg(recdict, msg, msgt_error)

def msg_system(recdict, msg):
    """Print an executed system command."""
    if msg[-1] == '\n':
	msg = msg[:-1]	    # remove trailing newline
    msg_msg(recdict, msg, msgt_system)

def msg_result(recdict, msg):
    """Print an executed system command."""
    if msg[-1] == '\n':
	msg = msg[:-1]	    # remove trailing newline
    msg_msg(recdict, msg, msgt_result)

def msg_info(recdict, msg):
    """Print an informational message."""
    msg_msg(recdict, msg, msgt_info)

def msg_extra(recdict, msg):
    """Print an extra informational message."""
    msg_msg(recdict, msg, msgt_extra)

def msg_changedir(recdict, dir):
    """Print a message about changing directories."""
    # Note: This message is not translated, so that a parser
    # for the messages isn't confused by various languages.
    msg_msg(recdict, 'Entering directory "' + dir + '"', msgt_changedir)

def msg_depend(recdict, msg, level = None):
    """Print a message about dependencies."""
    if level:
	msg = ("%d - " % level) + msg
    msg_msg(recdict, msg, msgt_depend)

def msg_print(msg):
    """Print a message always, and log it."""
    print msg
    msg_log(msg, msgt_print)


def msg_init(recdict):
    """Set the MESSAGE variable according to the command line arguments.
       Skip this when it's already set from the command line."""
    if not recdict.has_key("MESSAGE"):
	if Global.cmd_args.has_option("silent"):
	    recdict["MESSAGE"] = msgt_error
	elif Global.cmd_args.has_option("verbose"):
	    recdict["MESSAGE"] = msgt_all
	else:
	    recdict["MESSAGE"] = (msgt_error + ","
					       + msgt_system + "," + msgt_info)

# vim: set sw=4 sts=4 tw=79 fo+=l:
