Source

hgdeps / deps.py

   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
# deps.py -- Mercurial extension for repository dependencies
#
# Copyright (C) 2008 Aleix Conchillo Flaque <aleix@member.fsf.org>
# Copyright (C) 2009 Martin Vejnar <avakar@ratatanek.cz>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

'''create and manage versioned repository dependencies

For each revision there is an associated list of dependencies. Each entry
fully specifies the state of a dependency; it lists its alias,
the path to the directory it should be located in, and its revision.

An alias is used to refer to a particular dependency across all revisions.
Every alias is associated with a remote location or a command, from or with
which the dependency can be fetched.

Dependency lists and alias mapping are both stored in a versioned file
called '.hgdeps'. The file is divided to sections, each of which begins
with '[SECTIONNAME]' header.

Special section 'aliases' contains alias mapping. Each line consists
of alias name, remote repository type, and its remote location.
The lines are parsed with shlex. An example:

    [aliases]
    spam hg  http://example.org/hg/spam-stable
    eggs cmd 'svn co http://svn.example.com/eggs/trunk/@$rev $dest'

Aliases can be managed using 'hg depalias', 'hg depaliases',
and 'hg deprmalias' commands.

The rest of the sections represent dependency lists. The name of a section
should be a hexadecimal nodeid located in the local repository.

    [c1d2ab11121e30a80d4703969b81d3db8be4ac0d]
    6976733213056a95ab3395fb4663c10987606814 spam lib/spam
    73986 eggs lib/contrib/bacon/eggs

Use 'hg dep' command to move dependencies around the working dir.
The '.hgdeps' file can be automatically updated using 'hg depci'.

Use 'hg depup' after 'hg up' to update dependencies according
to the proper dependency list.
'''

import os
import os.path
import re
import shutil

from string import Template

import mercurial.node
import mercurial.revlog
from mercurial.i18n import _
from mercurial import cmdutil, commands, fancyopts, hg, util, localrepo
from mercurial import context
from mercurial.repo import RepoError

def deps(ui, repo, tag = None, **opts):
    '''create and manage versioned repository dependencies

    This extension is useful when a repository might depend on some
    external dependencies: other repositories (Mercurial, CVS,
    Subversion...), files not handled by a SCM tool or some other
    dependencies.

    To enable this extension, add this to your global .hgrc file (or
    to your repository .hg/hgrc file):

    [extensions]
    hgext.deps =
    # or, if deps.py is not in the hgext dir:
    # deps = /path/to/deps.py

    In order to define these external dependencies, you need to add a
    section [deps] in your repository .hg/hgrc file (or in the global
    .hgrc) where you will define how to find them. As an example,
    let's say that our repository depends on two external libraries
    managed by different SCM tools: 'libfoo' managed by Mercurial and
    'libbar' managed by CVS.

    [deps]
    aliases = libfoo, libbar
    alias.libfoo = /path/to/libfoo
    alias.libbar = :pserver:anonymous@cvs.server.org:/sources/bar
    alias.libbar.command = cvs -z3 -d$source co -r $rev -d $dest bar

    Two aliases have been defined, one for each library, and also the
    sources where the libraries can be obtained. 'libbar' has two
    options: the library location and the CVS command to use in order
    to get the library. For 'libfoo' only a path to the Mercurial
    repository has been specified. $rev, $source, and $dest are
    substitution placeholders and will be explained later.

    Once the location of the depedencies have been defined, depedency
    lists can be created. A dependency list has an associated
    name. Following the example above, two depedency lists will be
    created, one for version 0.9.1 of our repository and another for
    version 1.0. 0.9.1 and 1.0 will be used as the name of the lists.

    [1.0]
    f24139319bdb    libfoo    lib/foo
    v0r8_0          libbar    lib/bar

    [0.9.1]
    3a9b061bada1    libfoo    lib/foo
    v0r7_8          libbar    lib/bar

    A dependency is defined by three fields: a revision name, the
    alias of the external dependency and a destination directory. The
    alias must be one of the aliases defined in the [deps] section
    (see above). The revision name will be substituted for the
    placeholder $rev also seen before. For Mercurial, the revision
    name will just be a Mercurial revision of the external
    repository. Finally, the destination directory will be substituted
    for $dest.

    To facilitate version control, distribution, and merging of
    dependencies, they are stored as a file named '.hgdeps' which is
    managed similarly to other project files and can be hand-edited if
    necessary.

    ----

    If no name is given to this command, a list of all dependencies
    will be shown. A given name will only display the dependencies for
    that name.

    To add a dependency for a given name, the external repository
    alias, a revision of that repository and a future destination path
    must be provided.

    To get the external dependencies for a given name, run the
    'depsclone' command.
    '''
    config = _get_config(ui, repo)

    if not tag and config.is_empty():
        return

    alias = opts['alias']
    rev = opts['rev']
    dest = opts['dest']

    if not tag:
        config.print_all()
    else:
        dep = None
        if alias and rev and dest:
            dep = dependency(rev, alias, dest)

        if not dep and (alias or rev or dest):
            raise util.Abort(_('missing parameters '
                               '(revision = %s, alias = %s, path = %s)'
                               % (rev, alias, dest)))

        if opts['remove']:
            config.remove(tag, dep)
            _save_config(ui, repo, config)
        elif not dep:
            config.print_list(tag)
        else:
            config.add(tag, dep)
            _save_config(ui, repo, config)


def depupdate(ui, repo, rev=None):
    '''update dependencies to a configured state
    
    Loads the dependency list from .hgdeps file and applies it.
    
    The .hgdeps file contains a set of named dependency lists.
    If given, the REV parameter is used to lookup the list.
    Should the lookup fail, REV is assumed to identify a revision.
    If REV is not specified, current revision is used.
    
    The long form of a revision identifier is used to lookup
    the dependency list. If the lookup fails, the search continues
    with the parent revision. The search terminates at the first merge.
    
    If a dependency list is successfully retrieved, the dependencies
    are updated as if by using the 'hg dep' commnad.
    '''
    
    wlock = lock = None
    try:
        wlock = repo.wlock()
        lock = repo.lock()
        
        config = _get_config(ui, repo)
        deplist = _find_deplist(ui, repo, config, rev, default=None)
        
        if deplist is None:
            if rev is not None:
                raise util.Abort(_('no appropriate dependency list was found'))
            else:
                deplist = []
        
        manifest = _load_manifest(repo)
        try:
            for item in manifest.values():
                if item.dest:
                    scmhandler = _get_scm_handler(ui, repo, manifest, item.alias_name)
                    scmhandler.move(dest=None)
            
            for dependency in deplist:
                scmhandler = _get_scm_handler(ui, repo, manifest, dependency.alias, config.aliases)
                scmhandler.fetch(config.aliases, dependency.rev)
                scmhandler.update(dependency.rev)
                scmhandler.move(dependency.dest)
        finally:
            manifest.save(repo)
    finally:
        if lock: lock.release()
        if wlock: wlock.release()

def depstatus(ui, repo):
    '''show changes to the working dependency list
    
    Show status of dependencies in the dependency list.
    
    The dependencies are written in '<alias> <rev> <dir>' format,
    unless the dependency is not present, in which case <rev> and <dir>
    are omitted. The original values are shown in parentheses.
    The directory path is relative to the repository root
    and uses '/' as a path component separator.
    
    The unmodified dependencies are not shown unless -v/--verbose
    option is used.
    
    The codes used to show the status of dependecies are:
    M = modified
    A = added
    R = removed
      = unmodified
    '''
    manifest = _load_manifest(repo)
    config = _get_config(ui, repo)
    deplist = _find_deplist(ui, repo, config, rev=None, default=[])
    
    for item in manifest.values():
        if item.dest is None:
            continue

        for dep_ in deplist:
            if dep_.alias == item.alias_name:
                dep = dep_
                break
        else:
            dep = None
        
        scmhandler = _get_scm_handler(ui, repo, manifest, item.alias_name)
        rev = scmhandler.get_revision()
        alias = config.aliases.get(item.alias_name)
        
        if dep is None:
            ui.write("A %s %s %s\n" % (item.alias_name, item.dest,
                _readable_rev(item.scmtype, rev)))
        elif dep.dest != item.dest or rev != dep.rev:
            ui.write("M %s %s %s (%s %s)\n" % (item.alias_name,
                item.dest, _readable_rev(item.scmtype, rev),
                dep.dest,
                _readable_rev(alias.scmtype, dep.rev) if alias else dep.rev))
        else:
            ui.note("  %s %s %s\n" % (item.alias_name, item.dest,
                _readable_rev(item.scmtype, rev)))
    
    for dep in deplist:
        if dep.alias not in manifest or manifest[dep.alias].dest is None:
            alias = config.aliases.get(dep.alias)
            ui.write('R %s (%s %s)\n' % (dep.alias, dep.dest,
                _readable_rev(alias.scmtype, dep.rev) if alias else dep.rev))

def depcommit(ui, repo, commit, **commitopts):
    '''save dependency state
    
    Update the .hgdeps file to reflect the current state of dependecies.
    
    The current dependency list is appended to the .hgdeps file.
    The list is tagged with the revision of the parent
    of the working directory.
    
    If the dependency list is unmodified, the command is a no-op.
    
    The command will not work, if the working copy has either
    none or more than one parents.
    '''
    manifest = _load_manifest(repo)
    deplist = []
    for item in manifest.itervalues():
        if item.dest is None:
            continue
        
        scmhandler = _get_scm_handler(ui, repo, manifest, item.alias_name)
        rev = scmhandler.get_revision()
        
        deplist.append(dependency(rev, item.alias_name, item.dest))
    deplist.sort()
    
    config = _get_config(ui, repo)
    old_deplist = _find_deplist(ui, repo, config, rev=None, default=[])
    old_deplist.sort()
    
    if old_deplist != deplist:
        parents = context.workingctx(repo).parents()
        if len(parents) != 1:
            raise util.Abort(_('cannot commit dependencies on a merged working copy'))
        rev = mercurial.node.hex(parents[0].node())
        
        config.set_tag(rev, deplist)
        _save_config(ui, repo, config)
        
        if commit:
            if not commitopts['message'] and not commitopts['logfile']:
                commitopts['message'] = 'Updated dependency list for changeset %s' % rev[:12]
            mercurial.commands.commit(ui, repo, '.hgdeps', **commitopts)

def depalias(ui, repo, alias, location, type):
    '''bind an alias to a source location
    
    Add or modify a binding between an alias and a source of
    a dependency. The binding is immediately recorded in 'aliases' section
    of .hgdeps file.
    
    By default, the dependency is assumed to be a Mercurial repository.
    You can set a different dependency type using the -t parameter.
    '''
    wlock = repo.wlock()
    try:
        config = _get_config(ui, repo)
        config.aliases.add_versioned(alias, type, location, args=[])
        _save_config(ui, repo, config)
    finally:
        wlock.release()

def depaliases(ui, repo):
    '''list dependency aliases
    
    Print the list of all known dependency aliases. The list is formatted
    as follows:
    
        [*]<alias> <type> <source-location>
    
    Asterisks mark unversioned bindings (those loaded from hgrc).
    '''
    config = _get_config(ui, repo)
    for alias_name in config.aliases:
        alias = config.aliases[alias_name]
        if alias.scmtype == '-':
            continue
        
        if not alias.is_versioned():
            ui.write('*')
        ui.write(alias.versioned_text())

def deprmalias(ui, repo, *aliases):
    '''remove dependency aliases
    
    Remove aliases from from the 'aliases' section in .hgdeps file.
    If a specified alias does not exist, do nothing.
    '''
    wlock = repo.wlock()
    try:
        config = _get_config(ui, repo)
        for alias in aliases:
            if alias in config.aliases:
                if config.aliases[alias].is_versioned():
                    ui.note(_('removing alias: %s\n') % alias)
                    config.aliases.add_versioned(alias, '-', '-', '')
                else:
                    ui.status(_('skipping non-versioned alias: %s\n') % alias)
            else:
                ui.status(_('skipping undefined alias: %s\n') % alias)
        _save_config(ui, repo, config)
    finally:
        wlock.release()

def dep(ui, repo, alias_name, dest, rev=None):
    '''fetch or move a dependency to a specified destination
    
    Updates the dependency to a given revision and moves it to
    the specified directory. If the depenency is already fetched,
    the revision parameter may be omitted, in which case no update occurs.
    '''
    wlock = lock = None
    try:
        wlock = repo.wlock()
        lock = repo.lock()
        
        config = _get_config(ui, repo)
        
        if alias_name not in config.aliases:
            raise util.Abort(_('undefined alias: %s') % alias)
        
        dest = _normpath(dest)
        if not dest or dest == '.' or dest.find('..') != -1:
            raise util.Abort(_('the path must be relative to and contained within the repository root'))
        
        manifest = _load_manifest(repo)
        try:
            scmhandler = _get_scm_handler(ui, repo, manifest, alias_name, config.aliases)
            
            if rev is not None:
                ui.debug("fetching dependency to version: %s\n" % rev)
                scmhandler.fetch(config.aliases, rev)
                ui.debug("updating dependency to version: %s\n" % rev)
                scmhandler.update(rev)
            elif alias_name not in manifest:
                raise util.Abort(_('unfetched dependency: %s (specify revision to update to)')
                    % alias_name)
            
            scmhandler.move(dest)
        finally:
            manifest.save(repo)
    finally:
        if lock: lock.release()
        if wlock: wlock.release()

def depremove(ui, repo, *aliases):
    '''remove dependencies from the working copy
    
    The aliases specified are not deleted, instead they are moved
    to '.hg/deps' directory and can be quickly retrieved with 'hg dep'.
    '''
    wlock = lock = None
    try:
        wlock = repo.wlock()
        lock = repo.lock()
        
        manifest = _load_manifest(repo)
        try:
            for alias in aliases:
                if alias in manifest:
                    scmhandler = _get_scm_handler(ui, repo, manifest, alias)
                    scmhandler.move(dest=None)
                else:
                    ui.note(_('dependency is not present: %s\n') % alias)
        finally:
            manifest.save(repo)
    finally:
        if lock: lock.release()
        if wlock: wlock.release() 

def deppurge(ui, repo, *aliases):
    '''delete dependencies
    
    The specified dependencies are completely removed from the disk and
    are not saved to '.hg/deps' directory.
    '''
    
    wlock = lock = None
    try:
        wlock = repo.wlock()
        lock = repo.lock()
        
        config = _get_config(ui, repo)
        manifest = _load_manifest(repo)
        try:
            for alias in aliases:
                if alias in manifest:
                    scmhandler = _get_scm_handler(ui, repo, manifest, alias)
                    scmhandler.purge()
                else:
                    ui.status(_('dependency is not present: %s\n') % alias)
        finally:
            manifest.save(repo)
    finally:
        if lock: lock.release()
        if wlock: wlock.release()


# Internal classes

def _get_config(ui, repo):
    config = deps_config(ui)
    
    # Retrieve the set of head nodes containing
    # .hgdeps file. The tip node should be processed
    # last. The snippet is copied from
    # mercurial.localrepo.locarepository._hgtagsnodes
    heads = repo.heads()
    heads.reverse()
    last = {}
    filenodes = []
    for node in heads:
        c = context.changectx(repo, node)
        try:
            fnode = c.filenode('.hgdeps')
        except mercurial.revlog.LookupError:
            continue
        filenodes.append((node, fnode))
        if fnode in last:
            filenodes[last[fnode]] = None
        last[fnode] = len(filenodes) - 1
    
    import StringIO
    f = None
    for node, fnode in filenodes:
        f = (f and f.filectx(fnode) or
             repo.filectx('.hgdeps', fileid=fnode))
        config.load(StringIO.StringIO(f.data()))
    
    status = repo.status()
    if '.hgdeps' not in status[0] and '.hgdeps' not in status[1]:
        return config
    
    filename = os.path.join(repo.root, '.hgdeps')
    try:
        f = open(filename, 'rb')
    except IOError:
        return config
    
    try:
        config.load(f)
    finally:
        f.close()
    
    return config

def _save_config(ui, repo, config):
    text = config.get_text()
    
    f = open(os.path.join(repo.root, '.hgdeps'), 'wb')
    try:
        f.write(text)
    finally:
        f.close()
    
    if repo.dirstate['.hgdeps'] == '?':
        repo.add(['.hgdeps'])

def _find_deplist(ui, repo, config, rev, default):
    if rev is not None and config.has_tag(rev):
        return config.tag(rev)
    
    if rev is None:
        parents = context.workingctx(repo).parents()
        chctx = parents[0] if len(parents) == 1 else None
    else:
        chctx = context.changectx(repo, repo.lookup(rev))
    
    while chctx is not None:
        tag = mercurial.node.hex(chctx.node())
        if config.has_tag(tag):
            return config.tag(tag)
        
        # Filter out null parents manually,
        # the behavior of parents() differ between
        # hg-1.0 and hg-1.2.
        parents = [parent for parent in chctx.parents()
            if parent.node() != mercurial.node.nullid]
        if not parents:
            chctx = context.changectx(repo, mercurial.node.nullid)
        elif len(parents) == 1:
            chctx = parents[0]
        else:
            chctx = None
    
    return default

def _normpath(path):
    drive, path = os.path.splitdrive(path)
    if drive:
        return None
    
    if os.path.isabs(path):
        return None
    
    head = os.path.normpath(path)
    parts = []
    while head:
        head, tail = os.path.split(head)
        parts.append(tail)
    parts.reverse()
    path = '/'.join(parts)
    return path

class scm_unknown:
    def __init__(self, ui, repo, manifest, alias_name):
        self.ui = ui
        self.repo = repo
        self.manifest = manifest
        self.alias_name = alias_name
        self.alias = None
    
    def _make_deppath(self, dest):
        if dest is None:
            return os.path.join(self.repo.path, 'deps', self.alias_name)
        else:
            return os.path.join(self.repo.root, *dest.split('/'))
    
    def _clean_path(self, dest):
        if not dest:
            return
        
        # dest itself should already be removed,
        # try to remove its parents.
        
        parts = dest.split('/')
        parts.pop()
        while parts:
            path = os.path.join(self.repo.root, *parts)
            try:
                os.rmdir(path)
            except os.error:
                return
            parts.pop()
    
    def get_revision(self):
        return self.manifest[self.alias_name].rev
    
    def readable_rev(rev):
        return rev
    readable_rev = staticmethod(readable_rev)
    
    def fetch(self, aliases, rev):
        self.alias = aliases[self.alias_name]
    
    def update(self, rev):
        raise util.Abort(_('cannot update a dependency of unknown type: %s, %s')
            % (self.alias_name, self.alias.scmtype))
    
    def move(self, dest):
        item = self.manifest[self.alias_name]
        
        old_path = self._make_deppath(item.dest)
        new_path = self._make_deppath(dest)
        
        if old_path == new_path:
            return
        
        tmp_path = self._make_deppath(None)
        
        if old_path != tmp_path:
            shutil.move(old_path, tmp_path)
            self.manifest.set(self.alias_name, item.scmtype, item.rev, None)
            self._clean_path(item.dest)

        if tmp_path != new_path:
            shutil.move(tmp_path, new_path)
            self.manifest.set(self.alias_name, item.scmtype, item.rev, dest)
    
    def purge(self):
        item = self.manifest[self.alias_name]
        path = self._make_deppath(item.dest)
        
        if os.path.exists(path):
            self.ui.note("purging dependency: %s, %s\n" % (self.alias_name, path))
            
            # cannot use shutil.rmtree here,
            # because it fails on read-only files (svn repos).
            import stat
            for dirpath, dirnames, filenames in os.walk(path, topdown=False):
                for filename in filenames:
                    path_ = os.path.join(dirpath, filename)
                    os.chmod(path_, os.lstat(path_).st_mode | stat.S_IWRITE)
                    os.remove(path_)
                for dirname in dirnames:
                    os.rmdir(os.path.join(dirpath, dirname))
            os.rmdir(path)
            
            self._clean_path(item.dest)
        else:
            self.ui.warn("warning: fixing inconsistent manifest file: missing dependency: %s, %s\n"
                % (self.alias_name, path))
        
        del self.manifest[self.alias_name]

class scm_removed(scm_unknown):
    def update(self, rev):
        raise util.Abort(_('removed alias: %s') % self.alias_name)

class scm_hg(scm_unknown):
    def get_revision(self):
        dir = self.manifest.get_dir(self.alias_name)
        path = self._make_deppath(dir)
        
        deprepo = localrepo.localrepository(self.ui, path)
        nodeids = context.workingctx(deprepo).parents()
        return ','.join(mercurial.node.hex(nodeid.node()) for nodeid in nodeids)
    
    def readable_rev(revision):
        return ','.join(nodeid[:12] for nodeid in revision.split(','))
    readable_rev = staticmethod(readable_rev)

    def fetch(self, aliases, rev):
        dir = self.manifest.get_dir(self.alias_name)
        path = self._make_deppath(dir)
        
        create = not os.path.exists(path)
        
        if create:
            parentpath = os.path.split(path)[0]
            if not os.path.exists(parentpath):
                os.makedirs(parentpath)
            self.ui.debug(_('creating a new repository: %s\n') % path)
        
        deprepo = localrepo.localrepository(self.ui, path, create)
        self.manifest.set(self.alias_name, 'hg', '-', dir)
        
        need_pull = True
        try:
            deprepo.lookup(rev)
            need_pull = False
        except mercurial.revlog.LookupError:
            pass
        except RepoError:
            pass
        
        if need_pull:
            self.ui.debug(_('fetching changesets for dependency: %s up to: %s\n')
                % (self.alias_name, rev))
            alias = aliases[self.alias_name]
            if alias.scmtype != 'hg':
                raise util.Abort(_('scmtype mismatch (try running "hg deppurge %s")')
                    % alias.name)
            otherrepo = hg.repository(self.ui, alias.location)
            targetnode = otherrepo.lookup(rev)
            deprepo.pull(otherrepo, heads=[targetnode])
    
    def update(self, rev):
        dir = self.manifest.get_dir(self.alias_name)
        path = self._make_deppath(dir)
        
        current_repo = localrepo.localrepository(self.ui, path)
        hg.update(current_repo, current_repo.lookup(rev))

class scm_cmd(scm_unknown):
    def update(self, rev):
        if self.alias is None:
            raise util.Abort(_('cannot update unfetched dependency: %s') % self.alias_name)
            
        dir = self.manifest.get_dir(self.alias_name)
        path = self._make_deppath(dir)
        
        if self.alias.scmtype != 'cmd':
            raise util.Abort(_('scmtype mismatch (try running "hg deppurge %s")')
                % self.alias.name)

        s = Template(self.alias.location)
        cmd = s.substitute(rev = rev, dest = path)

        self.ui.status(_('running %s\n') % cmd)
        os.system(cmd)
        
        self.manifest.set(self.alias_name, 'cmd', rev, dir)

_scmhandlers = { 'hg': scm_hg, 'cmd': scm_cmd, '-': scm_removed }

def _readable_rev(scmtype, rev):
    scmclass = _scmhandlers.get(scmtype, scm_unknown)
    return scmclass.readable_rev(rev)

def _get_scm_handler(ui, repo, manifest, alias_name, aliases=None):
    if alias_name in manifest:
        scmtype = manifest[alias_name].scmtype
    else:
        assert aliases
        if not alias_name in aliases:
            raise util.Abort(_('cannot determine scmtype for dependency: %s') % alias_name)
        scmtype = aliases[alias_name].scmtype
    
    scmclass = _scmhandlers.get(scmtype, scm_unknown)
    return scmclass(ui, repo, manifest, alias_name)

class ManifestItem:
    def __init__(self, alias_name, scmtype, rev, dest):
        self.alias_name = alias_name
        self.scmtype = scmtype
        self.rev = rev
        self.dest = dest
    
    def get_text(self):
        if self.dest is None:
            return "%s %s %s\n" % (self.alias_name, self.scmtype, self.rev)
        else:
            return "%s %s %s %s\n" % (self.alias_name, self.scmtype, self.rev, self.dest)

def _load_manifest(source):
    res = Manifest()
    res.load(source)
    return res

def _get_manifest_filename(repo):
    return os.path.join(repo.path, 'depsmanifest')

class Manifest(dict):
    def get_text(self):
        res = []
        for item in self.itervalues():
            res.append(item.get_text())
        return ''.join(res)
    
    def get_dir(self, alias):
        item = self.get(alias)
        if item:
            return item.dest
    
    def set(self, alias, scmtype, rev, dir):
        self[alias] = ManifestItem(alias, scmtype, rev, dir)
    
    def load(self, repo):
        filename = _get_manifest_filename(repo)
        
        if not os.path.exists(filename):
            return
        
        f = open(filename, 'rb')
        try:
            for line in f:
                tokens = line.split()
                if not (3 <= len(tokens) <= 4):
                    raise util.Abort("Manifest file is corrupt: %s" % filename)
                alias_name, scmtype, rev = tokens[:3]
                dest = tokens[3] if len(tokens) == 4 else None
                item = ManifestItem(alias_name, scmtype, rev, dest)
                self[alias_name] = item
        finally:
            f.close()
    
    def save(self, repo):
        filename = _get_manifest_filename(repo)
    
        f = open(filename, 'wb')
        try:
            f.write(self.get_text())
        finally:
            f.close()

class dependency:
    def __init__(self, rev, alias, dest):
        self.rev = rev
        self.alias = alias
        self.dest = dest

    def __cmp__(self, other):
        return cmp((self.alias, self.rev, self.dest),
            (other.alias, other.rev, other.dest))

    def __str__(self):
        return '(revision = %s, alias = %s, path = %s)' \
            % (self.rev, self.alias, self.dest)


def _shescape(text):
    return '"' + text.replace('\\', '\\\\').replace('"', '\\"') + '"'

class dep_alias:
    def __init__(self, name, scmtype, location, args, versioned_text):
        self.name = name
        self.scmtype = scmtype
        self.location = location
        self.args = args
        self._versioned_text = versioned_text

        self._opts = {}
        try:
            fancyopts.fancyopts(args, _cloneopts, self._opts)
        except fancyopts.getopt.GetoptError, inst:
            raise util.Abort(_("in alias '%s', %s"
                               % (name, inst.args[0])))

    def is_versioned(self):
        return self._versioned_text is not None
    
    def make_versioned(self):
        self._versioned_text = self.versioned_text()
    
    def versioned_text(self):
        if self._versioned_text:
            return self._versioned_text
    
        if self.args:
            return '%s %s %s %s\n' % (self.name, self.scmtype,
                _shescape(self.location), _shescape(' '.join(self.args)))
        else:
            return '%s %s %s\n' % (self.name, self.scmtype,
                _shescape(self.location))

    def __eq__(self, a):
        return (self.name == a.name) \
            and (self.scmtype == a.scmtype) \
            and (self.location == a.location)

class deps_aliases:
    def __init__(self, ui):
        self._aliases = {}
        self._order = []
        self._read_config(ui)
    
    def __iter__(self):
        return iter(self._order)
    
    def __getitem__(self, name):
        return self._aliases[name]
    
    def __contains__(self, name):
        return name in self._aliases
    
    def add_new(self, name, scmtype, location, args, versioned_text=None):
        alias = dep_alias(name, scmtype, location, args, versioned_text)
        if name in self._aliases:
            self._order.remove(name)
        self._aliases[name] = alias
        self._order.append(name)
        return alias
    
    def add_versioned(self, name, scmtype, location, args):
        alias = self.add_new(name, scmtype, location, args)
        alias.make_versioned()
        return alias
    
    def get(self, name):
        return self._aliases.get(name)
    
    def remove(self, name):
        self._order.remove(name)
        del self._aliases[name]

    def _read_config(self, ui):
        aliases = ui.configlist('deps', 'aliases')
        for name in aliases:
            location = ui.config('deps', 'alias.%s' % name)
            command = ui.config('deps', 'alias.%s.command' % name)
            options = ui.config('deps', 'alias.%s.options' % name)
            if not command:
                scmtype = 'hg'
                args = options.split() if options else []                
            else:
                scmtype = 'cmd'
                args = []
                location = Template(command).safe_substitute(source=location)
            
            self.add_new(name, scmtype, location, args)

class deps_config:
    def __init__(self, ui):
        self._ui = ui
        self._order = []
        self._tags = {}
        self.aliases = deps_aliases(ui)

    def tag(self, tag):
        self._check_tag(tag)
        return self._tags[tag]

    def has_tag(self, tag):
        return self._tags.has_key(tag)
    
    def set_tag(self, tag_name, deplist):
        if tag_name not in self._tags:
            self._add_tag(tag_name)
        
        self._tags[tag_name] = list(deplist)
    
    def is_empty(self):
        return len(self._tags) == 0

    def add(self, tag, dep):
        '''adds a given dependency to an specified list'''
        aliases = deps_aliases(self._ui)

        alias = aliases[dep.alias]

        if not self.has_tag(tag):
            self._add_tag(tag)

        if dep in self._tags[tag]:
            raise util.Abort(_("depedency '%s' already registered for '%s'" % (dep, tag)))

        self._ui.status(_("adding dependency %s for '%s'\n" % (dep, tag)))
        self._tags[tag].append(dep)

    def remove(self, tag, dep):
        '''remove a given dependency from an existent list'''
        self._check_tag(tag)
        try:
            if dep:
                self._ui.status(_("removing dependency %s from '%s'\n" % (dep, tag)))
                self._tags[tag].remove(dep)
                if not self._tags[tag]:
                    self._remove_tag(tag)
            else:
                self._ui.status(_("removing dependency list '%s'\n" % tag))
                self._remove_tag(tag)
        except ValueError:
            raise util.Abort(_("dependency %s is not registered for '%s'" % (dep, tag)))

    def print_all(self):
        '''prints the list of the registered dependency lists'''
        self._ui.status(self.get_text())
    
    def get_text(self):
        res = []
        versioned_aliases = [alias for alias in self.aliases if self.aliases[alias].is_versioned()]
        if versioned_aliases:
            res.append('[aliases]\n')
            for alias in versioned_aliases:
                res.append(self.aliases[alias].versioned_text())
            res.append('\n')
        for t in self._order:
            res.append('[%s]\n' % t)
            for dep in self._tags[t]:
                res.append('%s %s %s\n' % (dep.rev, dep.alias, dep.dest))
            res.append('\n')
        return ''.join(res)

    def _add_tag(self, tag):
        if tag not in self._tags:
            self._order.append(tag)
        self._tags[tag] = []

    def _remove_tag(self, tag):
        self._order.remove(tag)
        del self._tags[tag]

    def _check_tag(self, tag):
        if not self.has_tag(tag):
            raise util.Abort(_("dependency list '%s' is not registered" % tag))

    def load(self, f):
        p_tag = re.compile(r'\[(\S+)\]')
        p_dep = re.compile(r'(\S+)\s+(\S+)\s+(\S+)')
        tag = None
        for i, line in enumerate(f.readlines()):
            m = p_tag.search(line)
            if m:
                tag = m.group(1).strip()
                if tag != 'aliases':
                    self._add_tag(tag)
                else:
                    import shlex
            elif tag == 'aliases':
                tokens = shlex.split(line)
                if tokens:
                    if not 3 <= len(tokens) <= 4:
                        raise util.Abort(_('in .hgdeps, line %i, `aliases` section: expected 3 or 4 space-delimited tokens, found %i'
                            % (i, len(tokens))))
                    alias = tokens[0]
                    scmtype = tokens[1]
                    location = tokens[2]
                    args = tokens[3].split() if len(tokens) > 3 else []
                    self.aliases.add_new(alias, scmtype, location, args, line)
            else:
                m = p_dep.search(line)
                if m:
                    rev = m.group(1).strip()
                    alias = m.group(2).strip()
                    dest = m.group(3).strip()
                    dep = dependency(rev, alias, dest)
                    if dep in self._tags[tag]:
                        raise util.Abort(_("in .hgdeps, depedency %s already"
                                           " registered for '%s'" % (dep, tag)))
                    self._tags[tag].append(dep)

_cloneopts = [
    ('', 'pull', None, _('use pull protocol to copy metadata')),
    ('', 'uncompressed', None, _('use uncompressed transfer (fast over LAN)')),
] + commands.remoteopts

cmdtable = {
    'deps': (deps,
            [('a', 'alias', '', 'alias of the repository dependency'),
             ('r', 'rev', '', 'revision of the repository dependency'),
             ('', 'remove', None, "remove name's dependencies"),
             ('d', 'dest', '', 'destination directory for the dependency')],
            'hg deps [-a ALIAS -r REV -d DEST] [NAME]'),
    
    'depupdate|depup|depsclone': (depupdate, [], '[NAME]'), 
    'depstatus|depst': (depstatus, [], ''),
    
    'depcommit|depci':
        (depcommit, [
            ('C', 'commit', None, 'commit changes immediately'),
            ] + mercurial.commands.commitopts + mercurial.commands.commitopts2,
        '[OPTION]...'), 
    
    'depalias':
        (depalias, [
            ('t', 'type', 'hg', 'repository type')],
        '[-t TYPE] ALIAS LOCATION'),
    
    'depaliases':
        (depaliases, [], ''),
    
    'deprmalias':
        (deprmalias, [], 'ALIAS'),

    'dep': (dep, [], 'ALIAS DEST [REV]'),
    'depremove|deprm': (depremove, [], 'ALIAS...'),
    'deppurge': (deppurge, [], '[ALIAS]...'),
}