########################################################################
# $Header: /var/local/cvsroot/4Suite/Ft/Server/Client/Commands/CommandUtil.py,v 1.11 2005/03/19 10:41:16 jkloth Exp $
"""
Functions used by various '4ss' command implementations.

Copyright 2004 Fourthought, Inc. (USA).
Detailed license and copyright information: http://4suite.org/COPYRIGHT
Project home, documentation, distributions: http://4suite.org/
"""

import sys

from Ft.Lib import Wrap
from Ft.Server.Client import SmartLogin, FtServerClientException
from Ft.Server.Common import AclConstants

__all__ = ['GetRepository', 'WritePreamble']


def GetRepository(options, cmdName):
    """
    Given an options dictionary and the name of a command, uses the
    options in an attempt to obtain a repository access object, then
    verifies that the user attempting the access has execute access
    on the corresopnding Command resource in the repository. If
    successful, returns the repository access object. Otherwise,
    prints an exception message to standard error and returns None.
    """
    repo = None
    try:
        repo = SmartLogin(options)
        if cmdName is not None:
            cmd = repo.getCommand(cmdName)
            if cmd is None:
                raise ValueError("Unknown Command: " + cmdName)
            cmd.verifyAcl(AclConstants.EXECUTE_ACCESS,0)

    except FtServerClientException, e:
        sys.stderr.write(str(e)+'\n')
        sys.stderr.flush()
        repo = None

    return repo


def WritePreamble(heading, uchar='=', maxwidth=None, stream=sys.stderr):
    """
    Commands that need to preface their output with a preamble can
    use this function to write it to the output stream (a file-like
    object) in a consistent way. The given heading will be wrapped
    if necessary to fit within a maximum width, then will be written
    out, followed by a row a underline characters that is as wide
    as the widest line in the heading.
    """
    lines = heading.split('\n')
    longest_len = max(map(lambda s: len(s), lines))
    if maxwidth and maxwidth > 0 and longest_len >= maxwidth:
        heading = Wrap(heading, maxwidth)
        longest_len = max(map(lambda s: len(s), heading.split('\n')))
    stream.write(heading)
    if heading[-1] != '\n':
        stream.write('\n')
    stream.write(uchar * longest_len + '\n')
    stream.flush()
    return
