~abentley/bzrtools/bzrtools.dev

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
# arch-tag: david@allouche.net - 2003-11-17 15:29:01 469107000
# Copyright (C) 2003  John Goerzen, David Allouche
# <jgoerzen@complete.org> <david@allouche.net>
#
#    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 2 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, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

"""Construction of tla commands
"""

import os.path
import re
from arch.pathname import DirName, FileName
from arch import errors
from arch._escaping import *

tlasyn = None
tlaobj = None


def gettlasyntax():
    global tlasyn, tlaobj
    if tlasyn != None:
        return tlasyn
    if text_cmd(['-V']).splitlines()[0].find('tla-1.0.') != -1:
        tlasyn = '1.0'
        tlaobj = Tla10()
    else:
        tlasyn = '1.1'
        tlaobj = Tla11()
    tlaobj.name_escaping = (0 == status_cmd(['escape'], (0,1)))
    return tlasyn


class Tla10:
    tagging_method = 'tagging-method'
    add = 'add-tag'
    move = 'move-tag'
    delete = 'delete-tag'
    update = 'update --in-place .'
    replay = 'replay --in-place .'
    ancestry_graph = None
    log_versions = 'logs'
    log_ls = 'log-ls'
    merges = None
    inventory_ids = ('inventory', '--tags')
    has_register_archive_wo_name = False
    get_changeset = 'get-patch'


class Tla11:
    tagging_method = 'id-tagging-method'
    add = 'add'
    move = 'move'
    delete = 'delete'
    update = 'update'
    replay = 'replay'
    ancestry_graph = 'ancestry-graph'
    log_versions = 'log-versions'
    log_ls = 'logs'
    merges = 'merges'
    inventory_ids = ('inventory', '--ids')
    has_register_archive_wo_name = True
    get_changeset = 'get-changeset'


def cmd():
    global tlaobj
    gettlasyntax()
    return tlaobj


### Utility functions ###

def _check_expected_param(expected):
    msg_format = ("'expected' param must be a sequence of positive"
                  " integers but was: %r")
    try:
        iterator = iter(expected)
    except TypeError:
        raise TypeError, msg_format % expected
    for status in iterator:
        if not isinstance(status, int):
            raise TypeError, msg_format % expected
        if status < 0:
            raise ValueError, msg_format % expected


### Subrocess spawning ###

def _spawner():
    import arch
    return arch.backend.spawner

def null_cmd(args, chdir=None):
    status = _spawner().status_cmd(args, chdir, (0,))
    assert status == 0

def one_cmd(args, chdir=None):
    status, line = status_one_cmd(args, chdir, (0,))
    assert status == 0
    return line

def sequence_cmd(args, chdir=None, expected=(0,)):
    _check_expected_param(expected)
    return _spawner().sequence_cmd(args, chdir, expected)

def text_cmd(args, chdir=None):
    status, text = _spawner().status_text_cmd(args, chdir, (0,))
    assert status == 0
    return text

def status_cmd(args, expected):
    _check_expected_param(expected)
    return _spawner().status_cmd(args, None, expected)

def status_one_cmd(args, chdir, expected):
    _check_expected_param(expected)
    seq = sequence_cmd(args, chdir, expected)
    try:
        out = seq.next()
    except StopIteration:
        return seq.status, None
    tail = list(seq)
    if not tail:
        return seq.status, out
    raise AssertionError, (
        'one liner actually produced multiline output:\n%s'
        % '\n'.join([out] + tail))

def status_text_cmd(args, expected):
    _check_expected_param(expected)
    return _spawner().status_text_cmd(args, None, expected)


### tla commands ###

# User Commands

def my_id():
    status, output = status_one_cmd(('my-id',), None, (0,2))
    # status is 2 if the user id is not set.
    # maybe an exception should be thrown instead of returning None.
    if status != 0: return None
    return output


def set_my_id(newid):
    null_cmd(('my-id', newid))


def default_archive():
    status, output = status_one_cmd(('my-default-archive',), None, (0,1))
    if status != 0: return None
    return output


def set_default_archive(archive):
    null_cmd(('my-default-archive', archive))

def make_archive(archive, location, signed=False, listing=False):
    args = ['make-archive']
    if signed: args.append('--signed')
    if listing: args.append('--listing')
    args.extend((archive, location))
    null_cmd(args)

def make_archive_mirror(master, name, location, signed=False, listing=False):
    args = ['make-archive', '--mirror', master]
    if signed: args.append('--signed')
    if listing: args.append('--listing')
    args.extend((name, location))
    return null_cmd(args)

def register_archive(archive, location):
    if archive is None:
        if not cmd().has_register_archive_wo_name:
            raise NotImplementedError, \
                  "register-archive without an archive name"\
                  " is not implemented in tla 1.0"
        null_cmd(('register-archive', location))
    else:
        null_cmd(('register-archive', archive, location))


def unregister_archive(archive):
    null_cmd(('register-archive', '--delete', archive))

def whereis_archive(archive):
    return one_cmd(('whereis-archive', archive))

def archive_meta_info(archive, key):
    status, output = status_one_cmd(
        ('archive-meta-info', '--archive', archive, key), None, (0, 1))
    if status == 1:
        raise KeyError, "No such meta-info in archive %s: %s" % (archive, key)
    return output

def archives():
    return sequence_cmd(('archives', '--names'))

def archive_registered(archive):
    return archive in archives()


# Project Tree commands

def init_tree(dir, version=None, nested=False):
    args = ['init-tree', '--dir', dir]
    if nested: args.append('--nested')
    if version is not None: args.append(version)
    null_cmd(args)

def tree_root(dir):
    status, output = status_text_cmd(('tree-root', dir), (0,1))
    if status == 1: raise errors.TreeRootError(dir)
    return output[:-1]

def tree_version(dir):
    vsn_name = dir/'{arch}'/'++default-version'
    try:
        return open(vsn_name, 'r').read().rstrip('\n')
    except IOError:
        if not os.path.exists(vsn_name): return None
        raise

def set_tree_version(dir, version):
    null_cmd(('set-tree-version', '--dir', dir, version))

def has_changes(dir):
    args = ('changes', '--dir', dir, '--quiet')
    return 1 == status_cmd(args, expected=(0,1))

def star_merge(dir, from_=None, reference=None, forward=False, diff3=False):
    args = ['star-merge', '--dir', dir]
    if reference is not None: args.extend(('--reference', reference))
    if forward: args.append('--forward')
    if diff3: args.append('--three-way')
    if from_ is not None: args.append(from_)
    # yes, we want to raise if there was a conflict, see the docstring
    # of arch.WorkingTree.star_merge for details.
    null_cmd(args)

def iter_star_merge(dir, from_=None, reference=None, forward=False,
                    diff3=False):
    args = ['star-merge', '--dir', dir]
    if reference is not None: args.extend(('--reference', reference))
    if forward: args.append('--forward')
    if diff3: args.append('--three-way')
    if from_ is not None: args.append(from_)
    return sequence_cmd(args, expected=(0,1))

def sync_tree(dir, revision):
    null_cmd(('sync-tree', '--dir', dir, revision))

def undo(dir, revision=None, output=None, quiet=False, throw_away=False):
    args = ['undo', '--dir', dir]
    if quiet: args.append('--quiet')
    if throw_away:
        args.append('--no-output')
    elif output:
        args.extend(('--output', output))
    if revision: args.append(revision)
    null_cmd(args)

def log_for_merge(dir):
    args = ['log-for-merge', '--dir', dir]
    return text_cmd(args)


def redo(dir, patch=None, keep=False, quiet=False):
    args = ['redo', '--dir', dir]
    if quiet: args.append('--quiet')
    if keep: args.append('--keep')
    if patch: args.extend(('--patch', patch))
    null_cmd(args)

def update(dir):
    """FIXME: add the other parameters."""
    ### Correct implementation
    # args = ['update', '--dir', dir]
    # return null_cmd(args)
    ### Work around bug in tla 1.2.1
    null_cmd(['update'], chdir=dir)

def replay(dir):
    """FIXME: add the other parameters."""
    args = ['replay', '--dir', dir]
    null_cmd(args)


# Project Tree Inventory commands

def __inventory_helper(dir, opts,
                       source, precious, backups, junk, unrecognized, trees,
                       directories, files, both, names, limit):
    __pychecker__ = 'maxargs=13'
    # Asserts there is only one kind and one type
    (source, precious, backups,
     junk, unrecognized, trees) = map(bool, (source, precious, backups,
                                             junk, unrecognized, trees))
    assert 1 == sum(map(int, (source, precious, backups,
                              junk, unrecognized, trees)))
    (directories, files, both) = map(bool, (directories, files, both))
    assert 1 == sum(map(int, (directories, files, both, trees)))

    if source: opts.append('--source')
    if precious: opts.append('--precious')
    if backups: opts.append('--backups')
    if junk: opts.append('--junk')
    if unrecognized: opts.append('--unrecognized')
    if trees: opts.append('--trees')
    if directories: opts.append('--directories')
    if files: opts.append('--files')
    if both: opts.append('--both')
    if names: opts.append('--names')
    if limit is not None: opts.append(limit)
    return sequence_cmd(opts, chdir=dir)


def iter_inventory(dir, source=False, precious=False, backups=False,
                   junk=False, unrecognized=False, trees=False,
                   directories=False, files=False, both=False, names=False,
                   limit=None):
    __pychecker__ = 'maxargs=12'
    return __inventory_helper(dir, ['inventory'], source, precious, backups,
                              junk, unrecognized, trees,
                              directories, files, both, names, limit)


def iter_inventory_ids(dir, source=False, precious=False, backups=False,
                       junk=False, unrecognized=False, trees=False,
                       directories=False, files=False, both=False,
                       limit=None):
    __pychecker__ = 'maxargs=11'
    for line in __inventory_helper(dir, list(cmd().inventory_ids),
                                   source, precious, backups,
                                   junk, unrecognized, trees,
                                   directories, files, both,
                                   names=False, limit=limit):
        yield line.split('\t')


def tagging_method(dir):
    return one_cmd((cmd().tagging_method, '--dir', dir))

def set_tagging_method(dir, method):
    null_cmd((cmd().tagging_method, '--dir', dir, method))

def add(file):
    null_cmd((cmd().add, file))

def delete(file):
    null_cmd((cmd().delete, file))

def move(src, dest):
    return null_cmd((cmd().move, src, dest))

def get_tag(file):
    status, output = status_one_cmd(('id', file), None, (0,1))
    if status == 1: return None
    return output.split('\t')[1]


# Patch Set Commands

def changeset(orig, mod, dest, files=()):
    return null_cmd(('changeset', orig, mod, dest) + files)

def iter_apply_changeset(changeset, tree, reverse=False):
    args = ['apply-changeset']
    if reverse: args.append('--reverse')
    args.extend((changeset, tree))
    return sequence_cmd(args, expected=(0,1))


# Archive Transaction Commands

def archive_setup(name):
    null_cmd(('archive-setup', name))

def import_(dir, log=None):
    args = ['import', '--dir', dir]
    if log is not None: args.extend(('--log', log))
    null_cmd(args)

def iter_commit(dir, version, log=None, strict=False, seal=False, fix=False,
           out_of_date_ok=False, file_list=None, base=None):
    args = ['commit']
    if log is not None: args.extend(('--log', log))
    if strict: args.append('--strict')
    assert not (seal and fix)
    if seal: args.append('--seal')
    if fix: args.append('--fix')
    if out_of_date_ok: args.append('--out-of-date-ok')
    if base is not None:
        args.extend(('--base', base))
    args.append(version)
    if file_list is not None:
        file_list = tuple(file_list)
        assert 0 < len(file_list)
        args.append('--')
        args.extend(map(str, file_list))
    return sequence_cmd(args, chdir=str(dir))

def get(revision, dir, link=False):
    command = ['get']
    if link: command.append('--link')
    command.extend((revision, dir))
    null_cmd(command)

def get_patch(revision, dir):
    P = NameParser(revision)
    # XXX Work around bug in 1.2.2rc2 and corresponding integration revisions
    # XXX where get-changeset would fail with "no default archive set".
    args = [cmd().get_changeset, '-A', P.get_archive(), P.get_nonarch(), dir]
    null_cmd(args)

def archive_mirror(from_, to, limit=None, no_cached=False, cached_tags=False):
    # --summary would be useful only in iter_archive_mirror
    args = ['archive-mirror']
    assert no_cached + cached_tags < 2
    if no_cached: args.append('--no-cached')
    if cached_tags: args.append('--cached-tags')
    args.append(from_)
    if to is not None: args.append(to)
    if limit is not None:
        assert 0 < len(limit)
        args.extend(limit)
    null_cmd(args)

# Archive Commands

def categories(archive):
    return sequence_cmd(('categories', '--archive', archive))

def branches(category):
    return sequence_cmd(('branches', category))

def versions(branch, reverse=False):
    if not reverse:
        return sequence_cmd(('versions', branch))
    else:
        return sequence_cmd(('versions', '--reverse', branch))

def revisions(version, reverse=False):
    if not reverse:
        return sequence_cmd(('revisions', version))
    else:
        return sequence_cmd(('revisions', '--reverse', version))


def category_exists(archive, category):
    if not archive_registered(archive):
        raise errors.ArchiveNotRegistered(archive)
    else:
        return category in categories(archive)


def branch_exists(archive, branch):
    category = NameParser(branch).get_category()
    if not category_exists(archive, category):
        return False
    else:
        return branch in branches(archive+"/"+category)


def version_exists(archive, version):
    package = NameParser(version).get_package()
    if not branch_exists(archive, package):
        return False
    else:
        return version in versions(archive+"/"+package)


def revision_exists(archive, version, patchlevel):
    try:
        return patchlevel in revisions(archive+"/"+version)
    except Exception:
        if not version_exists(archive, version):
            return False
        else:
            raise

def cat_archive_log(revision):
    return text_cmd(('cat-archive-log', revision))


def cacherev(revision, cache=None):
    if cache is None:
        return null_cmd(('cacherev', revision))
    else:
        return null_cmd(('cacherev', '--cache', cache, revision))


def cachedrevs(version):
    return sequence_cmd(('cachedrevs', version))


def uncacherev(revision):
    null_cmd(('uncacherev', revision))


def iter_merges(version1, version2=None, reverse=False, metoo=True):
    subcmd = cmd().merges
    if subcmd is None:
        raise NotImplementedError, \
              "merges is not implemented in tla 1.0"""
    args = [ subcmd ]
    if reverse: args.append('--reverse')
    args.append('--full')
    args.append(version1)
    if version2 is not None: args.append(version2)
    for line in sequence_cmd(args):
        target, source = line.split('\t')
        if metoo or '%s--%s' % (version1, target) != source:
            yield target, source


def iter_ancestry_graph(revision, merges=False, reverse=False):
    subcmd = cmd().ancestry_graph
    if subcmd is None:
        raise NotImplementedError, \
              "ancestry-graph is not implemented in tla 1.0"
    args = [ subcmd ]
    if merges: args.append('--merges')
    if reverse: args.append('--reverse')
    args.append(revision)
    for line in sequence_cmd(args):
        yield line.split('\t')


def ancestor(revision):
    subcmd = cmd().ancestry_graph
    if subcmd is None:
        raise NotImplementedError, \
              "ancestry-graph is not implemented in tla 1.0"
    rvsn = one_cmd((subcmd, '--immediate', revision))
    if rvsn == '(null)': return None
    # --immediate always return a fully qualified revision
    return rvsn

def previous(revision):
    subcmd = cmd().ancestry_graph
    if subcmd is None:
        raise NotImplementedError, \
              "ancestry-graph is not implemented in tla 1.0"
    rvsn = one_cmd((subcmd, '--previous', revision))
    if rvsn == '(null)': return None
    # --previous always returns a nonarch revision name part
    return NameParser(revision).get_archive()+'/'+rvsn


# Patch Log Commands

def make_log(dir, version=None):
    args = ['make-log', '--dir', dir]
    if version is not None:
        args.append(version)
    return text_cmd(args)[:-1]

def log_name(dir, version=None):
    if version is None:
        version = tree_version(dir)
    parse = NameParser(version)
    return dir/FileName('++log.%s--%s'
                        % (parse.get_nonarch(), parse.get_archive()))

def add_log_version(dir, version):
    null_cmd(('add-log-version', '--dir', dir, version))

def remove_log_version(dir, version):
    null_cmd(('remove-log-version', '--dir', dir, version))


def iter_log_versions(dir, reverse=False,
                      archive=None, category=None, branch=None, version=None):
    opts = (cmd().log_versions, '--dir', dir)
    if reverse: opts += ('--reverse',)
    if archive: opts += ('--archive', archive)
    if category: opts += ('--category', category)
    if branch: opts += ('--branch', branch)
    if version: opts += ('--vsn', version)
    return sequence_cmd(opts)


def iter_log_ls(dir, version, reverse=False):
    opts = [ cmd().log_ls, '--full', '--dir', dir ]
    if reverse: opts.append('--reverse')
    opts.append(version)
    return sequence_cmd(opts)


def cat_log(dir, revision):
    return text_cmd(('cat-log', '--dir', dir, revision))


# Multi-project Configuration Commands

# Commands for Branching and Merging

def tag(source_revision, tag_version):
    null_cmd(('tag', source_revision, tag_version))

def iter_delta (orig, mod, dest):
    args = ['delta', orig, mod, dest]
    return sequence_cmd(args)


# Local Cache Commands

def file_find(tree, file_name, revision):
    args = ('file-find', '--new-file', file_name, revision)
    # XXX Work around missing --silent option, ignore chatter
    output = text_cmd(args, chdir=tree)
    path = output.splitlines()[-1]
    if path == '/dev/null': return None
    if cmd().name_escaping:
        return name_unescape(path)
    else:
        return path

def iter_pristines(dir_name):
    args = ('pristines', '--dir', dir_name)
    return sequence_cmd(args)

def add_pristine(dir_name, revision):
    args = ('add-pristine', '--dir', dir_name, revision)
    null_cmd(args)

def find_pristine(dir_name, revision):
    args = ('find-pristine', '--dir', dir_name, revision)
    return one_cmd(args)


# Revision Library Commands

def iter_revision_libraries():
    args = ('my-revision-library', '--silent')
    try:
        for val in sequence_cmd(args):
            yield val
    except errors.ExecProblem, e:
        if e.proc.error != \
            "my-revision-library: no revision library path set\n":
            raise

def register_revision_library(dirname):
    null_cmd(('my-revision-library', '--silent', dirname))

def unregister_revision_library(dirname):
    null_cmd(('my-revision-library', '--silent', '--delete', dirname))

def library_archives():
    return sequence_cmd(('library-archives',))

def library_categories(archive):
    return sequence_cmd(('library-categories', '--archive', archive))

def library_branches(category):
    return  sequence_cmd(('library-branches', category))

def library_versions(branch, reverse=False):
    if not reverse:
        return sequence_cmd(('library-versions', branch))
    else:
        return sequence_cmd(('library-versions', '--reverse', branch))

def library_revisions(version, reverse=False):
    if not reverse:
        return sequence_cmd(('library-revisions', version))
    else:
        return sequence_cmd(('library-revisions', '--reverse', version))


def library_add(revision, library):
    args = ['library-add']
    if library is not None:
        args.extend(['-L', library])
    args.append(revision)
    return null_cmd(('library-add', revision))

def library_remove(revision):
    null_cmd(('library-remove', revision))

def library_find(revision):
    return text_cmd(('library-find', revision))[:-1]

def library_log(revision):
    return text_cmd(('library-log', revision))


### Name parsing ###

class ForkNameParser(str):

    """Parse Arch names with with tla.

    All operations run tla, this is generally too expensive for
    practical use. Use NameParser instead, which is implemented
    natively.

    This class is retained for testing purposes.
    """

    def __valid_package_name(self, opt, tolerant=True):
        opts = [ 'valid-package-name' ]
        if tolerant: opts.append('--tolerant')
        if opt: opts.append(opt)
        opts.append(self)
        return 0 == status_cmd(opts, expected=(0,1))

    def __parse_package_name(self, opt):
        opts = [ 'parse-package-name' ]
        if opt: opts.append(opt)
        opts.append(self)
        status, retval = status_one_cmd(opts, None, (0,1))
        return retval

    def is_category(self):
        return self.__valid_package_name('--category', tolerant=False)
    def is_package(self):
        return self.__valid_package_name('--package', tolerant=False)
    def is_version(self):
        return self.__valid_package_name('--vsn', tolerant=False)
    def is_patchlevel(self):
        return self.__valid_package_name('--patch-level', tolerant=False)

    def has_archive(self):
        return self.__valid_package_name('--archive')
    def has_category(self):
        return self.__valid_package_name('--category')
    def has_package(self):
        return self.__valid_package_name('--package')
    def has_version(self):
        return self.__valid_package_name('--vsn')
    def has_patchlevel(self):
        return self.__valid_package_name('--patch-level')

    def get_archive(self):
        return self.__parse_package_name('--arch')
    def get_nonarch(self):
        return self.__parse_package_name('--non-arch')
    def get_category(self):
        return self.__parse_package_name('--category')
    def get_branch(self):
        return self.__parse_package_name('--branch')
    def get_package(self):
        return self.__parse_package_name('--package')
    def get_version(self):
        if not self.has_version(): return None # work around a tla bug
        return self.__parse_package_name('--vsn')
    def get_package_version(self):
        return self.__parse_package_name('--package-version')
    def get_patchlevel(self):
        if not self.has_patchlevel(): return None # work around a tla bug
        return self.__parse_package_name('--patch-level')


class NameParser(str):

    """Parser for names in Arch archive namespace.

    Implements name parsing natively for performance reasons. It
    should behave exactly as tla, any discrepancy is to be considered
    a bug, unless tla is obviously buggy.

    Bare names of archives, category, branch, versions ids, and
    unqualified patchlevel names are not part of the archive
    namespace. They can be validated using static methods.

    :group Specificity level: is_category, is_package, is_version

    :group Presence name components: has_archive, has_category, has_branch,
        has_package, has_version, has_revision, has_patchlevel

    :group Getting name components: get_archive, get_nonarch, get_category,
        get_branch, get_package, get_version, get_package_version,
        get_patchlevel

    :group Validating name components: is_archive_name, is_category_name,
        is_branch_name, is_version_id, is_patchlevel
    """

    __archive_regex = re.compile('^[-a-zA-Z0-9]+(\.[-a-zA-Z0-9]+)*@'
                                 '[-a-zA-Z0-9.]*$')
    __name_regex = re.compile('^[a-zA-Z]([a-zA-Z0-9]|-[a-zA-Z0-9])*$')
    __version_regex = re.compile('^[0-9]+(\\.[0-9]+)*$')
    #__level_regex = re.compile('^base-0|version-0|(patch|versionfix)-[0-9]+$')
    # tla accepts --version-12, so mimick that:
    __level_regex = re.compile('^base-0|(version|patch|versionfix)-[0-9]+$')

    def __init__(self, s):
        """Create a parser object for the given string.

        :param s: string to parse.
        :type s: str
        """
        str.__init__(s)
        parts = self.__parse()
        if parts:
            self.__valid = True
        else:
            parts = None, None, None, None, None, None
            self.__valid = False
        (self.__archive, self.__nonarch, self.__category,
         self.__branch, self.__version, self.__level) = parts

    def __parse(self):
        parts = self.split('/')
        if len(parts) == 1:
            archive, nonarch = None, parts[0]
        elif len(parts) == 2:
            archive, nonarch = parts
        else:
            return False

        parts = nonarch.split('--')
        category, branch, version, level = None, None, None, None
        if len(parts) == 1:
            category = parts[0]
        elif len(parts) == 2:
            if self.__name_regex.match(parts[1]):
                category, branch = parts
            else:
                category, version = parts
        elif len(parts) == 3:
            if self.__name_regex.match(parts[1]):
                category, branch, version = parts
            else:
                category, version, level = parts
        elif len(parts) == 4:
            category, branch, version, level = parts
        else:
            return False

        if archive and not self.__archive_regex.match(archive):
            return False
        elif not self.__name_regex.match(category):
            return False
        elif branch and not self.__name_regex.match(branch):
            return False
        elif not version and not level: pass
        elif not self.__version_regex.match(version):
            return False
        elif not level: pass
        elif not self.__level_regex.match(level):
            return False

        return archive, nonarch, category, branch, version, level

    def is_category(self):
        """Is this a category name?

        :rtype: bool
        """
        return bool(self.__category) and not (self.__branch or self.__version)

    def is_package(self):
        """Is this a package name (category or branch name)?

        :rtype: bool
        """
        return bool(self.__category) and not self.__version
    def is_version(self):
        """Is this a version name?

        :rtype: bool
        """
        return bool(self.__version) and not self.__level

    def has_archive(self):
        """Does this include an archive name?

        :rtype: bool
        """
        return bool(self.__archive)

    def has_category(self):
        """Does this include an category name?

        :rtype: bool
        """
        return bool(self.__category)

    def has_package(self):
        """Does this include an package name?

        :rtype: bool
        """
        return bool(self.__category)

    def has_version(self):
        """Does this include a version name?

        :rtype: bool
        """
        return bool(self.__version)

    def has_patchlevel(self):
        """Does this include a revision name?

        :rtype: bool
        """
        return bool(self.__level)

    def get_archive(self):
        """Get the archive part of the name

        :return: archive part of the name, or the default archive name, or None
            if the name is invalid.
        :rtype: str, None
        """
        if not self.__valid: return None
        if not self.__archive: return default_archive()
        return self.__archive

    def get_nonarch(self):
        """Get Non-archive part of the name

        :return: the name without the archive component, or None if the name is
            invalid or has no archive component.
        :rtype: str, None
        """
        return self.__nonarch

    def get_category(self):
        """Get the Category name

        :return: part of the name which identifies the category within
            the archive, or None if the name is invalid or has no category
            component.
        :rtype: str, None
        """
        return self.__category

    def get_branch(self):
        """Get the branch part of name

        :return: part of the name which identifies the branch within the
            category, or None if the name is invalid or the empty string if the
            name has no branch component.
        :rtype: str, None
        """
        if not self.__valid: return None
        if not self.__branch: return str()
        return self.__branch

    def get_package(self):
        """Get the package name

        :return: part of the name including the category part and branch part
            (if present) of the name, or None if the name is not valid.
        :rtype: str, None
        """
        if not self.__valid: return None
        if self.__branch is None: return self.__category
        return self.__category + '--' + self.__branch

    def get_version(self):
        """Get the version id part of the name

        :return: part of the name identifying a version in a branch, or None if
            the name is invalid or does not contain a version id.
        :rtype: str, None
        """
        return self.__version

    def get_package_version(self):
        """Get the unqualified version name

        :return: part of the name identifying a version in an archive, or None
            if the name does not contain a version id or is invalid.
        :rtype: str, None
        """
        if not self.__version: return None
        return self.get_package() + '--' + self.__version

    def get_patchlevel(self):
        """Get the patch-level part of the name

        :return: part of the name identifying a patch in a version, or None if
            the name is not a revision or is invalid.
        :rtype: str, None
        """
        return self.__level

    def is_archive_name(klass, s):
        """Is this string a valid archive name?

        :param s: string to validate.
        :type s: str
        :rtype: bool
        """
        return bool(klass.__archive_regex.match(s))
    is_archive_name = classmethod(is_archive_name)

    def is_category_name(klass, s):
        """Is this string a valid category name?

        Currently does the same thing as is_branch_name, but that might
        change in the future when the namespace evolves and it is more
        expressive to have different functions.

        :param s: string to validate.
        :type s: str
        :rtype: bool
        """
        return bool(klass.__name_regex.match(s))
    is_category_name = classmethod(is_category_name)

    def is_branch_name(klass, s):
        """Is this string a valid category name?

        Currently does the same thing as is_category_name, but that might
        change in the future when the namespace evolves and it is more
        expressive to have different functions.

        :param s: string to validate.
        :type s: str
        :rtype: bool
        """
        return bool(klass.__name_regex.match(s))
    is_branch_name = classmethod(is_branch_name)

    def is_version_id(klass, s):
        """Is this string a valid version id?

        :param s: string to validate.
        :type s: str
        :rtype: bool
        """
        return bool(klass.__version_regex.match(s))
    is_version_id = classmethod(is_version_id)

    def is_patchlevel(klass, s):
        """Is this string a valid unqualified patch-level name?

        :param s: string to validate.
        :type s: str
        :rtype: bool
        """
        return bool(klass.__level_regex.match(s))
    is_patchlevel = classmethod(is_patchlevel)


### Pika escaping ###

def tla_name_escape(text):
   return text_cmd(('escape', text))

def tla_name_unescape(text):
    return text_cmd(('escape', '--unescaped', text))


### Misc features ###

def in_tree(dir):
    """Return True if dir is, or is inside, a Arch source tree."""
    # Must use tree-root and not tree-version because the tree-version
    # may be unset (after init-tree)
    status = status_cmd(('tree-root', dir), expected=(0,1))
    return not status


def is_tree_root(dir):
    """Return True if dir is a Arch source tree."""
    opts = [ 'tree-root', dir ]
    status, out = status_text_cmd(opts, expected=(0,1))
    if status != 0: return False
    return os.path.realpath(dir) == out[:-1]


def has_explicit_id(path):
    assert os.path.exists(path)
    arch_ids = DirName('.arch-ids')
    if os.path.isfile(path):
        dir_, base = FileName(path).splitname()
        return os.path.exists(dir_/arch_ids/(base+'.id'))
    if os.path.isdir(path):
        return os.path.exists(DirName(path)/arch_ids/'=id')
    raise AssertionError, 'not regular file or directory: ' + path