# Part of the A-A-P recipe executive: Python functions used in a recipe

# Copyright (C) 2002-2003 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

#
# These are Python functions available to the recipe.
# This means the arguments cannot be changed without causing incompatibilities!
#
# It's OK to do "from RecPython import *", these things are supposed to be
# global.
#

import os
import os.path
import sys

import import_re        # import the re module in a special way

import string
import tempfile

import Action
from Dictlist import str2dictlist, list2str, dictlist2str, listitem2str
from Dictlist import dictlist_expand, parse_attr
from Error import *
import Global
from Process import recipe_error
from Util import *
from Work import getwork
import Cache
from Message import *


#
################## Python functions used in Process() #####################
#

def expr2str(item):
    """Used to turn the result of a Python expression into a string.
       For a list the elements are separated with a space.
       "None" is changed to an empty string.
       Dollars are doubled to avoid them being recognized as variables."""
    s = var2string(item)

    # Replace items that could be misinterpreted by ":print".
    # TODO: Is this really the right place to do this, or should the user take
    # care of it when needed?
    s = string.replace(s, '$', '$$')
    s = string.replace(s, '#', '$#')
    s = string.replace(s, '>', '$(gt)')
    s = string.replace(s, '<', '$(lt)')
    s = string.replace(s, '|', '$(bar)')
    return s


def flush_cache(recdict):
    """Called just before setting $CACHEPATH."""
    # It's here so that only this module has to be imported in Process.py.
    Cache.dump_cache(recdict)

#
#################### Python functions for recipes #####################
#

def skipbuild():
    """Return True when skipping build commands."""
    return skip_commands()


def suffix(name):
    """Return the file suffix, empty string when there isn't one."""
    # Remove attributes
    while 1:
        s = string.find(name, "{")
        if s < 0:
            break
        try:
            n, v, e = parse_attr([], name, s)
        except UserError, e:
            # Error in attribute, only give a warning here.
            msg_warning(Global.globals, _("Warning: error in suffix() argument: %s") % str(e))
            e = len(name)
        if e >= len(name):
            name = name[:s]
            break
        else:
            name = name[:s] + ' ' + name[e:]

    # Find last dot.
    i = string.rfind(name, ".")
    if i < 0:
        return ''
    suf = name[i + 1:]

    # Reject suffix if it contains a path separator.
    if string.find(suf, "/") >= 0 or string.find(suf, "\\") >= 0:
        return ''

    # Remove trailing whitespace.
    while suf[-1] == ' ' or suf[-1] == '\t':
        suf = suf[:-1]
    return suf


def aap_sufreplace(suffrom, sufto, var):
    """Obsolete name for sufreplace."""
    return sufreplace(suffrom, sufto, var)

def sufreplace(suffrom, sufto, var):
    """
    Replace suffixes in "var" from "suffrom" to "sufto".
    When "suffrom" is None also add "sufto" if there is no suffix yet.
    When "suffrom" is empty accept any suffix.
    When "sufto" is empty the suffix is removed.
    """
    # Check that the from suffix starts with a dot.
    if suffrom and suffrom[0] != ".":
        recipe_error([], _('first sufreplace() argument must start with a dot'))

    try:
        if suffrom:
            rex = re.compile(string.replace(suffrom, ".", "\\.") + "$")
        else:
            rex = re.compile("\\.[^. \t/\\\\]+$")

        dl = var2dictlist(var)
        for n in dl:
            if (suffrom == None
                        and string.find(os.path.basename(n["name"]), '.') < 0):
                n["name"] = n["name"] + sufto
            else:
                n["name"] = rex.sub(sufto, n["name"])
        return dictlist2str(dl)

    except (StandardError, re.error), e:
        recipe_error([], _('sufreplace() failed: ') + str(e))
        return None     # not reached


def sufadd(suf, var, always = 0):
    """
    Add suffix "suf" to items in "var" that do not have a suffix.
    When "always" is non-zero add "suf" to all items.
    """
    # Check that the from suffix starts with a dot.
    if not suf or suf[0] != ".":
        recipe_error([], _('first sufadd() argument must start with a dot'))

    try:
        dl = var2dictlist(var)
        for n in dl:
            if always or string.find(os.path.basename(n["name"]), '.') < 0:
                n["name"] = n["name"] + suf
        return dictlist2str(dl)

    except (StandardError, re.error), e:
        recipe_error([], _('sufadd() failed: ') + str(e))
        return None     # not reached


def aap_abspath(var):
    """Obsolete name for var_abspath()."""
    return var_abspath(var)

def var_abspath(var):
    """Makes file names in "var" absolute."""
    # TODO: make this more robust.
    dl = str2dictlist([], var2string(var))
    for k in dl:
        n = k["name"]
        if not os.path.isabs(n):
            k["name"] = os.path.abspath(n)
    return dictlist2str(dl)


def aap_expand(var):
    """
    Obsolete name for var2string().
    """
    return var2string(var)


def childdir(arg):
    """
    Return the argument expanded to be relative to the directory of the parent
    recipe.
    """
    recdict = Global.globals
    if not recdict.has_key("CHILDDIR"):
        msg_error(recdict, _("Using childdir() at the top level"))
        return ''
    return relativedir(arg, "CHILDDIR")

def parentdir(arg):
    """
    Return the argument expanded to be relative to the current recipe
    directory, assuming it is relative to the parent recipe.
    """
    recdict = Global.globals
    if not recdict.has_key("PARENTDIR"):
        msg_error(recdict, _("Using parentdir() at the top level"))
        return ''
    return relativedir(arg, "PARENTDIR")

def topdir(arg):
    """
    Return the argument expanded to be relative to the directory of the
    toplevel recipe.
    """
    return relativedir(arg, "TOPDIR")

def basedir(arg):
    """
    Return the argument expanded to be relative to the current recipe
    directory, assuming it is relative to the toplevel recipe.
    """
    return relativedir(arg, "BASEDIR")

def relativedir(arg, varname):
    """
    Implementation of childdir() and topdir()
    """
    recdict = Global.globals
    dirname = recdict[varname]
    if not dirname:     # parent/top is in same directory.
        return arg

    dl = str2dictlist([], var2string(arg))
    for i in dl:
        i["name"] = os.path.join(dirname, i["name"])

    return dictlist2str(dl)


def src2obj(arg1, arg2 = None, sufname = "OBJSUF", auto = 1):
    """Turn a string (list of file names) to their respective object files."""
    # Allow passing two arguments for backwards compatibility.
    # But never use a string for recdict.
    import types
    if type(arg1) is types.DictType:
        recdict = arg1
        source = arg2
    else:
        recdict = Global.globals
        source = arg1
    source = var2string(source)

    dictlist = var2list(source)
    res = ''
    for name in dictlist:
        n = srcitem2obj(recdict, name, sufname = sufname, auto = auto)
        if res:
            res = res + ' '
        res = res + listitem2str(n)
    return res


def srcitem2obj(recdict, name, attrdict = {}, sufname = "OBJSUF", auto = 1):
    """
    Turn one file name to its object file name: Prepend $BDIR and add
    "sufname".  If "attrdict" is specified, use "var_" attributes for the
    variables.
    """
    node = getwork(recdict).find_node(name)
    if attrdict.has_key("var_BDIR"):
        bdir = attrdict["var_BDIR"]
    elif node and node.attributes.has_key("var_BDIR"):
        bdir = node.attributes["var_BDIR"]
    else:
        bdir = get_var_val_int(recdict, "BDIR")

    # When "name" starts with "../" replace it with "_/".  It's not a perfect
    # solution but should work nearly always.
    i = 0
    while (i < len(name)
            and name[i:i+2] == ".."
            and (name[i+2] == '/'
                or (os.name != "posix"
                    and name[i+2] == '\\'))):
        name = name[:i] + "_" + name[i+2:]
        i = i + 2

    name = os.path.join(bdir, name)

    if attrdict.has_key("suffix"):
        # Use the suffix attribute if it exists.
        objsuf = attrdict["suffix"]
    elif sufname:
        # Use the "sufname" argument.
        if not auto:
            ft = None
        else:
            # Use a language-specific suffix name $FT_OBJSUF if it exists.
            if node:
                ft = node.get_ftype(recdict)
            else:
                ft = attrdict.get("filetype")
                if not ft:
                    # A ":program" command adds a lower priority filetype
                    # attribute.
                    ft = attrdict.get("filetypehint")
                    if not ft:
                        from Filetype import ft_detect
                        ft = ft_detect(name, recdict = recdict)

        # If a filetype is known, find $FT_OBJSUF before $OBJSUF.
        if ft:
            l = [ string.upper(ft) + '_' + sufname, sufname ]
        else:
            l = [ sufname ]
        for sn in l:
            if attrdict.has_key("var_" + sn):
                objsuf = attrdict["var_" + sn]
                break
            if node and node.attributes.has_key("var_" + sn):
                objsuf = node.attributes["var_" + sn]
                break
            objsuf = get_var_val_int(recdict, sn)
            if objsuf:
                break
        if objsuf is None:
            recipe_error([], _('srcitem2obj(): $%s not set') % sufname)
    else:
        objsuf = ''

    i = string.rfind(name, '.')
    if i > 0 and i > string.rfind(name, '/') and i > string.rfind(name, '\\'):
        n = name[:i] + objsuf
    else:
        n = name + objsuf

    if attrdict.has_key("prefix"):
        n = os.path.join(os.path.dirname(n),
                                      attrdict["prefix"] + os.path.basename(n))
    return n


def get_attr(fname):
    """Obtain the attribute dictionary for a file name.
       Only works in a recipe, because it uses Global.globals."""
    node = getwork(Global.globals).find_node(fname)
    if node:
        return node.attributes
    return {}


def get_var_attr(var, attr):
    """
    Get the value of attribute "attr" from variable value "var".
    It's an error if two items in "var" have a different attribute value.
    """
    action = ''
    for item in var2dictlist(var):
	a = item.get(attr)
        if not a:
            a = get_attr(item["name"]).get(attr)
	if a:
	    if action and a != action:
                # TODO: mention recipe location!
                recipe_error([], _('get_var_attr(): Two different "%s" attributes specified: "%s" and "%s".') % (attr, action, a))
	    action = a
    return action


def program_path(name, path = None, pathext = None, skip = None):
    """Return the full name of a program "name" if it can be found in the
       search path.  None otherwise.
       If "path" is given, use it as the search path (string of items separated
       with os.pathsep).
       If "pathext" is given, try these suffixes (string of items separated
       with os.pathsep).
       If "skip" is given, skip this directory."""
    # Decide on the list of directories to examine.
    if not path is None:
        envpath = path
    elif os.environ.has_key('PATH'):
        envpath = os.environ['PATH']
    else:
        envpath = os.defpath
    if not type(envpath) is types.ListType:
        dirlist = string.split(envpath, os.pathsep)
    # When using a default path also include our own directory and its "bin"
    # subdirectory.
    if path is None and Global.aap_rootdir:
        dirlist = [ Global.aap_rootdir, Global.aap_bindir ] + dirlist

    # Decide on the list of suffixes to use.
    if not pathext is None:
        if pathext:
            if type(pathext) is types.ListType:
                extlist = pathext
            else:
                extlist = string.split(pathext, os.pathsep)
        else:
            extlist = [ '' ]    # empty pathext means not using a suffix
    elif os.environ.get('PATHEXT'):
        # Cygwin has os.pathsep set to ':' but PATHEXT does use ';' for
        # separator.  Since there should be no ';' in an extension it's
        # relatively safe to assume the separator is ';' if it's there.
        if ';' in os.environ['PATHEXT']:
            sep = ';'
        else:
            sep = os.pathsep
        extlist = string.split(os.environ['PATHEXT'], sep)
    elif os.name in [ 'dos', 'os2', 'nt' ]:
        extlist = [ '', '.exe', '.com', '.bat', '.cmd' ]
    else:
        extlist = [ '' ]
    # If the file name already includes an extention, don't try adding another
    # one.
    if string.find(os.path.basename(name), '.') > 0:
        extlist = [ '' ]

    for dir in dirlist:
        if skip and os.path.abspath(dir) == os.path.abspath(skip):
            continue
        for ext in extlist:
            fullname = os.path.join(dir, name) + ext
            if os.path.isfile(fullname):
                try:
                    # If os.access() is available we can check if the file is
                    # executable.
                    x_ok = os.access(fullname, os.X_OK)
                except:
                    # Couldn't execute os.access() (not supported on all
                    # systems), assume the file is executable.
                    x_ok = 1
                if not x_ok:
                    continue
                return fullname

    return None


def redir_system(arg1, arg2 = 1, arg3 = None):
    """Execute "cmd" with the shell and catch the output.
       Calls redir_system_int() to do the real work, passing the global
       variable dictionary."""
    # A previous version used "recdict" as the first argument.  Work backwards
    # compatible.
    import types
    if arg3 or type(arg1) is types.DictType:
        recdict = arg1
        cmd = arg2
        if arg3:
            use_tee = arg3
        else:
            use_tee = 1
    else:
        recdict = Global.globals
        cmd = arg1
        use_tee = arg2
    return redir_system_int(recdict, cmd, use_tee)


def sort_list(l):
    """Sort a list and return the result.  The sorting is done in-place, thus
       the original list is changed.  It's just a workaround for the Python
       sort method on lists returning None instead of the list."""
    l.sort()
    return l


def var2string(val):
    """
    Expand a variable when it is of ExpandVar class.
    To be used in Python code in a recipe.
    """
    if isinstance(val, ExpandVar):
        # Reduce an ExpandVar object to its value.
        from Commands import expand
        s = expand(0, Global.globals, val.getVal(), Expand(1, Expand.quote_aap))
    else:
        # Convert the value to a string.
        import types
        if type(val) == types.ListType:
            s = list2str(val)
        elif val is None:
            s = ''
        else:
            s = str(val)

    return s

def expandvar(l):
    """Obsolete name for expand2string()."""
    return expand2string(l)

def expand2string(l):
    """Expand wildcards and return a string."""
    return dictlist2str(dictlist_expand(str2dictlist([], var2string(l))))


def var2list(l):
    """Turn a variable with a string value into a list."""
    from Dictlist import str2list
    return str2list([], l)

def expand2list(l):
    """Like var2list() but also expand wildcards."""
    return map(lambda x: x["name"], dictlist_expand(str2dictlist([],
                                                               var2string(l))))


def var2dictlist(l):
    """Turn a variable with a string value into a dictlist."""
    return str2dictlist([], var2string(l))

def expand2dictlist(l):
    """Like var2dictlist() but also expand wildcards."""
    return dictlist_expand(str2dictlist([], var2string(l)))


def wildescape(l):
    """Escape wildcard characters in "l" so that they are not expanded."""
    res = ''
    for c in l:
        if c in ['*', '?', '[']:
            res = res + '[' + c + ']'
        else:
            res = res + c
    return res

def file2string(fname, recdict = None):
    """
    Read a file, remove comment lines and turn the result into one line.
    """
    res = ''
    # open the file, handle errors
    try:
        f = open(os.path.expanduser(fname))
    except StandardError, e:
        msg_error(recdict, (_('Cannot open "%s": ') % fname) + str(e))
    else:
        # read the file, handle errors
        lines = []
        try:
            lines = f.readlines()
        except StandardError, e:
            msg_error(recdict, (_('Error reading "%s": ') % fname) + str(e))
        f.close()

        # concatenate the lines, removing comment lines and white space
        for l in lines:
            l = string.strip(l)
            if l and l[0] != '#':
                res = res + ' ' + l

    res = string.lstrip(res)        # strip leading space
    return res


def has_target(arg1, arg2 = None):
    """Return zero if target "arg1" has no dependencies, one if it has and
       two if it also has build commands."""
    # This function used to have two arguments, first one the recdict used.
    # Figure out how it was called for backwards compatibility.
    if arg2:
        recdict = arg1
        target = arg2
    else:
        recdict = Global.globals
        target = arg1

    work = getwork(recdict)
    node = work.find_node(target)
    if node:
        if node.get_build_dependencies():
            return 2
        if node.get_dependencies():
            return 1
    return 0


def has_targetarg(targets):
    """
    Return non-zero if an entry in "targetlist" is one of the targets Aap was
    started with.
    """
    recdict = Global.globals
    l = var2list(get_var_val(0, recdict, "_no", "TARGETARG"))

    # Using filter() here causes warning messages...
    tlist = var2list(targets)
    for x in l:
        if x in tlist:
            return 1

    return 0


def has_build_target():
    """
    Return non-zero if there is a build target.
    Return zero if there are only fetch or cleanup targets, no need to run
    configure.
    """
    l = Global.cmd_args.targets
    if len(l) == 0:
        return 1        # The default target should build something
    for i in l:
        if not i in ["clean", "cleanmore", "cleanALL", "fetch"]:
            return 1
    return 0


def tempfname():
    """Return the name of a temporary file which is for private use."""
    # TODO: create a directory with 0700 permissions, so that it's private
    return tempfile.mktemp()


def aap_has(arg):
    """
    Return non-zero if "arg" is a supported feature.
    """
    # aap_has(":command")
    if len(arg) > 1 and arg[0] == ':':
        from Process import aap_cmd_names
        return arg[1:] in aap_cmd_names

    return 0


def define_action(action, primary, commands, attr = {},
                            intypes = [], outtypes = [],
                            defer_var_names = [],
                            outfilename = ''):
    """
    Define an action.
    """
    from RecPos import RecPos

    # TODO: is there a way to put a line number in rpstack?
    recdict = Global.globals
    str = "define_action(%s)" % action
    if intypes:
        str = str + " from %s" % reduce(lambda x, y: x + "," + y, intypes)
    if outtypes:
        str = str + " to %s" % reduce(lambda x, y: x + "," + y, outtypes)
    act = Action.Action([RecPos(str)], recdict, attr, commands,
                                    intypes = intypes, outtypes = outtypes,
                                             defer_var_names = defer_var_names,
                                             outfilename = outfilename)
    Action.action_add_to_dict(action, act)
    act.primary = primary
    return act


def action_in_types(name, outtype = None):
    """
    Find action object(s) by name and return a list of the supported input
    types.  Restrict to actions that support "outtype".
    """
    return Action.get_ftypes(name, 1, outtype = outtype)

def action_out_types(name, intype = None):
    """
    Find action object(s) by name and return a list of the supported output
    types.  Restrict to actions that support "intype".
    """
    return Action.get_ftypes(name, 0, intype = intype)

# Remember the last installed port to avoid asking the user twice about using
# it.
lastportname = None

def do_BSD_port(name, target):
    """
    Try using the BSD port system for the package "name".
    "target" is "install" to install and "all" to build only.
    Will ask the user when root permissions are required.
    Returns non-zero for success.
    """
    global lastportname

    recdict = Global.globals

    dirname = "/usr/ports/%s" % name
    try:
        if not os.access(dirname, os.R_OK):
            # Doesn't appear to exist.
            return 0
    except:
        # Can't use os.access().
        return 0

    if lastportname != name and not os.access(dirname, os.W_OK):
        r = raw_input(("\nThe %s port appears to exist.\n" % dirname) +
                        "Do you want to become root and use the port? (y/n) ")
        if not r or (r[0] != 'y' and r[0] != 'Y'):
            # User doesn't want this.
            lastportname = None
            return 0

    lastportname = None

    cwd = os.getcwd()
    try:
        os.chdir(dirname)
    except StandardError, e:
        msg_error(recdict, (_("Cannot cd to %s") % dirname) + str(e))
        return 0

    cmd = "make %s" % target
    try:
        if os.access("/", os.W_OK):
            from Commands import aap_system
            aap_system(0, recdict, cmd)
        else:
            res = do_as_root(recdict, [], cmd)
            if not res:
                raise UserError, _("%s failed") % cmd
    finally:
        os.chdir(cwd)

    lastportname = name

    return 1


# Remember the last installed package to avoid asking the user twice about
# using it.
lastpkgname = None

def do_Debian_pkg(name, target):
    """
    Try using the Debian apt-get command for the package "name".
    "target" is "install" to install and "all" to, eh, do nothing.
    Will ask the user when root permissions are required.
    Returns non-zero for success.
    """
    global lastpkgname

    recdict = Global.globals

    # Safety check: don't allow non-printable and non-ASCII characters in the
    # package name, since we are feeding it to a shell.
    for c in name:
        if ord(c) <= 32 or ord(c) >= 127:
            print _("Illegal character '%s' in package name '%s'") % (c, name)
            return 0

    try:
        if not os.path.isfile("/etc/debian_version"):
            return 0    # Not a Debian system.
        if not program_path("apt-get"):
            return 0    # apt-get is not available (or $PATH wrong)
    except:
        # Can't use os.access().
        return 0

    if lastpkgname != name and not os.access("/", os.W_OK):
        r = raw_input(("\nThis appears to be a Debian system and apt-get is found.\n") +
                        "Do you want to become root and install the %s package? (y/n) " % name)
        if not r or (r[0] != 'y' and r[0] != 'Y'):
            # User doesn't want this.
            lastpkgname = None
            return 0

    lastpkgname = None

    # Only do the work when actually installing.
    if target == "install":
        cmd = "apt-get install %s" % name
        if os.access("/", os.W_OK):
            from Commands import aap_system
            aap_system(0, recdict, cmd)
        else:
            do_as_root(recdict, [], cmd)
        print "apt-get finished"

    lastpkgname = name

    return 1


def ask_prefix(name):
    """
    Ask the user where to install package "name".
    Return a boolean, indicating whether ":asroot" is to be used, and the
    prefix to be used.
    """
    # If the user already is root silently install in /usr/local.
    if os.access("/", os.W_OK):
        return 1, "/usr/local/"

    home = home_dir()
    if home:
        home = os.path.dirname(home)
    r = raw_input((_('\nSelect where to install %s:\n') % name)
            + _('1. become root and install in "/usr/local"\n')
            + _('2. become root and install in a specified location\n')
            + (_('3. install in your home directory "%s"\n') % home)
            + _('4. install in a specified location\n')
            + _('q. quit\n')
            + _('choice: '))
    if r:
        if r[0] == 'q' or r[0] == 'Q':
            recipe_error([], _('ask_prefix() aborted'))
        if r[0] == '2' or r[0] == '4':
            dir = raw_input(_("Enter directory name: "))
            while dir and (dir[-1] == '\n' or dir[-1] == '\r'):
                dir = dir[:-1]
            dir = os.path.expanduser(dir)
        elif r[0] == '1':
            dir = "/usr/local/"
        elif r[0] == '3':
            dir = home
        else:
            return 0, ''

        # Make sure the directory ends in a slash (or backslash).
        if dir[-1] != '/' and dir[-1] != '\\':
            dir = dir + '/'

        if r[0] == '1' or r[0] == '2':
            return 1, dir
        return 0, dir

    # invalid answer
    return 0, ''


# This must be here instead of inside get_html_images() for Python 1.5.
import htmllib

def get_html_images(files, add_dir = 1):
    """
    Function to extract a list of image file names from HTML files.
    Only relative file names are supported, because a relative file name means
    the file can be found when testing locally.
    """
    class ImgHTMLParser(htmllib.HTMLParser):
        def __init__(self, formatter, verbose=0):
            htmllib.HTMLParser.__init__(self, formatter, verbose)
            self.img_list = []      # list of images so far
        def set_dir(self, dir):
            self.img_dir = dir      # dir of image file
        # Overrule handle_image(): append the file name to self.img_list[].
        def handle_image(self, src, alt, *args):
            if src:
                from Remote import url_split3
                scheme, mach, path = url_split3(src)
                if scheme == '' and not os.path.isabs(src):
                    # img file name is relative to html file dir.
                    # Remove things like "../" and "./".
                    n = os.path.normpath(os.path.join(self.img_dir, src))
                    if not n in self.img_list:
                        self.img_list.append(n)
        def get_img_list(self):
            return self.img_list


    import formatter
    parser = ImgHTMLParser(formatter.NullFormatter())

    if not type(files) is types.ListType:
        from Dictlist import str2list
        files = str2list([], files)

    for fname in files:
        try:
            f = open(fname)
        except StandardError, e:
            recipe_error([], _('get_html_images(): Cannot open file "%s": %s')
                                                             % (fname, str(e)))
        try:
            if add_dir:
                parser.set_dir(os.path.dirname(fname))
            parser.feed(f.read())
            parser.close()
            parser.reset()
        except StandardError, e:
            recipe_error([], _('get_html_images(): Error parsing file "%s": %s')
                                                             % (fname, str(e)))
        f.close()

    return parser.get_img_list()


#
#################### Python functions for internal things ###################
#

def aap_depend_c(recdict, sourcestr, targetstr, local = 1, flags = None):
    """
    Check for included files in C or C++ file "source", write a dependency line
    in "target".
    When "local" is non-zero skip files included with <file>.
    When "flags" is given use this instead of $CFLAGS.  Use $CXXFLAGS for C++.
    """
    dl = str2dictlist([], sourcestr)
    source = dl[0]["name"]
    dl = str2dictlist([], targetstr)
    target = dl[0]["name"]
    msg_info(recdict, _('Scanning "%s" for dependencies') % source)

    # "scanned" is a list of files that have been encountered.  The key is an
    # absolute file name.  The value is zero when the file is to be scanned,
    # one if it has been scanned.
    scanned = {full_fname(source) : 0}

    # Make the local pathlist from "-Idir" arguments.
    # Should we include the current directory?  Probably not.  We do look in
    # the directory of the source file when double quotes are used.
    localpathlist = [ ]
    if flags is None:
        flags = get_var_val_int(recdict, "CFLAGS")
    for n in [get_var_val_int(recdict, "CPPFLAGS"),
             get_var_val_int(recdict, "INCLUDE"), flags]:
        dl = str2dictlist([], n)
        for al in dl:
            a = al["name"]
            if len(a) > 2 and a[:2] == "-I":
                localpathlist.append(a[2:])

    globalpathlist = [ "/usr/local/include", "/usr/include" ]

    # Loop until there are no more files to be scanned.
    found = 1
    while found:
        found = 0
        for fname in scanned.keys():
            if scanned[fname] == 0:
                found = 1
                scanned[fname] = 1

                _scan_c_file(recdict, fname, scanned, local,
                                                 localpathlist, globalpathlist)
                break

    try:
        f = open(target, "w")
    except IOError, e:
        msg_error(recdict, (_('Cannot create dependency file "%s": ')
                                                            % target) + str(e))
    else:
        try:
            f.write("%s : " % fname_fold(source))
            for k in scanned.keys():
                f.write(listitem2str(shorten_name(k)) + " ")
            f.close()
        except IOError, e:
            msg_error(recdict, (_('Cannot write to dependency file "%s": ')
                                                            % target) + str(e))


def _scan_c_file(recdict, fname, scanned, local, localpathlist, globalpathlist):
    """
    Add included files in "fname" to dictionary "scanned".
    When "local" is True don't add files included in <>.
    Use the paths in "localpathlist" and "globalpathlist" to find included
    files.
    """
    def search_path(pathlist, fname):
        """Search for included file "fname" in list of dirs "pathlist"."""
        if os.path.isabs(fname):
            return fname
        for dir in pathlist:
            f = os.path.join(dir, fname)
            if os.path.exists(f):
                return full_fname(f)
        return None     # include file not found

    def search_target(work, pathlist, fname):
        """
        Search for included file "fname" in the list of nodes.
        Accept a node only if it has a "fetch" attribute or dependencies.
        Use "pathlist" if necessary.
        """
        n = work.find_node(fname)
        if n and (n.attributes.get("fetch") or n.get_dependencies()):
            return fname
        for dir in pathlist:
            f = os.path.join(dir, fname)
            n = work.find_node(f)
            if n and (n.attributes.get("fetch") or n.get_dependencies()):
                return full_fname(f)
        return None     # include file not found

    try:
        # Scan file "fname".
        if not os.path.exists(fname):
            # The file doesn't exist.
            # Fetch and/or update it.  If this fails just skip it.
            from Commands import aap_update
            try:
                aap_update(0, recdict, fname)
            except:
                msg_extra(recdict, _('Cannot find included file "%s"' % fname))
                return

        mypath = os.path.dirname(fname)
        if mypath == '':
            mypath = '.'

        f = open(fname)
        msg_extra(recdict, _('Scanning "%s" for dependencies') % fname)

        while 1:
            # Read each line of the file.  Quickly check if it
            # starts with "\s*#\s*include".
            line = f.readline()
            if not line:
                break
            i = 0
            min_len = len(line) - 10 # at least need include"f"
            while (i < min_len
                    and (line[i] == ' ' or line[i] == '\t')):
                i = i + 1
            if i < min_len and line[i] == '#':
                i = i + 1
                while (i < min_len
                        and (line[i] == ' ' or line[i] == '\t')):
                    i = i + 1
                if line[i:i+7] == "include":
                    i = skip_white(line, i + 7)
                    line_len = len(line)
                    if i < line_len:
                        quote = line[i]
                        if (quote == '"'
                                or (quote == '<' and not local)):
                            if quote == '<':
                                quote = '>'
                            i = i + 1
                            s = i
                            while i < line_len and line[i] != quote:
                                i = i + 1
                            if i < line_len and line[i] == quote:
                                # Make file name uniform (forward slashes).
                                name = fname_fold(line[s:i])

                                # Search for the file in the specified path for
                                # include files.
                                if quote == '"':
                                    pathlist = [ mypath ] + localpathlist + globalpathlist
                                else:
                                    pathlist = globalpathlist + localpathlist
                                fn = search_path(pathlist, name)

                                # If the file is not found search for a target
                                # that can produce it or fetch it.
                                if not fn:
                                    fn = search_target(getwork(recdict),
                                                                pathlist, name)
                                if fn and not scanned.has_key(fn):
                                    scanned[fn] = not local

    except IOError:
        # ignore errors while scanning a file, always close the
        # file
        try:
            f.close()
        except:
            pass


def get_md5(fname):
    """Get the md5 checksum as a hexdigest for file "file".
       Used in the recipe generated with ":mkdownload".
       Returns "unknown" when the file can't be read."""
    from Sign import check_md5

    return check_md5(globals(), fname, msg = 0)


#
# INSTALL stuff.
#

def install_files(desttail, source, modestr, strip = 0, mandir = 0,
                                                                uninstall = 0):
    """
    Called from the default actions to install files "source" into directory
    $DESTDIR/$PREFIX/"desttail" with mode "modestr".
    When "strip" is non-zero run $STRIP on the executables.
    When "mandir" is non-zero, use the file name extension for the directory
    name, as usual for manpages
    Also used for uninstall with "uninstall" set to 1.
    """
    from CopyMove import remote_copy_move
    from RecPos import RecPos
    from Remote import url_split3

    recdict = Global.globals
    # TODO: get better stack info!
    if uninstall:
        rpstack = [RecPos("uninstall_files()")]
    else:
        rpstack = [RecPos("install_files()")]

        if strip:
            stripprog = get_var_val(0, recdict, "_no", "STRIP")
            if not stripprog:
                msg_warning(recdict, _("$STRIP is empty, stripping skipped"))

    # Prepend $DESTDIR and $PREFIX.  $DESTDIR is optional.  $PREFIX is not used
    # when "desttail" starts with a slash.
    prefix = get_var_val(0, recdict, "_no", "PREFIX")
    if not prefix:
        prefix = "/usr/local"
    destlist = str2dictlist(recdict, desttail)
    if len(destlist) != 1:
        recipe_error([], _('destination directory must be one item: "%s"')
                                                                    % desttail)
    dest = os.path.join(os.path.expanduser(prefix), destlist[0]["name"])
    destdir = get_var_val(0, recdict, "_no", "DESTDIR")
    if destdir:
        while dest[0] in "/\\":
            dest = dest[1:]     # remove leading slashes before joining
        dest = os.path.join(os.path.expanduser(destdir), dest)

    for item in str2dictlist(recdict, source):
        name = item["name"]

        # Install "foo.2" in "man2" directory.
        if mandir and len(name) > 2 and name[-2] == '.':
            destloc = os.path.join(dest, "man%s" % name[-1])
        else:
            destloc = dest

        if item.get("installdir"):
            destloc = os.path.join(destloc, item.get("installdir"))
            if item.get("keepdir"):
                msg_warning(recdict, _('"%s" has both "keepdir" and "installdir"; using "installdir"') % name)
        # with {keepdir} append the directory of the source.
        elif item.get("keepdir"):
            destloc = os.path.join(destloc, os.path.dirname(name))

        destname = os.path.join(destloc, os.path.basename(name))
        scheme, mach, path = url_split3(destname)

        if uninstall:
            if scheme != '':
                msg_warning(recdict, _('Cannot delete remotely yet: "%s"')
                                                                    % destname)
            elif os.path.exists(destname):
                if skip_commands():
                    msg_info(recdict, _('Skip delete "%s"') % destname)
                else:
                    # Delete the file.
                    try:
                        msg_info(recdict, _('Deleting "%s"') % destname)
                        os.remove(destname)
                    except EnvironmentError, e:
                        msg_warning(recdict, (_('Could not delete "%s": ')
                                                          % destname) + str(e))

        else:

            # Create directories.
            if scheme == '' and destloc and not os.path.exists(destloc):
                if skip_commands():
                    msg_info(recdict, _('Skip create directory "%s"') % destloc)
                else:
                    msg_info(recdict, _('Creating directory "%s"') % destloc)
                    try:
                        os.makedirs(destloc)
                    except EnvironmentError, e:
                        recipe_error([], _('Could not create directory: %s') % e)

            if item.get("keepmode"):
                newmode = -1
            else:
                if item.get("mode"):
                    newmode = oct2int(item.get("mode"))
                else:
                    newmode = oct2int(modestr)
            dostrip = strip and stripprog and not item.get("nostrip")

            if skip_commands():
                msg_info(recdict, _('Skip copy "%s" to "%s"')
                                                            % (name, destname))
                if dostrip:
                    msg_info(recdict, _('Skip strip "%s"') % destname)
                if newmode >= 0:
                    msg_info(recdict, _('Skip chmod 0%o "%s"')
                                                         % (newmode, destname))
            else:
                if (newmode >= 0 or dostrip) and scheme != '':
                    # strip a remote program before copying, first make a copy.
                    tmpname = tempfname()
                    remote_copy_move(rpstack, recdict, 1,
                                [ {"name" : name} ], {"name" : tmpname},
                                {"force": 1}, 0, errmsg = 1)
                    if dostrip:
                        logged_system(recdict, "%s '%s'" % (stripprog, tmpname))
                    if newmode >= 0:
                        os.chmod(tmpname, newmode)
                    name = tmpname
                    copy = 0
                else:
                    copy = 1

                # Copy the file.
                remote_copy_move(rpstack, recdict, copy,
                            [ {"name" : name} ], {"name" : destname},
                            {"force": 1}, 0, errmsg = 1)

                # If stripping is requested and there is a strip program, strip.
                if dostrip and scheme == '':
                    logged_system(recdict, "%s '%s'" % (stripprog, destname))

                if newmode >= 0 and scheme == '':
                    os.chmod(destname, newmode)


def uninstall_files(desttail, source, mandir = 0):
    """
    Called by uninstall actions to remove files.
    """
    install_files(desttail, source, 0, mandir = mandir, uninstall = 1)


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