# Software License Agreement (BSD License)
#
# Copyright (c) 2010, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
#  * Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#  * Redistributions in binary form must reproduce the above
#    copyright notice, this list of conditions and the following
#    disclaimer in the documentation and/or other materials provided
#    with the distribution.
#  * Neither the name of Willow Garage, Inc. nor the names of its
#    contributors may be used to endorse or promote products derived
#    from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

from __future__ import print_function
import os
import sys
import textwrap
import shutil
import datetime
import yaml
from optparse import OptionParser, IndentedHelpFormatter

from wstool.cli_common import get_info_list, get_info_table, \
    get_info_table_raw_csv, ONLY_OPTION_VALID_ATTRS
from wstool.common import samefile, select_element, select_elements, \
    MultiProjectException, normalize_uri, string_diff
from wstool.config_yaml import PathSpec, get_path_spec_from_yaml
import wstool.multiproject_cmd as multiproject_cmd
from wstool.ui import Ui

# implementation of single CLI commands (extracted for use in several
# overlapping scripts)

# usage help
__MULTIPRO_CMD_DICT__ = {
    "help":     "provide help for commands",
    "init":     "set up a directory as workspace",
    "info":     "Overview of some entries",
    "merge":    "merges your workspace with another config set",
    "set":      "add or changes one entry from your workspace config",
    "update":   "update or check out some of your config elements",
    "remove":   "remove an entry from your workspace config, without deleting files",
    "export":   "export a snapshot of the workspace",
    "diff":     "print a diff over some SCM controlled entries",
    "foreach":  "run shell command in given entries",
    "status":   "print the change status of files in some SCM controlled entries",
    "scrape":   "interactively add all found unmanaged VCS subfolders to workspace"
}

# usage help ordering and sections
__MULTIPRO_CMD_HELP_LIST__ = ['help', 'init',
                              None, 'set', 'merge', 'remove', 'scrape',
                              None, 'update',
                              None, 'info', 'export', 'status', 'diff', 'foreach']

# command aliases
__MULTIPRO_CMD_ALIASES__ = {'update': 'up',
                            'remove': 'rm',
                            'status': 'st',
                            'diff': 'di'}


def get_header(progname):
    config_header = ("# THIS IS AN AUTOGENERATED FILE, LAST GENERATED USING %s ON %s\n"
                     % (progname, datetime.date.today().isoformat()))
    return config_header


class IndentedHelpFormatterWithNL(IndentedHelpFormatter):
    def format_description(self, description):
        if not description:
            return ""
        desc_width = self.width - self.current_indent
        indent = " " * self.current_indent
        # the above is still the same
        bits = description.split('\n')
        formatted_bits = [
            textwrap.fill(bit,
                          desc_width,
                          initial_indent=indent,
                          subsequent_indent=indent)
            for bit in bits]
        result = "\n".join(formatted_bits) + "\n"
        return result


def _get_mode_from_options(parser, options):
    mode = 'prompt'
    if options.delete_changed:
        mode = 'delete'
    if options.abort_changed:
        if mode == 'delete':
            parser.error("delete-changed-uris is mutually exclusive with abort-changed-uris")
        mode = 'abort'
    if options.backup_changed != '':
        if mode == 'delete':
            parser.error("delete-changed-uris is mutually exclusive with backup-changed-uris")
        if mode == 'abort':
            parser.error("abort-changed-uris is mutually exclusive with backup-changed-uris")
        mode = 'backup'
    return mode


def _get_element_diff(new_path_spec, config_old, extra_verbose=False):
    """
    :returns: a string telling what changed for element compared to old config
    """
    if new_path_spec is None or config_old is None:
        return ''
    output = [' %s' % new_path_spec.get_local_name()]
    if extra_verbose:
        old_element = None
        if config_old is not None:
            old_element = select_element(config_old.get_config_elements(),
                                         new_path_spec.get_local_name())

        if old_element is None:
            if new_path_spec.get_scmtype() is not None:
                output.append(
                    "   \t%s  %s   %s" % (new_path_spec.get_scmtype(),
                                          new_path_spec.get_uri(),
                                          new_path_spec.get_version() or ''))
        else:
            old_path_spec = old_element.get_path_spec()
            accessor_map = {PathSpec.get_scmtype: 'scmtype',
                            PathSpec.get_version: 'version',
                            PathSpec.get_revision: 'revision',
                            PathSpec.get_current_revision: 'current revision',
                            PathSpec.get_curr_uri: 'current_uri',
                            PathSpec.get_uri: 'specified uri'}
            for accessor, label in list(accessor_map.items()):
                old_val = accessor(old_path_spec)
                new_val = accessor(new_path_spec)
                if old_val is not None and\
                        old_val != new_val:
                    diff = string_diff(old_val, new_val)
                    output.append("  \t%s: %s -> %s;" % (label, old_val, diff))
                elif old_val is None and\
                        new_val is not None and\
                        new_val != "" and\
                        new_val != []:
                    output.append("  %s = %s" % (label,
                                                 new_val))
    return ''.join(output)


def prompt_merge(target_path,
                 additional_uris,
                 additional_specs,
                 path_change_message=None,
                 merge_strategy='KillAppend',
                 confirmed=False,
                 confirm=False,
                 show_advanced=True,
                 show_verbosity=True,
                 config_filename=None,
                 config=None,
                 allow_other_element=True):
    """
    Prompts the user for the resolution of a merge. Without
    further options, will prompt only if elements change. New
    elements are just added without prompt.

    :param target_path: Location of the config workspace
    :param additional_uris: uris from which to load more elements
    :param additional_specs: path specs for additional elements
    :param path_change_message: Something to tell the user about elements order
    :param merge_strategy: See Config.insert_element
    :param confirmed: Never ask
    :param confirm: Always ask, supercedes confirmed
    :param config: None or a Config object for target path if available
    :param show_advanced: if true allow to change merge strategy
    :param show_verbosity: if true allows to change verbosity
    :param allow_other_element: if False merge fails hwen it could cause other elements
    :returns: tupel (Config or None if no change, bool path_changed)
    """
    if config is None:
        config = multiproject_cmd.get_config(
            target_path,
            additional_uris=[],
            config_filename=config_filename)
    elif config.get_base_path() != target_path:
        msg = "Config path does not match %s %s " % (config.get_base_path(),
                                                     target_path)
        raise MultiProjectException(msg)
    local_names_old = [x.get_local_name() for x in config.get_config_elements()]

    extra_verbose = confirmed or confirm
    abort = False
    last_merge_strategy = None
    while not abort:

        if (last_merge_strategy is None
            or last_merge_strategy != merge_strategy):
            if not config_filename:
                # should never happen right now with rosinstall/rosws/wstool
                # TODO Need a better way to work with clones of original config
                raise ValueError('Cannot merge when no config filename is set')
            newconfig = multiproject_cmd.get_config(
                target_path,
                additional_uris=[],
                config_filename=config_filename)
            config_actions = multiproject_cmd.add_uris(
                config=newconfig,
                additional_uris=additional_uris,
                config_filename=None,
                merge_strategy=merge_strategy,
                allow_other_element=allow_other_element)
            for path_spec in additional_specs:
                action = newconfig.add_path_spec(path_spec, merge_strategy)
                config_actions[path_spec.get_local_name()] = (action, path_spec)
            last_merge_strategy = merge_strategy

        local_names_new = [x.get_local_name() for x in newconfig.get_config_elements()]

        path_changed = False
        ask_user = False
        output = ""
        new_elements = []
        changed_elements = []
        discard_elements = []
        for localname, (action, new_path_spec) in list(config_actions.items()):
            index = -1
            if localname in local_names_old:
                index = local_names_old.index(localname)
            if action == 'KillAppend':
                ask_user = True
                if (index > -1 and local_names_old[:index + 1] == local_names_new[:index + 1]):
                    action = 'MergeReplace'
                else:
                    changed_elements.append(_get_element_diff(new_path_spec, config, extra_verbose))
                    path_changed = True

            if action == 'Append':
                path_changed = True
                new_elements.append(_get_element_diff(new_path_spec,
                                                      config,
                                                      extra_verbose))
            elif action == 'MergeReplace':
                changed_elements.append(_get_element_diff(new_path_spec,
                                                          config,
                                                          extra_verbose))
                ask_user = True
            elif action == 'MergeKeep':
                discard_elements.append(_get_element_diff(new_path_spec,
                                                          config,
                                                          extra_verbose))
                ask_user = True
        if len(changed_elements) > 0:
            output += "\n     Change details of element (Use --merge-keep or --merge-replace to change):\n"
            if extra_verbose:
                output += " %s\n" % ("\n".join(sorted(changed_elements)))
            else:
                output += " %s\n" % (", ".join(sorted(changed_elements)))
        if len(new_elements) > 0:
            output += "\n     Add new elements:\n"
            if extra_verbose:
                output += " %s\n" % ("\n".join(sorted(new_elements)))
            else:
                output += " %s\n" % (", ".join(sorted(new_elements)))

        if local_names_old != local_names_new[:len(local_names_old)]:
            old_order = ' '.join(reversed(local_names_old))
            new_order = ' '.join(reversed(local_names_new))
            output += "\n     %s " % path_change_message or "Element order change"
            output += "(Use --merge-keep or --merge-replace to prevent) "
            output += "from\n %s\n     to\n %s\n\n" % (old_order, new_order)
            ask_user = True

        if output == "":
            return (None, False)
        if not confirm and (confirmed or not ask_user):
            print("     Performing actions: ")
            print(output)
            return (newconfig, path_changed)
        else:
            print(output)
            showhelp = True
            while(showhelp):
                showhelp = False
                prompt = "Continue: (y)es, (n)o"
                if show_verbosity:
                    prompt += ", (v)erbosity"
                if show_advanced:
                    prompt += ", (a)dvanced options"
                prompt += ": "
                mode_input = Ui.get_ui().get_input(prompt)
                if mode_input == 'y':
                    return (newconfig, path_changed)
                elif mode_input == 'n':
                    abort = True
                elif show_advanced and mode_input == 'a':
                    strategies = {'MergeKeep': "(k)eep",
                                  'MergeReplace': "(s)witch in",
                                  'KillAppend': "(a)ppending"}
                    unselected = [v for k, v in
                                  list(strategies.items())
                                  if k != merge_strategy]
                    print("""New entries will just be appended to the config and
appear at the beginning of your ROS_PACKAGE_PATH. The merge strategy
decides how to deal with entries having a duplicate localname or path.

"(k)eep" means the existing entry will stay as it is, the new one will
be discarded. Useful for getting additional elements from other
workspaces without affecting your setup.

"(s)witch in" means that the new entry will replace the old in the
same position. Useful for upgrading/downgrading.

"switch (a)ppend" means that the existing entry will be removed, and
the new entry appended to the end of the list. This maintains order
of elements in the order they were given.

Switch append is the default.
""")
                    prompt = "Change Strategy %s: " % (", ".join(unselected))
                    mode_input = Ui.get_ui().get_input(prompt)
                    if mode_input == 's':
                        merge_strategy = 'MergeReplace'
                    elif mode_input == 'k':
                        merge_strategy = 'MergeKeep'
                    elif mode_input == 'a':
                        merge_strategy = 'KillAppend'

                elif show_verbosity and mode_input == 'v':
                    extra_verbose = not extra_verbose
        if abort:
            print("No changes made.")
        print('==========================================')
    return (None, False)


def list_usage(progname, description, command_keys, command_helps, command_aliases):
    """
    Constructs program usage for a list of commands with help and aliases.
    Contructs in the order given in command keys. Newlines can be used for
    command sections by adding None entries to command_keys list.
    Only one alias allowed per command.

    :param command_keys: list of keys or None to print help or empty lines
    :param command_helps: dict{key: help}
    :param command_aliases: dict{key: alias}
    :returns: usage string (multiline)
    """
    dvars = {'prog': progname}
    dvars.update(vars())
    result = []
    result.append(description % dvars)
    for key in command_keys:
        if key in command_aliases:
            alias = ' (%s)' % command_aliases[key]
        else:
            alias = ''
        if key is not None:
            result.append(("%s%s" % (key, alias)).ljust(10) + '   \t' + command_helps[key])
        else:
            result.append('')
    return '\n'.join(result)


class MultiprojectCLI:

    def __init__(self,
                 progname,
                 config_filename=None,
                 allow_other_element=False,
                 config_generator=None):
        '''
        creates the instance. Historically, rosinstall allowed "other"
        elements that went into the ROS_PACKAGE_PATH, but were ignored
        for vcs operations. A pure vcs tool has no use for such
        elements.

        :param progname: name to diplay in help
        :param config_filename: filename of files maintaining workspaces (.rosinstall)
        :param allow_other_element: bool, if True rosinstall semantics for "other" apply
        :param config_generator: function that writes config file
        '''
        self.config_filename = config_filename
        self.config_generator = config_generator or multiproject_cmd.cmd_persist_config
        self.progname = progname
        self.allow_other_element = allow_other_element

    def cmd_init(self, argv):
        if self.config_filename is None:
            print('Error: Bug: config filename required for init')
            return 1
        parser = OptionParser(
            usage="""usage: %s init [TARGET_PATH [SOURCE_PATH]]?""" % self.progname,
            formatter=IndentedHelpFormatterWithNL(),
            description=__MULTIPRO_CMD_DICT__["init"] + """

%(prog)s init does the following:
  1. Reads folder/file/web-uri SOURCE_PATH looking for a rosinstall yaml
  2. Creates new %(cfg_file)s file at TARGET-PATH

SOURCE_PATH can e.g. be a web uri or a rosinstall file with vcs entries only
If PATH is not given, uses current dir.

Examples:
$ %(prog)s init ~/fuerte /opt/ros/fuerte
""" % {'cfg_file': self.config_filename, 'prog': self.progname},
                              epilog="See: http://www.ros.org/wiki/rosinstall for details\n")
        parser.add_option("--continue-on-error", dest="robust", default=False,
                          help="Continue despite checkout errors",
                          action="store_true")
        parser.add_option("-j", "--parallel", dest="jobs", default=1,
                          help="How many parallel threads to use for installing",
                          action="store")
        parser.add_option("--shallow", dest="shallow", default=False,
                          help="Checkout only latest revision if possible",
                          action="store_true")
        (options, args) = parser.parse_args(argv)
        if len(args) < 1:
            target_path = '.'
        else:
            target_path = args[0]

        if not os.path.isdir(target_path):
            if not os.path.exists(target_path):
                os.mkdir(target_path)
            else:
                print('Error: Cannot create in target path %s ' % target_path)

        if os.path.exists(os.path.join(target_path, self.config_filename)):
            print('Error: There already is a workspace config file %s at "%s". Use %s install/modify.' %
                  (self.config_filename, target_path, self.progname))
            return 1
        if len(args) > 2:
            parser.error('Too many arguments')

        if len(args) == 2:
            print('Using initial elements from: %s' % args[1])
            config_uris = [args[1]]
        else:
            config_uris = []

        config = multiproject_cmd.get_config(
            basepath=target_path,
            additional_uris=config_uris,
            # catkin workspaces have no reasonable chaining semantics
            # config_filename=self.config_filename
            )
        if config_uris and len(config.get_config_elements()) == 0:
            sys.stderr.write('WARNING: Not using any element from %s\n' % config_uris[0])
        for element in config.get_config_elements():
            if not element.is_vcs_element():
                raise MultiProjectException("wstool does not allow elements without vcs information. %s" % element)

        # includes ROS specific files

        if self.config_filename:
            print("Writing %s" % os.path.join(config.get_base_path(), self.config_filename))
        self.config_generator(config, self.config_filename, get_header(self.progname))

        ## install or update each element
        install_success = multiproject_cmd.cmd_install_or_update(
            config,
            robust=False,
            shallow=options.shallow,
            num_threads=int(options.jobs))

        if not install_success:
            print("Warning: installation encountered errors, but --continue-on-error was requested.  Look above for warnings.")
        print("\nupdate complete.")
        return 0

    def cmd_merge(self, target_path, argv, config=None):
        parser = OptionParser(
            usage="usage: %s merge [URI] [OPTIONS]" % self.progname,
            formatter=IndentedHelpFormatterWithNL(),
            description=__MULTIPRO_CMD_DICT__["merge"] + """.

The command merges config with given other rosinstall element sets, from files or web uris.

The default workspace will be inferred from context, you can specify one using -t.

By default, when an element in an additional URI has the same
local-name as an existing element, the existing element will be
replaced. In order to ensure the ordering of elements is as
provided in the URI, use the option --merge-kill-append.

Examples:
$ %(prog)s merge someother.rosinstall

You can use '-' to pipe in input, as an example:
$ roslocate info robot_model | %(prog)s merge -
""" % {'prog': self.progname},
            epilog="See: http://www.ros.org/wiki/rosinstall for details\n")
        # same options as for multiproject
        parser.add_option(
            "-a", "--merge-kill-append", dest="merge_kill_append",
            default=False,
            help="merge by deleting given entry and appending new one",
            action="store_true")
        parser.add_option("-k", "--merge-keep", dest="merge_keep",
                          default=False,
                          help="merge by keeping existing entry and discarding new one",
                          action="store_true")
        parser.add_option("-r", "--merge-replace", dest="merge_replace",
                          default=False,
                          help="(default) merge by replacing given entry with new one maintaining ordering",
                          action="store_true")
        parser.add_option("-y", "--confirm-all", dest="confirm_all",
                          default='',
                          help="do not ask for confirmation unless strictly necessary",
                          action="store_true")
        # required here but used one layer above
        parser.add_option(
            "-t", "--target-workspace", dest="workspace", default=None,
            help="which workspace to use",
            action="store")
        (options, args) = parser.parse_args(argv)

        if len(args) > 1:
            print("Error: Too many arguments.")
            print(parser.usage)
            return -1
        if len(args) == 0:
            print("Error: Too few arguments.")
            print(parser.usage)
            return -1

        config_uris = args

        specs = []
        if config_uris[0] == '-':
            pipedata = "".join(sys.stdin.readlines())
            try:
                yamldicts = yaml.safe_load(pipedata)
            except yaml.YAMLError as e:
                raise MultiProjectException(
                    "Invalid yaml format: \n%s \n%s" % (pipedata, e))
            if yamldicts is None:
                parser.error("No Input read from stdin")
            # cant have user interaction and piped input
            options.confirm_all = True
            specs.extend([get_path_spec_from_yaml(x) for x in yamldicts])
            config_uris = []

        merge_strategy = None
        count_mergeoptions = 0
        if options.merge_kill_append:
            merge_strategy = 'KillAppend'
            count_mergeoptions += 1
        if options.merge_keep:
            merge_strategy = 'MergeKeep'
            count_mergeoptions += 1
        if options.merge_replace:
            merge_strategy = 'MergeReplace'
            count_mergeoptions += 1
        if count_mergeoptions > 1:
            parser.error("You can only provide one merge-strategy")
        # default option
        if count_mergeoptions == 0:
            merge_strategy = 'MergeReplace'
        (newconfig, _) = prompt_merge(
            target_path,
            additional_uris=config_uris,
            additional_specs=specs,
            path_change_message="element order changed",
            merge_strategy=merge_strategy,
            confirmed=options.confirm_all,
            config_filename=self.config_filename,
            config=config,
            allow_other_element=self.allow_other_element)
        if newconfig is not None:
            print("Config changed, maybe you need run %s update to update SCM entries." % self.progname)
            print("Overwriting %s" % os.path.join(newconfig.get_base_path(), self.config_filename))
            shutil.copy(os.path.join(newconfig.get_base_path(), self.config_filename), "%s.bak" % os.path.join(newconfig.get_base_path(), self.config_filename))
            self.config_generator(newconfig, self.config_filename, get_header(self.progname))
            print("\nupdate complete.")
        else:
            print("Merge caused no change, no new elements found")
        return 0

    def cmd_diff(self, target_path, argv, config=None):
        parser = OptionParser(usage="usage: %s diff [localname]* " % self.progname,
                              description=__MULTIPRO_CMD_DICT__["diff"],
                              epilog="See: http://www.ros.org/wiki/rosinstall for details\n")
        # required here but used one layer above
        parser.add_option("-t", "--target-workspace", dest="workspace",
                          default=None,
                          help="which workspace to use",
                          action="store")
        (_, args) = parser.parse_args(argv)

        if config is None:
            config = multiproject_cmd.get_config(
                target_path,
                additional_uris=[],
                config_filename=self.config_filename)
        elif config.get_base_path() != target_path:
            raise MultiProjectException(
                "Config path does not match %s %s " % (config.get_base_path(),
                                                       target_path))

        if len(args) > 0:
            difflist = multiproject_cmd.cmd_diff(config, localnames=args)
        else:
            difflist = multiproject_cmd.cmd_diff(config)
        alldiff = []
        for entrydiff in difflist:
            if entrydiff['diff'] is not None and entrydiff['diff'] != '':
                alldiff.append(entrydiff['diff'])
        result = '\n'.join(alldiff)
        # result has no newline at end
        if result:
            print(result)

        return False

    def cmd_foreach(self, target_path, argv, config=None):
        """Run shell commands in each repository."""
        parser = OptionParser(
            usage=('usage: %s foreach [[localname]* | [VCSFILTER]*]'
                   ' [command] [OPTIONS]' % self.progname),
            formatter=IndentedHelpFormatterWithNL(),
            description=__MULTIPRO_CMD_DICT__['foreach'] + """.

Example:
$ %(progname)s foreach --git 'git status'
""" % { 'progname': self.progname},
            epilog='See: http://www.ros.org/wiki/rosinstall for details')
        parser.add_option('--shell', default=False,
                          help='use the shell as the program to execute',
                          action='store_true')
        parser.add_option('--no-stdout', dest='show_stdout',
                          default=True,
                          help='do not show stdout',
                          action='store_false')
        parser.add_option('--no-stderr', dest='show_stderr',
                          default=True,
                          help='do not show stderr',
                          action='store_false')
        parser.add_option("--git", dest="git", default=False,
                          help="run command in git entries",
                          action="store_true")
        parser.add_option("--svn", dest="svn", default=False,
                          help="run command in svn entries",
                          action="store_true")
        parser.add_option("--hg", dest="hg", default=False,
                          help="run command in hg entries",
                          action="store_true")
        parser.add_option("--bzr", dest="bzr", default=False,
                          help="run command in bzr entries",
                          action="store_true")
        parser.add_option("-m", "--timeout", dest="timeout",
                          default=None,
                          help="How long to wait for each repo before failing [seconds]",
                          action="store", type=float)
        parser.add_option("-j", "--parallel", dest="jobs",
                          default=1,
                          help="How many parallel threads to use for running the custom commands",
                          action="store")
        parser.add_option("-v", "--verbose", dest="verbose",
                          default=False,
                          help="Whether to print out more information",
                          action="store_true")
        # -t option required here for help but used one layer above
        # see cli_common
        parser.add_option("-t", "--target-workspace", dest="workspace",
                          default=None,
                          help="which workspace to use",
                          action="store")
        (options, args) = parser.parse_args(argv)

        if args:
            localnames, command = args[:-1], args[-1]
            localnames = localnames if localnames else None
        else:
            print("Error: Too few arguments.")
            print(parser.usage)
            return -1

        scm_types = []
        if options.git:
            scm_types.append('git')
        if options.svn:
            scm_types.append('svn')
        if options.hg:
            scm_types.append('hg')
        if options.bzr:
            scm_types.append('bzr')
        if not scm_types:
            scm_types = None

        if localnames and scm_types:
            sys.stderr.write("Error: Either localnames or scm-filters"
                             " [--(git|svn|hg|bzr)] should be specified.\n")
            return -1

        if config is None:
            config = multiproject_cmd.get_config(
                target_path,
                additional_uris=[],
                config_filename=self.config_filename)
        elif config.get_base_path() != target_path:
            raise MultiProjectException('Config path does not match %s %s' %
                                        (config.get_base_path(), target_path))

        # run shell command
        outputs = multiproject_cmd.cmd_foreach(config,
                                               command=command,
                                               localnames=localnames,
                                               num_threads=int(options.jobs),
                                               timeout=options.timeout,
                                               scm_types=scm_types,
                                               shell=options.shell,
                                               verbose=options.verbose)

        def add_localname_prefix(localname, lines):
            return ['[%s] %s' % (localname, line) for line in lines]

        for output in outputs:
            localname = output['entry'].get_local_name()
            rc = output['returncode']
            if options.show_stdout:
                if output['stdout'] is None:
                    continue
                lines = output['stdout'].strip().split('\n')
                lines = add_localname_prefix(localname, lines)
                sys.stdout.write('\n'.join(lines))
                sys.stdout.write('\n')
            if options.show_stderr:
                lines = []
                if output['stderr'] is not None:
                    lines += output['stderr'].strip().split('\n')
                if rc != 0:
                    lines +=  ['Command failed with return code [%s]' % rc]
                if not lines:
                    continue
                lines = add_localname_prefix(localname, lines)
                sys.stderr.write('\n'.join(lines))
                sys.stderr.write('\n')
        return 0 if all([o['returncode'] == 0  for o in outputs]) else 1

    def cmd_status(self, target_path, argv, config=None):
        parser = OptionParser(usage="usage: %s status [localname]* " % self.progname,
                              description=__MULTIPRO_CMD_DICT__["status"] +
                              ". The status columns meanings are as the respective SCM defines them.",
                              epilog="""See: http://www.ros.org/wiki/rosinstall for details""")
        parser.add_option("-u", "--untracked", dest="untracked",
                          default=False,
                          help="Also shows untracked files",
                          action="store_true")
        # -t option required here for help but used one layer above, see cli_common
        parser.add_option("-t", "--target-workspace", dest="workspace",
                          default=None,
                          help="which workspace to use",
                          action="store")
        (options, args) = parser.parse_args(argv)

        if config is None:
            config = multiproject_cmd.get_config(
                target_path,
                additional_uris=[],
                config_filename=self.config_filename)
        elif config.get_base_path() != target_path:
            raise MultiProjectException(
                "Config path does not match %s %s " % (config.get_base_path(),
                                                       target_path))

        if len(args) > 0:
            statuslist = multiproject_cmd.cmd_status(config,
                                                     localnames=args,
                                                     untracked=options.untracked)
        else:
            statuslist = multiproject_cmd.cmd_status(config,
                                                     untracked=options.untracked)
        allstatus = []
        for entrystatus in statuslist:
            if entrystatus['status'] is not None:
                allstatus.append(entrystatus['status'])
        print(''.join(allstatus), end='')
        return 0

    def cmd_set(self, target_path, argv, config=None):
        """
        command for modifying/adding a single entry
        :param target_path: where to look for config
        :param config: config to use instead of parsing file anew
        """
        usage = ("usage: %s set [localname] [[SCM-URI] --(%ssvn|hg|git|bzr) [--version=VERSION]?]?" %
                 (self.progname, 'detached|' if self.allow_other_element else ''))
        parser = OptionParser(
            usage=usage,
            formatter=IndentedHelpFormatterWithNL(),
            description=__MULTIPRO_CMD_DICT__["set"] + """
The command will infer whether you want to add or modify an entry. If
you modify, it will only change the details you provide, keeping
those you did not provide. if you only provide a uri, will use the
basename of it as localname unless such an element already exists.

The command only changes the configuration, to checkout or update
the element, run %(progname)s update afterwards.

Examples:
$ %(progname)s set robot_model --hg https://kforge.ros.org/robotmodel/robot_model
$ %(progname)s set robot_model --version-new robot_model-1.7.1
%(detached)s
""" % { 'progname': self.progname,
        'detached': '$ %s set robot_model --detached' % (self.progname
                                                         if self.allow_other_element
                                                         else '')},
            epilog="See: http://www.ros.org/wiki/rosinstall for details\n")
        if self.allow_other_element:
            parser.add_option("--detached", dest="detach", default=False,
                              help="make an entry unmanaged (default for new element)",
                              action="store_true")
        parser.add_option("-v", "--version-new", dest="version", default=None,
                          help="point SCM to this version",
                          action="store")
        parser.add_option("--git", dest="git", default=False,
                          help="make an entry a git entry",
                          action="store_true")
        parser.add_option("--svn", dest="svn", default=False,
                          help="make an entry a subversion entry",
                          action="store_true")
        parser.add_option("--hg", dest="hg", default=False,
                          help="make an entry a mercurial entry",
                          action="store_true")
        parser.add_option("--bzr", dest="bzr", default=False,
                          help="make an entry a bazaar entry",
                          action="store_true")
        parser.add_option("-y", "--confirm", dest="confirm", default='',
                          help="Do not ask for confirmation",
                          action="store_true")
        parser.add_option("-u", "--update", dest="do_update", default=False,
                          help="update repository after set",
                          action="store_true")
        # -t option required here for help but used one layer above, see cli_common
        parser.add_option(
            "-t", "--target-workspace", dest="workspace", default=None,
            help="which workspace to use",
            action="store")
        (options, args) = parser.parse_args(argv)
        if not self.allow_other_element:
            options.detach = False

        if len(args) > 2:
            print("Error: Too many arguments.")
            print(parser.usage)
            return -1

        if config is None:
            config = multiproject_cmd.get_config(
                target_path,
                additional_uris=[],
                config_filename=self.config_filename)
        elif config.get_base_path() != target_path:
            raise MultiProjectException(
                "Config path does not match %s %s " % (config.get_base_path(),
                                                       target_path))

        scmtype = None
        count_scms = 0
        if options.git:
            scmtype = 'git'
            count_scms += 1
        if options.svn:
            scmtype = 'svn'
            count_scms += 1
        if options.hg:
            scmtype = 'hg'
            count_scms += 1
        if options.bzr:
            scmtype = 'bzr'
            count_scms += 1
        if options.detach:
            count_scms += 1
        if count_scms > 1:
            parser.error(
                "You cannot provide more than one scm provider option")

        if len(args) == 0:
            parser.error("Must provide a localname")

        element = select_element(config.get_config_elements(), args[0])

        uri = None
        if len(args) == 2:
            uri = args[1]
        version = None
        if options.version is not None:
            version = options.version.strip("'\"")

        # create spec object
        if element is None:
            if scmtype is None and not self.allow_other_element:
                # for modification, not re-stating the scm type is
                # okay, for new elements not
                parser.error("You have to provide one scm provider option")
            # asssume is insert, choose localname
            localname = os.path.normpath(args[0])
            rel_path = os.path.relpath(os.path.realpath(localname),
                                       os.path.realpath(config.get_base_path()))
            if os.path.isabs(localname):
                # use shorter localname for folders inside workspace
                if not rel_path.startswith('..'):
                    localname = rel_path
            else:
                # got a relative path as localname, could point to a dir or be
                # meant relative to workspace
                if not samefile(os.getcwd(), config.get_base_path()):
                    if os.path.isdir(localname):
                        parser.error(
                            "Cannot decide which one you want to add:\n%s\n%s" % (
                                os.path.abspath(localname),
                                os.path.join(config.get_base_path(), localname)))
                    if not rel_path.startswith('..'):
                        localname = rel_path

            spec = PathSpec(local_name=localname,
                            uri=normalize_uri(uri, config.get_base_path()),
                            version=version,
                            scmtype=scmtype)
        else:
            # modify
            localname = element.get_local_name()
            old_spec = element.get_path_spec()
            if options.detach:
                spec = PathSpec(local_name=localname)
            else:
                # '' evals to False, we do not want that
                if version is None:
                    version = old_spec.get_version()
                spec = PathSpec(local_name=localname,
                                uri=normalize_uri(uri or old_spec.get_uri(),
                                                  config.get_base_path()),
                                version=version,
                                scmtype=scmtype or old_spec.get_scmtype(),
                                path=old_spec.get_path())
            if spec.get_legacy_yaml() == old_spec.get_legacy_yaml():
                if not options.detach and spec.get_scmtype() is not None:
                    parser.error(
                        "Element %s already exists, did you mean --detached ?" % spec)
                parser.error("Element %s already exists" % spec)

        (newconfig, path_changed) = prompt_merge(
            target_path,
            additional_uris=[],
            additional_specs=[spec],
            merge_strategy='MergeReplace',
            confirmed=options.confirm,
            confirm=not options.confirm,
            show_verbosity=False,
            show_advanced=False,
            config_filename=self.config_filename,
            config=config,
            allow_other_element=self.allow_other_element)

        if newconfig is not None:
            print("Overwriting %s" % os.path.join(
                newconfig.get_base_path(), self.config_filename))
            shutil.copy(
                os.path.join(newconfig.get_base_path(), self.config_filename),
                "%s.bak" % os.path.join(newconfig.get_base_path(), self.config_filename))
            self.config_generator(newconfig, self.config_filename)
            if options.do_update:
                install_success = multiproject_cmd.cmd_install_or_update(
                                        newconfig, localnames=[localname])
                if not install_success:
                    print("Warning: installation encountered errors.")
                print("\nupdate complete.")
            elif (spec.get_scmtype() is not None):
                print("Config changed, remember to run '%s update %s' to update the folder from %s" %
                      (self.progname, spec.get_local_name(), spec.get_scmtype()))
        else:
            print("New element %s could not be added, " % spec)
            return 1
        # auto-install not a good feature, maybe make an option
        # for element in config.get_config_elements():
        #   if element.get_local_name() == spec.get_local_name():
        #     if element.is_vcs_element():
        #       element.install(checkout=not os.path.exists(os.path.join(config.get_base_path(), spec.get_local_name())))
        #       break
        return 0

    def cmd_update(self, target_path, argv, config=None):
        parser = OptionParser(usage="usage: %s update [localname]*" % self.progname,
                              formatter=IndentedHelpFormatterWithNL(),
                              description=__MULTIPRO_CMD_DICT__["update"] + """

This command calls the SCM provider to pull changes from remote to
your local filesystem. In case the url has changed, the command will
ask whether to delete or backup the folder.

Examples:
$ %(progname)s update -t ~/fuerte
$ %(progname)s update robot_model geometry
""" % {'progname': self.progname},
                              epilog="See: http://www.ros.org/wiki/rosinstall for details\n")
        parser.add_option("--delete-changed-uris", dest="delete_changed",
                          default=False,
                          help="Delete the local copy of a directory before changing uri.",
                          action="store_true")
        parser.add_option("--abort-changed-uris", dest="abort_changed",
                          default=False,
                          help="Abort if changed uri detected",
                          action="store_true")
        parser.add_option("--continue-on-error", dest="robust",
                          default=False,
                          help="Continue despite checkout errors",
                          action="store_true")
        parser.add_option("--backup-changed-uris", dest="backup_changed",
                          default='',
                          help="backup the local copy of a directory before changing uri to this directory.",
                          action="store")
        parser.add_option("-m", "--timeout", dest="timeout",
                          default=None,
                          help="How long to wait for each repo before failing [seconds]",
                          action="store", type=float)
        parser.add_option("-j", "--parallel", dest="jobs",
                          default=1,
                          help="How many parallel threads to use for installing",
                          action="store")
        parser.add_option("-v", "--verbose", dest="verbose",
                          default=False,
                          help="Whether to print out more information",
                          action="store_true")
        # -t option required here for help but used one layer above, see cli_common
        parser.add_option("-t", "--target-workspace", dest="workspace",
                          default=None,
                          help="which workspace to use",
                          action="store")
        (options, args) = parser.parse_args(argv)

        if config is None:
            config = multiproject_cmd.get_config(
                target_path,
                additional_uris=[],
                config_filename=self.config_filename)
        elif config.get_base_path() != target_path:
            raise MultiProjectException("Config path does not match %s %s " % (
                config.get_base_path(),
                target_path))
        success = True
        mode = _get_mode_from_options(parser, options)
        if args == []:
            # None means no filter, [] means filter all
            args = None
        if success:
            install_success = multiproject_cmd.cmd_install_or_update(
                config,
                localnames=args,
                backup_path=options.backup_changed,
                mode=mode,
                robust=options.robust,
                num_threads=int(options.jobs),
                timeout=options.timeout,
                verbose=options.verbose)
            if install_success or options.robust:
                return 0
        return 1

    def cmd_remove(self, target_path, argv, config=None):
        parser = OptionParser(usage="usage: %s remove [localname]*" % self.progname,
                              formatter=IndentedHelpFormatterWithNL(),
                              description=__MULTIPRO_CMD_DICT__["remove"] + """
The command removes entries from your configuration file, it does not affect your filesystem.
""",
                              epilog="See: http://www.ros.org/wiki/rosinstall for details\n")
        # -t option required here for help but used one layer above, see cli_common
        parser.add_option(
            "-t", "--target-workspace", dest="workspace", default=None,
            help="which workspace to use",
            action="store")
        (_, args) = parser.parse_args(argv)
        if len(args) < 1:
            print("Error: Too few arguments.")
            print(parser.usage)
            return -1

        if config is None:
            config = multiproject_cmd.get_config(
                target_path,
                additional_uris=[],
                config_filename=self.config_filename)
        elif config.get_base_path() != target_path:
            raise MultiProjectException(
                "Config path does not match %s %s " % (config.get_base_path(),
                                                       target_path))
        success = True
        elements = select_elements(config, args)
        for element in elements:
            if not config.remove_element(element.get_local_name()):
                success = False
                print("Bug: No such element %s in config, aborting without changes" %
                      (element.get_local_name()))
                break
        if success:
            print("Overwriting %s" % os.path.join(config.get_base_path(),
                                                  self.config_filename))
            shutil.copy(os.path.join(config.get_base_path(),
                                     self.config_filename),
                        "%s.bak" % os.path.join(config.get_base_path(),
                                                self.config_filename))
            self.config_generator(config, self.config_filename)
            print("Removed entries %s" % args)

        return 0

    def cmd_snapshot(self, target_path, argv, config=None):
        parser = OptionParser(
            usage="usage: %s info [localname]* [OPTIONS]" % self.progname,
            formatter=IndentedHelpFormatterWithNL(),
            description=__MULTIPRO_CMD_DICT__["export"] + """
Exports the current workspace.

The --exact option will cause the output to contain the exact commit uuid for
each version-controlled entry. The --spec option tells wstool to look at the
workspace .rosinstall for versioning info instead of the workspace.

Examples:
$ %(prog)s export
$ %(prog)s export -t ~/ros/fuerte
$ %(prog)s export --exact
""" % {'prog': self.progname, 'opts': ONLY_OPTION_VALID_ATTRS},
            epilog="See: http://www.ros.org/wiki/rosinstall for details\n")
        parser.add_option(
            "-o", "--output", dest="output_filename", default=None,
            help="Write the .rosinstall export to the specified file",
            action="store")
        parser.add_option(
            "-t", "--target-workspace", dest="workspace", default=None,
            help="which workspace to use",
            action="store")
        parser.add_option(
            "--exact", dest="exact", default=False, action="store_true",
            help="export exact commit hashes instead of branch names")
        parser.add_option(
            "--spec", dest="spec", default=False, action="store_true",
            help="export version from workspace spec instead of current")

        (options, _) = parser.parse_args(argv)

        if config is None:
            config = multiproject_cmd.get_config(
                target_path,
                additional_uris=[],
                config_filename=self.config_filename)
        elif config.get_base_path() != target_path:
            raise MultiProjectException("Config path does not match %s %s " %
                                        (config.get_base_path(), target_path))

        # TODO: Check for workspace differences and issue warnings?

        fname = options.output_filename
        if fname:
            fname = os.path.abspath(fname)
            print("Writing %s" % fname)
        self.config_generator(config, fname, get_header(self.progname),
                              spec=options.spec, exact=options.exact,
                              vcs_only=True)

        return 0

    def cmd_info(self, target_path, argv, reverse=True, config=None):
        parser = OptionParser(
            usage="usage: %s info [localname]* [OPTIONS]" % self.progname,
            formatter=IndentedHelpFormatterWithNL(),
            description=__MULTIPRO_CMD_DICT__["info"] + """

The Status (S) column shows
 x  for missing
 L  for uncommited (local) changes
 V  for difference in version and/or remote URI
 C  for difference in local and remote versions

The 'Version-Spec' column shows what tag, branch or revision was given
in the .rosinstall file. The 'UID' column shows the unique ID of the
current (and specified) version. The 'URI' column shows the configured
URL of the repo.

If status is V, the difference between what was specified and what is
real is shown in the respective column. For SVN entries, the url is
split up according to standard layout (trunk/tags/branches).

When given one localname, just show the data of one element in list form.
This also has the generic properties element which is usually empty.

The --only option accepts keywords: %(opts)s

Examples:
$ %(prog)s info -t ~/ros/fuerte
$ %(prog)s info robot_model
$ %(prog)s info --yaml
$ %(prog)s info --only=path,cur_uri,cur_revision robot_model geometry
""" % {'prog': self.progname, 'opts': ONLY_OPTION_VALID_ATTRS},
            epilog="See: http://www.ros.org/wiki/rosinstall for details\n")
        parser.add_option(
            "--root", dest="show_ws_root", default=False,
            help="Show workspace root path",
            action="store_true")
        parser.add_option(
            "--data-only", dest="data_only", default=False,
            help="Does not provide explanations",
            action="store_true")
        parser.add_option(
            "-s", "--short", dest="short", default=False,
            help="Shows simplified version info table.",
            action="store_true")
        parser.add_option(
            "--only", dest="only", default=False,
            help="Shows comma-separated lists of only given comma-separated attribute(s).",
            action="store")
        parser.add_option(
            "--yaml", dest="yaml", default=False,
            help="Shows only version of single entry. Intended for scripting.",
            action="store_true")
        parser.add_option(
            "--fetch", dest="fetch", default=False,
            help="When used, retrieves version information from remote (takes longer).",
            action="store_true")
        parser.add_option(
            "-u", "--untracked", dest="untracked",
            default=False,
            help="Also show untracked files as modifications",
            action="store_true")
        # -t option required here for help but used one layer above, see cli_common
        parser.add_option(
            "-t", "--target-workspace", dest="workspace", default=None,
            help="which workspace to use",
            action="store")
        parser.add_option(
            "-m", "--managed-only", dest="unmanaged", default=True,
            help="only show managed elements",
            action="store_false")
        (options, args) = parser.parse_args(argv)

        if config is None:
            config = multiproject_cmd.get_config(
                target_path,
                additional_uris=[],
                config_filename=self.config_filename)
        elif config.get_base_path() != target_path:
            raise MultiProjectException("Config path does not match %s %s " %
                                        (config.get_base_path(), target_path))

        if options.show_ws_root:
            print(config.get_base_path())
            return 0

        if args == []:
            args = None

        if options.only:
            only_options = options.only.split(",")
            if only_options == '':
                parser.error('No valid options given')
            lines = get_info_table_raw_csv(config,
                                           parser,
                                           properties=only_options,
                                           localnames=args)
            print('\n'.join(lines))
            return 0
        elif options.yaml:
            # TODO: Not sure what this does, used to be cmd_snapshot,
            # but that command was not implemented.
            source_aggregate = multiproject_cmd.cmd_snapshot(config,
                                                             localnames=args)
            print(yaml.safe_dump(source_aggregate, default_flow_style=None), end='')
            return 0

        # this call takes long, as it invokes scms.
        outputs = multiproject_cmd.cmd_info(config,
                                            localnames=args,
                                            untracked=options.untracked,
                                            fetch=options.fetch)
        if args and len(args) == 1:
            # if only one element selected, print just one line
            print(get_info_list(config.get_base_path(),
                                outputs[0],
                                options.data_only))
            return 0

        columns = None
        if options.short:
            columns = ['localname', 'status', 'version']

        header = 'workspace: %s' % (target_path)
        print(header)
        table = get_info_table(config.get_base_path(),
                               outputs,
                               options.data_only,
                               reverse=reverse,
                               selected_headers=columns)
        if table is not None and table != '':
           print("\n%s" % table)

        if options.unmanaged:
            outputs2 = multiproject_cmd.cmd_find_unmanaged_repos(config)
            table2 = get_info_table(config.get_base_path(),
                                   outputs2,
                                   options.data_only,
                                   reverse=reverse,
                                   unmanaged=True,
                                   selected_headers=columns)
            if table2 is not None and table2 != '':
                print("\nAlso detected these repositories in the workspace, add using '%s scrape' or '%s set':\n\n%s" % (self.progname, self.progname, table2))

        return 0

    def cmd_scrape(self, target_path, argv, config=None):
        """
        command for adding yet unamanaged repos under workspace root to managed repos.
        :param target_path: where to look for config
        :param config: config to use instead of parsing file anew
        """
        usage = ("usage: %s scrape [OPTIONS]" % self.progname)
        parser = OptionParser(
            usage=usage,
            description=__MULTIPRO_CMD_DICT__["scrape"],
            epilog="See: http://www.ros.org/wiki/rosinstall for details\n")
        parser.add_option("-y", "--confirm", dest="confirm", default='',
                          help="Do not ask for confirmation",
                          action="store_true")
        # -t option required here for help but used one layer above, see cli_common
        parser.add_option(
            "-t", "--target-workspace", dest="workspace", default=None,
            help="which workspace to use",
            action="store")
        (options, args) = parser.parse_args(argv)

        if config is None:
            config = multiproject_cmd.get_config(
                target_path,
                additional_uris=[],
                config_filename=self.config_filename)
        elif config.get_base_path() != target_path:
            raise MultiProjectException(
                "Config path does not match %s %s " % (config.get_base_path(),
                                                       target_path))

        elems = multiproject_cmd.cmd_find_unmanaged_repos(config)
        if not elems:
            raise MultiProjectException(
                "No unmanaged repos found below '%s'" % (config.get_base_path()))
        for elem in elems:
            elem_abs_path = os.path.join(config.get_base_path(), elem['localname'])
            if os.path.isdir(elem_abs_path):
                args = [elem_abs_path, elem['scm'], elem['uri']]
                if (options.confirm):
                    args.append('-y')
                self.cmd_set(target_path, args)
        return 0
