This file is indexed.

/usr/lib/python2.7/dist-packages/wstool/multiproject_cli.py is in python-wstool 0.1.12-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
# 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",
    "snapshot": "write a file specifying repositories to have the version they currently have",
    "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', '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")
        (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

        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,
            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.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")
        # -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,
                                               scm_types=scm_types,
                                               shell=options.shell)

        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()
            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:
                if output['stderr'] is None:
                    continue
                lines = output['stderr'].strip().split('\n')
                lines = add_localname_prefix(localname, lines)
                sys.stderr.write('\n'.join(lines))
                sys.stderr.write('\n')
        return 0

    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("--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")
        (_, 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_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(
            "--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,
                                           properties=only_options,
                                           localnames=args)
            print('\n'.join(lines))
            return 0
        elif options.yaml:
            source_aggregate = multiproject_cmd.cmd_snapshot(config,
                                                             localnames=args)
            print(yaml.safe_dump(source_aggregate), 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

        header = 'workspace: %s' % (target_path)
        print(header)
        table = get_info_table(config.get_base_path(),
                               outputs,
                               options.data_only,
                               reverse=reverse)
        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)
            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