# Part of the A-A-P recipe executive: process the command line arguments.

# 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

import os
import os.path

import Global
from Node import Node
from Error import *
from Dictlist import dictlist2str, varname2dictlist
from Process import Process, recipe_error
from ParsePos import ParsePos
from RecPos import rpcopy, RecPos
from Util import *
from Depend import Depend, depend_auto
from Remote import url_time
from VersCont import fetch_nodelist
from Cache import local_name
from Sign import get_old_sign, get_new_sign, sign_clear, sign_clear_target
from Sign import sign_updated, buildcheckstr2sign, buildcheck_updated
from Sign import check_name
from Commands import expand, do_fetch_all, do_verscont_all, do_remove_add,\
	do_publish_all, do_revise_all, aap_do
from Message import *
from DoRead import goto_dir
from Work import setrpstack, getwork
from DoArgs import local_arg, error_continue


def dictlist2shellstr(list, key):
    """Turn a dictlist into a string that can be used as an argument for a
       shell command.
       TODO: let this depend on the type of shell used.
       """
    str = ''
    for i in list:
	if str:
	    str = str + ' '
	for c in i[key]:
	    if string.find("'\" \t", c) >= 0:
		str = str + "\\"
	    str = str + c
    return str


def exec_commands(dep, recdict, target):
    """Execute the build commands "dep.commands" to build the Node "target",
       using the info in the Depend object "dep"."""
    work = getwork(recdict)

    # Go to the build directory, unless the dependency is from a startup file.
    cwd = None
    if not dep.startup:
	cwd = os.getcwd()
	goto_dir(recdict, dep.builddir)

    # Use the copy of the recdict that target_update() created, to avoid the
    # commands modify them.
    new_recdict = dep.use_recdict

    # Set the variables $source, $target and the like.
    new_recdict["buildtarget"] = target.get_name()
    dl = shorten_dictlist(dep.targetlist)
    work.add_node_attributes(dl)
    xp = Expand(1, Expand.quote_aap)
    new_recdict["target"] = dictlist2str(dl, xp)
    new_recdict["target_list"] = map(lambda x : x["name"], dl)
    new_recdict["target_dl"] = dl

    # Get the list of dependencies.
    dl = shorten_dictlist(dep.sourcelist)
    work.add_node_attributes(dl)
    new_recdict["depend"] = dictlist2str(dl, xp)
    new_recdict["depend_list"] = map(lambda x : x["name"], dl)
    new_recdict["depend_dl"] = dl

    # Get the list of sources, omit virtual dependencies.
    sl = filter(lambda x : not x["_node"].attributes.get("virtual"), dl)
    new_recdict["source"] = dictlist2str(sl, xp)
    new_recdict["source_list"] = map(lambda x : x["name"], sl)
    new_recdict["source_dl"] = sl

    new_recdict["match"] = dep.matchstr

    # Add "var_XXX" attributes from dependencies to set the "XXX" variable.
    for s in dl:
	for k in s.keys():
	    if len(k) > 4 and k[:4] == "var_":
		new_recdict[k[4:]] = s[k]

    # Create a ParsePos object to contain the parse position in the string.
    # Make a copy of the RecPos stack, so that the item on top can be
    # changed.  Set the line number to just before where the commands were
    # defined.
    fp = ParsePos(rpcopy(dep.rpstack, dep.rpstack[-1].line_nr - 1),
						     string = dep.commands)
    #
    # Parse and execute the commands.
    #
    Process(fp, new_recdict)

    # Move the exported variables to the recdict of the current recipe AND to
    # the recdict of the recipe where the dependency was defined.
    exports = new_recdict["_exports"]
    for e in exports.keys():
	recdict[e] = exports[e]
	if dep.buildrecdict and dep.buildrecdict != recdict:
	    dep.buildrecdict[e] = exports[e]

    # Destroy the dictionary to free up used space (and it's not supposed to be
    # used again).
    dep.use_recdict = None

    # Go back to the directory we came from.
    if cwd:
	goto_dir(recdict, cwd)


def get_bdir(recdict):
    """Get the value of $BDIR as an absolute path and ending in '/'."""
    bd = os.path.abspath(get_var_val(0, recdict, "BDIR"))
    if bd[-1] != '/':
	bd = bd + '/'
    return bd

def remove_bdir(recdict, name, bdir = None, remove = 1):
    """When "name" starts with $BDIR or part of it, return what follows.
       When "remove" is zero returns the $BDIR part that matched.
       Otherwise return None.
       "name" must be an absolute path. "bdir" must end in a slash."""
    if bdir:
	bd = bdir
    else:
	bd = get_bdir(recdict)

    # Compare with $BDIR and then remove each "-variant" part.  The last
    # compare will be against "build/".
    while 1:
	i = len(bd)
	if len(name) > i and name[:i] == bd:
	    if remove:
		return name[i:]
	    return bd
	i = string.rfind(bd, '-')
	if i < 0:
	    break
	bd = bd[:i] + '/'
    return None


class Update:
    """Objects used to remember which source of a dependencey is outdated and
    the newest time for "newer"."""
    def __init__(self):
	self.forced = Global.cmd_args.options.get("force")
				    # {force} used on target or source
	self.time = 0		    # oldest timestamp found
	self.time_source = ''	    # source that has older timestamp
	self.source = ''	    # source that has outdated signature
	self.buildcheck = ''	    # buildcheck signature
	self.newsig = 0		    # no old signature known

    def outdated(self, target):
	"""Return TRUE if we already know that updating is required.
	   This doesn't handle a source being newer than the target."""
	return (self.forced
		or self.time
		or self.source
		or (target.attributes.get("virtual")
		    and not target.attributes.get("remember")))

    def set_buildcheck(self, recdict, str, target, level):
	"""Set the buildcheck signature from string "str" for target "target".
	   Check if it's different from the last time."""
	buildcheck = buildcheckstr2sign(str)
	self.buildcheck = buildcheck

	# Only need to do the check if not updating already.
	if not self.outdated(target):
	    # building is to be done if the signature differs.
	    # With "--contents" we don't build for a changed buildcheck.
	    old = get_old_sign(recdict, "", "buildcheck", target)
	    if not old:
		self.newsig = 1
	    if self.buildcheck != old:
		if Global.cmd_args.options.get("contents"):
		    msg_depend(recdict, _('Buildcheck for "%s" changed, ignored because of --contents option') % target.short_name(), level)
		else:
		    self.source = "buildcheck"
		    # DEBUG
		    # msg_extra(recdict, 'build commands: "%s"' % str)

    def upd_reason(self, dst_time, target):
	"""Check if "target" needs to be updated.  "dst_time" is the timestamp
	   of the target."""
	# If a target is older than any source or one of the targets in the
	# dependency doesn't exist: execute the commands.
	if self.forced:
	    if Global.cmd_args.options.get("force"):
		reason = _('-F or --force command line argument')
	    elif self.source:
		reason = (_('"%s" has force attribute')
						   % shorten_name(self.source))
	    else:
		reason = (_('target "%s" has force attribute')
							 % target.short_name())
	elif (target.attributes.get("virtual")
		and not target.attributes.get("remember")
		and (not self.source or self.source == 'buildcheck')):
	    # the buildcheck for a virtual target isn't stored, thus its
	    # signature will always be different (new).
	    reason = _('virtual target')
	elif self.source:
	    if self.newsig:
		reason = _('no old signature for "%s"') % shorten_name(self.source)
	    else:
		reason = _('"%s" has changed') % shorten_name(self.source)
	elif dst_time < self.time:
	    reason = _('"%s" is newer') % self.time_source
	elif dst_time == 0 and not target.attributes.get("virtual"):
	    reason = _("it doesn't exist")
	else:
	    reason = ''
	return reason


# Values for "done" below.
build_done_NOT = 0	# updating not done yet
build_done_OK = 1	# updating done OK
build_done_IGNORE = 2	# updating skipped
build_done_ERROR = 3	# updating failed

def dictlist_update(dictlist, work, recdict, alt_recdict, target, update,
					   rule, autodepend = 1, level = None):
    """Go over all items in dictlist "dictlist" and update them.
       Skip the "target" node (avoid files that depend on itself).
       Find out if an item is outdated, using "update".
       When "rule" is non-zero, use $SRCPATH.
       "recdict" is the normal namespace to get variables for, "alt_recdict" is
       an alternate space ($BDIR might be different there) or None.
       When "autodepend" is zero don't check for automatic dependencies.
       Returns the dictlist of nodes that have been updated.  This is
       "dictlist" with automatic dependencies added."""
    # Make sure there is a node for each item in "dictlist".
    dictlist2depnodelist(work, dictlist)
    retlist = []

    # Get the value of $BDIR now for speed.
    bdir = get_bdir(recdict)
    if alt_recdict:
	alt_bdir = get_bdir(alt_recdict)
    else:
	alt_bdir = None

    # Increas the level, if given.
    if level:
	nlevel = level + 1
    else:
	nlevel = None

    from Remote import is_url
    from Dictlist import str2dictlist

    for src_dict in dictlist:
	# For an absolute path use the source name literally, otherwise use
	# $SRCPATH to locate the source.
	# However, need to add the directory for a child recipe.
	src = src_dict["name"]
	src_isabs = os.path.isabs(src)
	if not src_isabs and src_dict.has_key("_node"):
	    src = src_dict["_node"].short_name()

	def expand_srcpath(recdict, isabs, name, dict):
	    """Expand "name" into a list of names using $SRCPATH.  The
	       "srcpath" attribute in "dict" overrules $SRCPATH."""
	    if not isabs:
		if dict.has_key("srcpath"):
		    srcpath = str2dictlist([], dict["srcpath"])
		else:
		    srcpath = varname2dictlist(recdict, "SRCPATH")
	    if isabs or not srcpath:
		names = [ name ]
	    else:
		names = []
		for i in srcpath:
		    names.append(os.path.join(i["name"], name))
	    return names

	names = expand_srcpath(recdict,
				     (src_isabs or is_url(src)), src, src_dict)
	if rule:
	    # When "src" starts with "$BDIR/" also try without it.
	    src_abs = os.path.abspath(src)
	    src_no_bdir = remove_bdir(recdict, src_abs, bdir)
	    if not src_no_bdir and alt_bdir:
		src_no_bdir = remove_bdir(recdict, src_abs, alt_bdir)
	    if src_no_bdir:
		names.extend(expand_srcpath(recdict, 0, src_no_bdir, src_dict))

	# Loop over all possible locations for this "src".
	done = build_done_NOT
	for src_name in names:
	    # Remove "./" things (from $SRCPATH)
	    src_name = os.path.normpath(src_name)

	    node = work.get_node(src_name, 1, src_dict)

	    # Ignore a source that depend on itself.
	    if node == target:
		msg_depend(recdict,
				  _('Target depends on itself (ignored): "%s"')
						  % target.short_name(), level)
		done = build_done_IGNORE
		break

	    # Check if we skip updating this item.
	    if node.attributes.get("update") == "no":
		done = build_done_OK
		break

	    # Try updating the item.  If it works we use it.
	    else:
		res = target_update(work, recdict, node, level = nlevel)
		if res == updated_OK:
		    done = build_done_OK
		    # TRICK: fix the dependency to use this node
		    src_dict["name"] = node.get_name()
		    src_dict["_node"] = node
		    break
		if res == updated_ERROR:
		    done = build_done_ERROR
		# For updated_FAIL we try another source.
	
	if done == build_done_IGNORE:
	    continue	# skip source equal to target

	if done == build_done_NOT:
	    msg = _('Do not know how to build "%s"')
	elif done == build_done_ERROR:
	    msg = _('Building "%s" FAILED')
	else:
	    msg = None
	
	if msg:
	    msg = msg % shorten_name(src)
	    if error_continue():
		# Ignoring errors: continue with further targets.
		# Remember building this target failed, any other targets
		# that depend on it will also fail.
		target.status = Node.builderror
		msg_error(recdict, msg)
	    else:
		# Quit building at the first error.
		raise UserError, msg

	# Find automatic dependencies for this item.  If there are any, also
	# update them (recursively!) and append them to the return value (so
	# that signatures are stored when building succeeds.
	# Don't do this if "autodepend" is zero (items were generated by a
	# recursive autodepend).
	# Do this on the global node, not the item in the dictlist, to re-use
	# dependencies also used in other dictlists.
	# Avoid endless recursion by setting did_auto_depend.
	if (autodepend and not node.did_auto_depend
				       and not node.attributes.get("virtual")):
	    # If "target" starts with (part of) $BDIR set the depdir attribute
	    # to it.  Useful if some variant isn't used for the directory.
	    # When "src" starts with "$BDIR/" also try without it.
	    if not node.attributes.has_key("depdir"):
		bdir = remove_bdir(recdict, target.get_name(), bdir, 0)
		if not bdir and alt_bdir:
		    bdir = remove_bdir(recdict, target.get_name(), alt_bdir, 0)
		if bdir:
		    node.attributes["depdir"] = bdir

	    depend_auto(work, recdict, node, nlevel)
	    if node.auto_depend:
		node.did_auto_depend = 1
		slist = dictlist_update(node.auto_depend, work, recdict, None,
					 target, update, rule,
					 autodepend = not node.auto_depend_rec,
					 level = nlevel)
		node.did_auto_depend = 0
		retlist.extend(slist)

	# Check if the target needs updating because item "src_dict" is
	# outdated.
	check_need_update(recdict, update, src_dict, target)

    # Make the list of nodes after adjusting for the item actually used in the
    # source path or after removing $BDIR.
    retlist.extend(dictlist2depnodelist(work, dictlist))

    # Return the list of items that were updated.
    return retlist


def check_need_update(recdict, update, src_dict, target, rootname = None):
    """Check if node "target" needs to be updated by checking the source
       "src_dict".
       "update" is the Update object used for the target.
       "rootname" is used for publishing: the target name without the publish
       attribute, used for the "--contents" option."""
    # Only need to do the check if not updating already.  Saves a bit of time
    # in computing signatures (although they might have to be computed anyway
    # to be able to remember them).
    if target.status != Node.builderror and not update.outdated(target):
	virtual = 0
	if src_dict.has_key("_node"):
	    node = src_dict["_node"]
	    src_name = node.get_name()
	    virtual = node.attributes.get("virtual")
	else:
	    src_name = os.path.normpath(src_dict["name"])

	# The "force" attribute forces updating always.
	# A virtual target used as a source causes updating as well.
	if src_dict.get("force"):
	    update.forced = 1
	    update.source = src_name
	elif virtual:
	    update.source = src_name
	else:
	    check = check_name(src_name, src_dict)
	    if check == "newer":
		c = "time"		# "newer" check also uses timestamp
	    else:
		c = check
		if rootname and Global.cmd_args.options.get("contents"):
		    # When publishing and the "--contents" option is used,
		    # obtain the most recent signature for any destination.
		    old = get_old_sign(recdict, src_name, c, target,
							   rootname = rootname)
		else:
		    old = get_old_sign(recdict, src_name, c, target)
	    new = get_new_sign(recdict, src_name, c)
	    if new == '' or new == '0':
		raise (UserError, _('Cannot compute signature for "%s"')
								    % src_name)
	    # Update update.time or update.source:
	    # If it's -1 we already know building is to be done.
	    # If the check is "newer" need to find the newest timestamp.
	    # For other checks building is to be done if the sign differs.
	    if check == "newer":
		t = long(new)
		if update.time == 0 or t > update.time:
		    update.time = t
		    update.time_source = src_name
	    else:
		if not old:
		    update.newsig = 1
		if new != old:
		    update.source = src_name


def buildcheck_update(recdict, checkstring, dep, target, update, level):
    """Check if the "checkstring" value changed since the last build and
       change "update" accordingly.  "dep.commands" are the commands for the
       build rule."""
    # If the "buildcheck" attribute is empty, don't check if it changed.
    i = skip_white(checkstring, 0)
    if i >= len(checkstring):
	update.buildcheck = ''
	return

    # No need to compute the buildcheck for a virtual target, it's not used or
    # stored anyway.  Speeds up the big build block that ":mkdownload"
    # generates.
    if (target.attributes.get("virtual")
				    and not target.attributes.get("remember")):
	update.buildcheck = ''
	return

    line_nr = dep.rpstack[-1].line_nr
    setrpstack(recdict, dep.rpstack)

    # To take into account changes in the commands of an action, need to
    # replace "do action file" by the commands for the action.
    from Action import action_expand_do
    commands = action_expand_do(recdict, dep.commands,
						dep.targetlist, dep.sourcelist)

    # Remove comments.
    i = 0
    cl = len(commands)
    while i < cl:
	s = skip_white(commands, i)
	e = string.find(commands, '\n', s)
	if e < 0:
	    e = cl - 1
	if commands[s] == '#':
	    cl = cl - (e + 1 - i)
	    commands = commands[:i] + commands[e + 1:]
	else:
	    i = e + 1

    # Remove the values for $source and $target, the dependency takes care of
    # changes in these and their values are unpredictable.
    save = {}
    saved = ["source", "target", "fname"]
    for k in saved:
	save[k] = recdict.get(k)
	if not save[k] is None:
	    del recdict[k]

    # Use "var_xxx" attributes from source files, they overrule variables.
    work = getwork(recdict)
    for s in dep.sourcelist:
	node = work.find_node(s["name"])
	if node:
	    for k in node.attributes.keys():
		if len(k) > 4 and k[:4] == "var_":
		    save[k] = recdict.get(k)
		    recdict[k[4:]] = node.attributes[k]
	for k in s.keys():
	    if len(k) > 4 and k[:4] == "var_":
		save[k] = recdict.get(k)
		recdict[k[4:]] = s[k]

    # Always compute the check signature, it either needs to be compared (not
    # outdate yet) or stored (when outdated already).
    # Only set the value of $xcommands when it's used, it takes some time and
    # may fail.
    recdict["commands"] = commands
    xp = Expand(0, Expand.quote_aap, skip_errors = 1)
    if string.find(checkstring, "xcommands") > 0:
	recdict["xcommands"] = expand(line_nr, recdict,
						 commands, xp, skip_errors = 1)
    check_str = expand(line_nr, recdict, checkstring, xp, skip_errors = 1)
    del recdict["commands"]
    if recdict.has_key("xcommands"):
	del recdict["xcommands"]

    for k in saved:
	if save[k] is None:
	    if recdict.has_key(k):
		del recdict[k]
	else:
	    recdict[k] = save[k]

    # Collapse spans of white space into a single space.  Items like $LIBS may
    # have irrelevant trailing spaces.  Leading white space may be relevant
    # though, keep it.
    # TODO: how about white space inside quotes?
    str = ''
    i = 0
    leading = 1
    check_str_len = len(check_str)
    while i < check_str_len:
	s = i
	c = check_str[i]
	while ((c == ' ' or c == '\t')
		and i + 1 < check_str_len
		and (check_str[i + 1] == ' ' or
		    check_str[i + 1] == '\t' or check_str[i + 1] == '\n')):
	    i = i + 1
	if not leading:
	    s = i
	e = i + 1
	while (e < check_str_len and check_str[e] != ' '
						     and check_str[e] != '\t'):
	    e = e + 1
	str = str + check_str[s:e]
	i = e
	leading = (str[-1] == '\n')

    update.set_buildcheck(recdict, str, target, level)


def target_rule(work, recdict, target, update, src_list_list, level):
    """Find rules that match "target" and do the work for each of them.
       "src_list_list" is extended for items that need their sign updated.
       Returns a dependency made out of a rule with build commands or None
    """
    #
    # No specific dependency is defined for this target:
    # - Find all matching rules and update their sources.  Remember the
    #   newest timestamp.
    # - Find a matching rule with commands and create a dependency from
    #   that.
    #
    target_name = target.get_name()
    target_sname = target.short_name()
    dep = None

    buildrule = None	# Fully matching build rule or has more than
			    # one source.
    buildrule_len = 0	# length of matching pattern
    buildrule_p = None	# Potential build rule, use when there is no
			    # full match.
    buildrule_p_len = 0	# length of matching pattern of buildrule_p
    double = 0		# set when more than one matching rule found
    double_p = 0		# set when more than one potentitial rule found

    for r in work.rules:
	matchstr, dir, matchlen = r.match_target(target_name, target_sname)
	if matchstr:
	    src_list = r.target2sourcelist(target_name, target_sname)
	    # Skip rules where the target and source are equal.
	    # Happens for ":rule %.jpg : path/%.jpg".
	    if len(src_list) == 1 and src_list[0]["name"] == target_name:
		continue

	    # Check if all the sources exist.
	    # When not, only remember it as a potential buildrule.
	    full_match = 1
	    for s in src_list:
		e = os.path.exists(s["name"])
		if not e:
		    # Try removing $BDIR.
		    n = remove_bdir(recdict, os.path.abspath(s["name"]))
		    if n:
			e = os.path.exists(n)
		if not e:
		    # TODO: Should check if this source can be build from
		    # other rules or dependencies.
		    # TODO: remote files
		    full_match = 0
		    break

	    if r.commands:
		# Remember the rule with the longest matching pattern.
		if full_match:
		    if buildrule and matchlen == buildrule_len:
			double = 1
		    if matchlen > buildrule_len:
			buildrule = r
			buildrule_len = matchlen
			double = 0
		else:
		    if buildrule_p and matchlen == buildrule_p_len:
			double_p = 1
		    if matchlen > buildrule_p_len:
			buildrule_p = r
			buildrule_p_len = matchlen
			double_p = 0
	    elif full_match:
		# Matching rule but no commands, need to update it
		msg_depend(recdict, _('Using rule "%s : %s" for target "%s"')
				% (dictlist2str(r.targetlist,
					      Expand(0, Expand.quote_aap)),
				   dictlist2str(r.sourcelist,
					      Expand(0, Expand.quote_aap)),
				   target_sname), level)
		target.current_rule = r
		slist = dictlist_update(src_list, work, recdict,
			      r.buildrecdict, target, update, 1, level = level)
		target.current_rule = None
		src_list_list.append(slist)

    # Give an error when more than one fully matching rule found or when
    # there is no matching rule and more then one potential rule found.
    if double or (not buildrule and double_p):
	raise UserError, (_('More than one matching build rule for "%s"')
								% target_sname)
    if not buildrule and buildrule_p:
	# Didn't find a fully matching rule, use the potential one.
	buildrule = buildrule_p

    if buildrule:
	msg_depend(recdict, _('Using build rule "%s : %s" for target "%s"')
			% (dictlist2str(buildrule.targetlist,
						  Expand(0, Expand.quote_aap)),
			   dictlist2str(buildrule.sourcelist,
						  Expand(0, Expand.quote_aap)),
			   target_sname), level)

	# Create a dependency to be executed with may_exec_depend().
	# The build directory is set to ".", which means to use the directory
	# where the rule was invoked from.
	src_list = buildrule.target2sourcelist(target_name, target_sname)
	dep = Depend(buildrule.target2targetlist(target_name, target_sname),
			buildrule.build_attr,
			src_list,
			work,
			buildrule.rpstack,
			buildrule.commands,
			".",
			buildrule.buildrecdict)
	dep.matchstr, dir, matchlen = buildrule.match_target(target_name,
							      target_sname)

	# Apply attributes from the rule to the target.  Must be before
	# dictlist_update(), because the "virtual" attribute may influence
	# what happens there (e.g., location of sign file).
	for d in dep.targetlist:
	    if d["name"] == target_name:
		target.set_attributes(d)

	# Update sources for this build rule.
	target.current_rule = buildrule
	slist = dictlist_update(src_list, work, recdict,
					buildrule.buildrecdict, target, update,
							      1, level = level)
	target.current_rule = None
	src_list_list.append(slist)

    return dep


def get_build_recdict(recdict, buildrecdict):
    """Make a copy of the recdict to avoid the commands modify them.
       Delete the variables that are local to the recipe.
       Add the items from "buildrecdict": the recdict of the recipe where the
       action was defined."""
    new_recdict = recdict.copy()
    if recdict.has_key("_locals"):
	for k in recdict["_locals"].keys():
	    if new_recdict.has_key(k):
		del new_recdict[k]

    # When the build commands were defined in a child recipe, the local
    # variables there need to be used.  Local variables of the child recipe
    # overrule variables from the caller.  For a dependency the recipe
    # variables overrule variables from the caller, unless they were exported.
    if buildrecdict and buildrecdict != recdict:
	for k in buildrecdict.keys():
	    if (not new_recdict.has_key(k)
		    or (((buildrecdict.has_key("_locals")
				and buildrecdict["_locals"].has_key(k))
			    or (buildrecdict.has_key("_assigned")
				and buildrecdict["_assigned"].has_key(k)))
			and (not buildrecdict.has_key("_globals")
			    or not buildrecdict["_globals"].has_key(k)))):
		new_recdict[k] = buildrecdict[k]

    init_build_recdict(new_recdict)

    return new_recdict


def init_build_recdict(recdict):
    """Init a few items in a recdict to be used for building."""
    recdict["_exports"] = {}
    recdict["_globals"] = {}
    recdict["_locals"] = {}
    recdict["_assigned"] = {}

# return values for target_update():
updated_OK = 1	    # updating worked.
updated_FAIL = 0    # don't know how to update the target.
updated_ERROR = -1  # error while executing commands.

def target_update(work, recdict, target, toplevel = 0, force = 0, level = None):
    """Update a target by finding the build rule for it and executing the build
       commands if it's outdated.
       "target" is a Node object.
       If "toplevel" is non-zero it is an error not to have build commands.
       Return a non-zero number for success."""
    retval = updated_OK

    # The "comment" target is a special case.
    if target.name == "comment":
	work.print_comments()
	return retval

    # Return right away if this target was already updated.
    if target.status is Node.updated and not force:
	# This message is left out, because it clogs the log file with remarks
	# about header files.
	# msg_depend(recdict, _('Target was already updated: "%s"')
	#				    % target.short_name(), level)
	return retval

    # Don't try updating a target that failed previously.
    if target.status is Node.builderror:
	msg_depend(recdict, _('skip updating target "%s": previously failed')
						  % target.short_name(), level)
	return updated_ERROR

    if force:
	msg_depend(recdict, _('updating target "%s" forcefully')
						  % target.short_name(), level)
    else:
	msg_depend(recdict, _('updating target "%s"')
						  % target.short_name(), level)

    # Check if we are trying to recursively update ourselves.
    if target.status is Node.busy:
	if target.current_rule:
	    rpstack = target.current_rule.rpstack
	    where = ' from rule'
	elif target.current_dep:
	    rpstack = target.current_dep.rpstack
	    where = ' from dependency'
	else:
	    where = ''
	if where:
	    where = where + (_(' in recipe "%s" line %d')
				     % (rpstack[-1].name, rpstack[-1].line_nr))

	if target.attributes.get("recursive"):
	    target.recursive_level = target.recursive_level + 1
	    if target.recursive_level > int(target.attributes.get("recursive")):
		raise UserError, (_('Cyclic dependency exceeds %d levels for "%s"%s')
		    % (target.recursive_level - 1, target.short_name(), where))
	else:
	    raise UserError, (_('Cyclic dependency for "%s"%s')
						% (target.short_name(), where))
    else:
	target.recursive_level = 1

    # Increase the build level.
    if level:
	nlevel = level + 1
    else:
	nlevel = None

    target.status = Node.busy
    target_name = target.get_name()
    target_sname = target.short_name()

    # save "virtual" attribute, it is restored after done with this dependency.
    save_virtual = target.attributes.get("virtual")

    # Use an Update object to remember if any of the sources for this target is
    # outdated, thus we need to build the target.
    # For the "newer" check we need to find the newest timestamp of the
    # sources, update.time is set to the timestamp of the item.
    # For other checks we compare with a previous signature.  If outdated,
    # update.source is set to the name of the outdated source.
    update = Update()
    if force or target.attributes.get("force"):
	update.forced = 1

    # Remember which lists of sources need to have their signatures updated
    # when building succeeds.
    src_list_list = []

    # Go over all specified dependencies that have this target in their target
    # list and update their sources.  Also find the newest timestamp.
    for dep in target.get_dependencies():
	msg = (_('Using dependency "%s : %s"')
			    % (dictlist2str(dep.targetlist,
						  Expand(1, Expand.quote_aap)),
			       dictlist2str(dep.sourcelist,
						  Expand(1, Expand.quote_aap))))
	if len(dep.targetlist) > 1:
	    msg = msg + _(' for target "%s"') % target_sname
	msg_depend(recdict, msg, nlevel)

	# The recdict to be used for the build commands is also used for
	# checking the dependencies.  This means the $BDIR of the child recipe
	# is used when necessary.
	dep.use_recdict = get_build_recdict(recdict, dep.buildrecdict)

	# Go to the build directory, so that auto-dependencies are stored in
	# the right AAPDIR directory ($BDIR is only valid in the directory of
	# the child recipe).  Don't do this for startup dependencies.
	cwd = None
	if not dep.startup:
	    cwd = os.getcwd()
	    goto_dir(recdict, dep.builddir)

	target.current_dep = dep
	slist = dictlist_update(dep.sourcelist, work, dep.use_recdict, recdict,
					      target, update, 0, level = nlevel)
	target.current_dep = None
	src_list_list.append(slist)

	# Go back to the directory we came from.
	if cwd:
	    goto_dir(recdict, cwd)

    # If there is a dependency with commands rules are not applied.
    dep = target.get_first_build_dependency()
    dirmode = target.isdir()

    # If there is no dependency and the target is not a directory:
    # 1. Find a # matching rule
    # 2. Fetch the file
    if not dep and not dirmode:
	# 1. Find matching rules.
	#    One with build commands is turned into a dependency.
	dep = target_rule(work, recdict, target, update, src_list_list, nlevel)
	if dep:
	    dep.use_recdict = get_build_recdict(recdict, dep.buildrecdict)
	else:
	    # 2. Fetch the file
	    #    If the target doesn't exist and has the "fetch" attribute, try
	    #    fetching it.  This may use a cached file.
	    if (not os.path.exists(target_name)
				     and target.attributes.has_key("fetch")):
		if target.current_rule:
		    rpstack = target.current_rule.rpstack
		elif target.current_dep:
		    rpstack = target.current_dep.rpstack
		else:
		    rpstack = []
		fetch_nodelist(rpstack, recdict, [ target ], 1)
	    if target.attributes.get("virtual"):
		msg_depend(recdict,
			_('Virtual target has no build commands: "%s"')
							 % target_sname, level)
		# This is an error if there are no sources.
		if not src_list_list:
		    retval = updated_FAIL
	    elif toplevel or not os.path.exists(target_name):
		msg_depend(recdict,
			     _('Do not know how to build "%s"')
							 % target_sname, level)
		retval = updated_FAIL
	    else:
		msg_depend(recdict,
			   _('Target has no build commands and exists: "%s"')
							 % target_sname, level)

    #
    # If there is a dependency with build commands, execute it.
    #
    if dep:
	# the "finally" and "fetch" target may have multiple build commands
	deplist = target.get_build_dependencies()
	if not deplist:
	    deplist = [ dep ]
	for d in deplist:
	    # Execute the dependency commands if the target is outdated.
	    may_exec_depend(recdict, d, update, target, src_list_list, level)

    elif dirmode:
	# Target is a directory and has no specific build commands: create the
	# directory if it doesn't exist.
	if os.path.exists(target_name):
	    if not os.path.isdir(target_name):
		msg_warning(recdict,
			_('WARNING: Target is not a directory: "%s"')
								% target_sname)
	    else:
		msg_depend(recdict, _('Directory exists: "%s"')
							 % target_sname, level)
	else:
	    if skip_commands():
		msg_info(recdict, _('skip creating directory "%s"')
								 % target_name)
	    else:
		try:
		    import types

		    # If a mode like "0777" was specified, use it.
		    if (isinstance(dirmode, types.StringType)
							and dirmode[0] == '0'):
			os.makedirs(target_name, oct2int(dirmode))
		    else:
			os.makedirs(target_name)
		    msg_info(recdict, _('Created directory: "%s"')
								 % target_name)
		except EnvironmentError, e:
		    recipe_error([], (_('Could not create directory "%s"')
						       % target_name) + str(e))

    elif target.name == "fetch":
	# Automatically fetch all nodes with an "fetch" attribute.
	if do_fetch_all([], recdict, {}):
	    retval = updated_OK
	else:
	    retval = updated_ERROR
    elif target.name == "publish":
	# Automatically publish all nodes with a "publish" attribute.
	# It worked when an empty list is returned.
	if not do_publish_all([], recdict, {}):
	    retval = updated_OK
	else:
	    retval = updated_ERROR
    elif target.name == "commit":
	# Automatically commit all nodes with a "commit" attribute.
	if do_verscont_all([], recdict, "commit", {}):
	    retval = updated_OK
	else:
	    retval = updated_ERROR
    elif target.name == "checkout":
	# Automatically checkout all nodes with a "commit" attribute.
	if do_verscont_all([], recdict, "checkout", {}):
	    retval = updated_OK
	else:
	    retval = updated_ERROR
    elif target.name == "checkin":
	# Automatically checkin all nodes with a "commit" attribute.
	if do_verscont_all([], recdict, "checkin", {}):
	    retval = updated_OK
	else:
	    retval = updated_ERROR
    elif target.name == "unlock":
	# Automatically unlcok all nodes with a "commit" attribute.
	if do_verscont_all([], recdict, "unlock", {}):
	    retval = updated_OK
	else:
	    retval = updated_ERROR
    elif target.name == "add":
	# Automatically add new nodes with a "commit" attribute.
	if do_remove_add([], recdict, {}, local_arg(), "add"):
	    retval = updated_OK
	else:
	    retval = updated_ERROR
    elif target.name == "remove":
	# Automatically delete nodes without a "commit" attribute.
	if do_remove_add([], recdict, {}, local_arg(), "remove"):
	    retval = updated_OK
	else:
	    retval = updated_ERROR
    elif target.name == "tag":
	# Automatically tag nodes with a "commit" and "tag" attribute.
	if do_verscont_all([], recdict, "tag", {}):
	    retval = updated_OK
	else:
	    retval = updated_ERROR
    elif target.name == "revise":
	# Automatically checkin all nodes with a "commit" attribute.
	# Automatically delete nodes.
	if do_revise_all([], recdict, {}, local_arg()):
	    retval = updated_OK
	else:
	    retval = updated_ERROR
    elif target.name == "reference":
	# Generate or update the cross reference
	# TODO: check for errors
	aap_do(0, recdict, "reference $SOURCE $?INCLUDE")
	retval = updated_OK
    elif target.name == "refresh":
	# Nothing to do, refreshing will have been done by now.
	retval = updated_OK


    if retval == updated_OK:
	target.status = Node.updated
    elif retval == updated_ERROR:
	target.status = Node.builderror
    else:
	target.status = Node.new
    target.recursive_level = target.recursive_level - 1

    # restore "virtual" attribute
    if save_virtual is None:
	if target.attributes.has_key("virtual"):
	    del target.attributes["virtual"]
    else:
	target.attributes["virtual"] = save_virtual

    return retval


class DepNode:
    """Object to keep the node of a dependency with the attributes local to the
       dependency."""
    def __init__(self, node, dict):
	self.node = node
	self.attributes = dict


def dictlist2depnodelist(work, dictlist):
    """Turn the items in "dictlist" into DepNodes, return the result."""
    nl = []
    for item in dictlist:
	# for a dependency we know the node, need to find it for a rule 
	if item.has_key("_node"):
	    n = item["_node"]
	else:
	    n = work.get_node(item["name"], 1)
	nl.append(DepNode(n, item))
	if n.attributes.get("virtual") and item.get("remember"):
	    recipe_error([],
			_('Cannot use "remember" attribute on virtual node %s')
								% item["name"])
    return nl


def may_exec_depend(recdict, dep, update, target, src_list_list, level):
    """Execute the build commands of dependency "dep" if the target "target" is
       outdated.
       When updating succeeds, remember the signs for the items in
       "src_list_list".
       Return non-zero when building was done."""
    target_name = target.get_name()
    target_sname = target.short_name()

    # Get timestamp for the target.  If this fails it probably doesn't
    # exist and needs to be rebuild (dst_time will be zero).
    dst_time = url_time(recdict, target_name)
    if dst_time > 0 and target.attributes.get("virtual"):
	msg_warning(recdict,
			   _('Warning: target is virtual but does exist: "%s"')
							     % target_sname)

    # If a "buildcheck" attribute is defined for the build commands, check
    # if it has changed.  Otherwise check if the build commands changed.
    if dep.build_attr.has_key("buildcheck"):
	buildcheck = dep.build_attr["buildcheck"]
    else:
	buildcheck = "$xcommands"
    buildcheck_update(dep.use_recdict, buildcheck, dep, target, update, level)

    # Get the reason for building (if any).
    reason = update.upd_reason(dst_time, target)
    if reason:
	retval = 1
    else:
	retval = 0

    if target.status == Node.builderror:
	# Can't build this target, there were errors in the dependencies or
	# building failed previously.
	return retval

    if reason:
	if (Global.cmd_args.options.get("touch") and not Global.force_build):
	    # Skip standard virtual targets, they are always rebuild
	    if not target.name in Global.virtual_targets:
		msg_info(recdict, _('Touching "%s"') % target_sname)
	else:
	    msg_depend(recdict, _('Updating "%s" from "%s": %s')
							       % (target_sname,
		       dictlist2str(shorten_dictlist(dep.sourcelist)), reason),
							       level)

	# Skip when not actually building.
	if not skip_commands():
	    # Create $BDIR if "target" starts with it.  Use $BDIR from the
	    # recipe of the build commands if possible.
	    t = 0
	    if dep.buildrecdict:
		t = remove_bdir(dep.buildrecdict, target_name)
	    if t or remove_bdir(recdict, target_name):
		# Make sure the directory for target_name exists.
		aap_checkdir(dep.rpstack, recdict, target_name)

	# Execute the build commands.
	exec_commands(dep, recdict, target)

	# Skip when not actually building.
	if not skip_commands():
	    # Check that the target was really updated.  Only when it
	    # exists.
	    if dst_time > 0 and not target.attributes.get("virtual"):
		t = url_time(recdict, target_name)
		if t == 0:
		    raise UserError, _('Building failed for "%s"') % target_name
		# if t == dst_time:
		#   Could give an error here, but on fast machines it often
		#   happens while nothing is wrong.

    else:
	msg_depend(recdict, _('Target "%s" is up-to-date') % target_sname,
									 level)

    if reason or update.newsig:
	# Update the signatures for all targets.  We assume they were all
	# updated, even though the build commands may skip some or were not
	# executed at all.
	for trg in dep.targetlist:
	    # Can there be a target without a node???
	    if not trg.has_key("_node"):
		continue
	    node = trg["_node"]
	    # Skip standard virtual targets, they are always rebuild
	    if node.name in Global.virtual_targets:
		continue

	    # Target changed, clear its cached signatures.
	    sign_clear(node.get_name())

	    # Remember the signatures of the sources now.  Do this for sources
	    # that the target depends on.  Any old signatures for this target
	    # can be removed, they are invalid anyway.
	    # Don't do this with the --nobuild argument, unless --touch was
	    # used as well.
	    if (not Global.cmd_args.options.get("nobuild")
		    or Global.cmd_args.options.get("touch")
		    or Global.force_build):
		sign_clear_target(recdict, node)
		for l in src_list_list:
		    for dn in l:
			# Call check_name() again, because creating the item
			# may cause the filetype to change.
			if not dn.node.attributes.get("virtual"):
			    sign_updated(recdict, dn.node, dn.attributes, node)

		# Mark a node that is not the main target as have been updated
		if node != target:
		    node.status = Node.updated

		# Also remember the buildcheck signature.
		if update.buildcheck:
		    buildcheck_updated(recdict, node, update.buildcheck)

	    # The target has changed, need to redo the automatic dependencies.
	    node.auto_depend = None

    # Return non-zero if building was to be done.
    return retval


def autodepend_recurse(work, recdict, src_list, update, target, source):
    """Read an auto-dependency file and extract the source dependencies.  If
       "update" isn't None check for the sources to be outdated.  Add the
       sources to list of DepNodes "src_list"."""
    if source.auto_depend_rec and os.path.exists(target.get_name()):
	from Depend import read_auto_depend
	auto_dep = read_auto_depend(recdict, target, source.get_name())
	if auto_dep:
	    work.dictlist_nodes(auto_dep)
	    if update:
		for a in auto_dep:
		    check_need_update(recdict, update, a, target)
	    src_list.extend(dictlist2depnodelist(work, auto_dep))
	# Always store the result in the source Node.
	source.auto_depend = auto_dep


def build_autodepend(work, recdict, stype, source, level):
    """Find an autodepend rule to make a dependency recipe from an "stype" file.
       When a match is found execute the build commands for Node "target" from
       Node "source".
       Unlike using pattern rules, this does NOT update the source.
       Return the recipe node (it is already up-to-date)."""
    # Search all defined autodepends for one where stype matches.
    from Action import find_depend_action

    action = find_depend_action(stype)
    if not action:
	return 0	# Didn't find a matching autodepend.

    msg_depend(recdict, _('Using depend %s for source "%s"')
					 % (stype, source.short_name()), level)

    # Make the name for the recipe that contains the automatic dependencies for
    # this node: "$BDIR/node_directory/node_basename.aap".
    # A "depdir" attribute of the source node overrules $BDIR.
    d = source.attributes.get("depdir")
    if not d:
	d = get_var_val(0, recdict, "BDIR")
    recipe = work.get_node(os.path.join(d, source.short_name()) + ".aap", 1)

    # Use an Update object to remember if any of the sources for this target is
    # outdated, thus we need to build the target.
    update = Update()

    # Check the signature of the source.  Use the attributes from the
    # autodepend plus those from the source Node.
    src_dict = action.attributes.copy()
    src_dict["name"] = source.get_name()
    src_dict["_node"] = source
    for k in source.attributes.keys():
	src_dict[k] = source.attributes[k]
    check_need_update(recdict, update, src_dict, recipe)

    # Make sure the output directory exists.
    aap_checkdir(action.rpstack, recdict, recipe.get_name())

    # If the autodepend used the {recursive} attribute, need to carry this over
    # to the source node.
    if action.attributes.has_key("recursive"):
	source.auto_depend_rec = action.attributes["recursive"]
    else:
	source.auto_depend_rec = 0

    # If the recipe exists and was generated recursively, the recipe depends on
    # all files mentioned in it.  This makes sure that the dependencies are
    # updated when "foo.c" includes "common.h" and "common.h" was changed.
    src_list = dictlist2depnodelist(work, [ src_dict ])
    autodepend_recurse(work, recdict, src_list, update, recipe, source)

    # Create a dependency to be executed below.
    dep = Depend([ {"name" : recipe.get_name()} ],
		    action.attributes,
		    [ {"name" : source.get_name()} ],
		    work, action.rpstack,
		    action.commands)

    # make a copy of the recdict, removing local variables.
    dep.use_recdict = get_build_recdict(recdict, action.buildrecdict)

    # Also execute the commands for "--nobuild" and "--touch".
    Global.force_build = Global.force_build + 1

    # Execute the build commands of the dependency when the recipe is outdated.
    res = may_exec_depend(recdict, dep, update, recipe, [ src_list ], level)

    Global.force_build = Global.force_build - 1

    if res:
	# Now the list of dependencies may have changed.  Also store signatures
	# for newly discovered dependencies, otherwise the file will be build
	# again when executing the recipe the next time.
	new_src_list = []
	autodepend_recurse(work, recdict, new_src_list, None, recipe, source)
	for dn in new_src_list:
	    found = 0
	    for odn in src_list:
		if dn.node == odn.node:
		    found = 1
		    break
	    if not found:
		sign_updated(recdict, dn.node, dn.attributes, recipe)

    return recipe


def default_targets(work, recdict):
    """Decide what the default target(s) is/are for this recipe."""
    if recdict.get("TARGET"):
	# Use the targets from $TARGET.
	msg_depend(recdict, _('Building target(s) specified with $TARGET'))
	targets = varname2dictlist(recdict, "TARGET")
	for i in xrange(0, len(targets)):
	    targets[i] = work.get_node(targets[i]["name"], 0, targets[i])

    elif work.find_node("all", ""):
	# Use the "all" target.
	msg_depend(recdict, _('Building the "all" target'))
	targets = [ work.find_node("all", "") ]

    else:
	msg_info(recdict,
		   _('No target on the command line and no $TARGET or "all" target in a recipe'))
	targets = []

    return targets


def dobuild(work):
    """
    Build the specified targets.
    """

    #
    # Execute all the "-c command" arguments.
    #
    if Global.cmd_args.has_option("command"):
	cmdlist = Global.cmd_args.options.get("command")
    else:
	cmdlist = []
    for cmd in cmdlist:
	# Create a ParsePos object to contain the parse position in the string.
	# Make a new rpstack to be able to give useful error messages.
	fp = ParsePos([ RecPos(_('Command line argument "%s"') % cmd, 0) ],
							   string = cmd + '\n')
	# Parse and execute the commands.
	Process(fp, work.recdict)

    # if there is a "-c command" argument and no targets we are done.
    if cmdlist and not Global.cmd_args.targets:
	return


    #
    # Build the specified or default targets.
    #
    if Global.cmd_args.targets:
	# Targets specified as an argument.
	msg_depend(work.recdict,
			       _('Building targets specified on command line'))
	update_target = work.find_node("update", "")

	targets = []
	for t in Global.cmd_args.targets:
	    if t == "update" and (not update_target
					    or not update_target.dependencies):
		# An "update" target for which there is no explicit dependency
		# is turned into "fetch" and then build the default
		# target(s).
		msg_depend(work.recdict,
			 _('"update" builds "fetch" and the default target'))
		targets.append(work.get_node("fetch", ""))
		targets.extend(default_targets(work, work.recdict))
	    else:
		# Find an existing Node or create a new one.
		targets.append(work.get_node(t))
    
    else:
	targets = default_targets(work, work.recdict)

    # Update the toplevel targets.  Catch a ":quit" or ":exit" command.
    try:
	for target in targets:
	    res = target_update(work, work.recdict, target, 1, level = 1)
	    if res == updated_FAIL:
		msg = _('Do not know how to build "%s"')
	    elif res == updated_ERROR:
		msg = _('Building "%s" failed')
	    else:
		msg = None
	    if msg:
		msg = msg % target.short_name()
		if error_continue():
		    # Ignoring errors: continue with further targets.
		    # Remember building this target failed, any other targets
		    # that depend on it will also fail.
		    target.status = Node.builderror
		    msg_error(work.recdict, msg)
		else:
		    # Quit building at the first error.
		    raise UserError, msg

    except NormalExit:
	pass

    # Update the "finally" target if it exists.
    target = work.find_node("finally", "")
    if target:
	msg_depend(work.recdict, _('Building the "finally" target'))
	target_update(work, work.recdict, target, level = 1)


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