~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
# Copyright (C) 2005 by Aaron Bentley

# 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

import errno

from bzrlib.errors import BzrError
from bzrlib.errors import NotBranchError, BzrCommandError, NoSuchRevision
from bzrlib.branch import Branch
from bzrlib.clone import copy_branch
from bzrlib.commit import Commit, NullCommitReporter
from bzrlib.commands import Command
from bzrlib.option import _global_option
from bzrlib.workingtree import WorkingTree
from errors import NoPyBaz
try:
    import pybaz
    import pybaz.errors
    from pybaz import NameParser as NameParser
    from pybaz.backends.baz import null_cmd
except ImportError:
    raise NoPyBaz
from fai import iter_new_merges, direct_merges
import tempfile
import os
import os.path
import shutil
import bzrlib
import bzrlib.trace
import bzrlib.merge
import bzrlib.inventory
import bzrlib.osutils
import sys
import email.Utils
from progress import *

class ImportCommitReporter(NullCommitReporter):
    def __init__(self, pb):
        self.pb = pb

    def escaped(self, escape_count, message):
        self.pb.clear()
        bzrlib.trace.warning("replaced %d control characters in message" %
                             escape_count)

def add_id(files, id=None):
    """Adds an explicit id to a list of files.

    :param files: the name of the file to add an id to
    :type files: list of str
    :param id: tag one file using the specified id, instead of generating id
    :type id: str
    """
    args = ["add-id"]
    if id is not None:
        args.extend(["--id", id])
    args.extend(files)
    return null_cmd(args)

saved_dir = None

def test_environ():
    """
    >>> q = test_environ()
    >>> os.path.exists(q)
    True
    >>> os.path.exists(os.path.join(q, "home", ".arch-params"))
    True
    >>> teardown_environ(q)
    >>> os.path.exists(q)
    False
    """
    global saved_dir
    saved_dir = os.getcwdu()
    tdir = tempfile.mkdtemp(prefix="testdir-")
    os.environ["HOME"] = os.path.join(tdir, "home")
    os.mkdir(os.environ["HOME"])
    arch_dir = os.path.join(tdir, "archive_dir")
    pybaz.make_archive("test@example.com", arch_dir)
    work_dir = os.path.join(tdir, "work_dir")
    os.mkdir(work_dir)
    os.chdir(work_dir)
    pybaz.init_tree(work_dir, "test@example.com/test--test--0")
    lib_dir = os.path.join(tdir, "lib_dir")
    os.mkdir(lib_dir)
    pybaz.register_revision_library(lib_dir)
    pybaz.set_my_id("Test User<test@example.org>")
    return tdir

def add_file(path, text, id):
    """
    >>> q = test_environ()
    >>> add_file("path with space", "text", "lalala")
    >>> tree = pybaz.tree_root(".")
    >>> inv = list(tree.iter_inventory_ids(source=True, both=True))
    >>> ("x_lalala", "path with space") in inv
    True
    >>> teardown_environ(q)
    """
    file(path, "wb").write(text)
    add_id([path], id)


def add_dir(path, id):
    """
    >>> q = test_environ()
    >>> add_dir("path with\(sp) space", "lalala")
    >>> tree = pybaz.tree_root(".")
    >>> inv = list(tree.iter_inventory_ids(source=True, both=True))
    >>> ("x_lalala", "path with\(sp) space") in inv
    True
    >>> teardown_environ(q)
    """
    os.mkdir(path)
    add_id([path], id)

def teardown_environ(tdir):
    os.chdir(saved_dir)
    shutil.rmtree(tdir)

def timport(tree, summary):
    msg = tree.log_message()
    msg["summary"] = summary
    tree.import_(msg)

def commit(tree, summary):
    """
    >>> q = test_environ()
    >>> tree = pybaz.tree_root(".")
    >>> timport(tree, "import")
    >>> commit(tree, "commit")
    >>> logs = [str(l.revision) for l in tree.iter_logs()]
    >>> len(logs)
    2
    >>> logs[0]
    'test@example.com/test--test--0--base-0'
    >>> logs[1]
    'test@example.com/test--test--0--patch-1'
    >>> teardown_environ(q)
    """
    msg = tree.log_message()
    msg["summary"] = summary
    tree.commit(msg)

def commit_test_revisions():
    """
    >>> q = test_environ()
    >>> commit_test_revisions()
    >>> a = pybaz.Archive("test@example.com")
    >>> revisions = list(a.iter_revisions("test--test--0"))
    >>> len(revisions)
    3
    >>> str(revisions[2])
    'test@example.com/test--test--0--base-0'
    >>> str(revisions[1])
    'test@example.com/test--test--0--patch-1'
    >>> str(revisions[0])
    'test@example.com/test--test--0--patch-2'
    >>> teardown_environ(q)
    """
    tree = pybaz.tree_root(".")
    add_file("mainfile", "void main(void){}", "mainfile by aaron")
    timport(tree, "Created mainfile")
    file("mainfile", "wb").write("or something like that")
    commit(tree, "altered mainfile")
    add_file("ofile", "this is another file", "ofile by aaron")
    commit(tree, "altered mainfile")


def commit_more_test_revisions():
    """
    >>> q = test_environ()
    >>> commit_test_revisions()
    >>> commit_more_test_revisions()
    >>> a = pybaz.Archive("test@example.com")
    >>> revisions = list(a.iter_revisions("test--test--0"))
    >>> len(revisions)
    4
    >>> str(revisions[0])
    'test@example.com/test--test--0--patch-3'
    >>> teardown_environ(q)
    """
    tree = pybaz.tree_root(".")
    add_file("trainfile", "void train(void){}", "trainfile by aaron")
    commit(tree, "altered trainfile")

class NoSuchVersion(Exception):
    def __init__(self, version):
        Exception.__init__(self, "The version %s does not exist." % version)
        self.version = version

def version_ancestry(version):
    """
    >>> q = test_environ()
    >>> commit_test_revisions()
    >>> version = pybaz.Version("test@example.com/test--test--0")
    >>> ancestors = version_ancestry(version)
    >>> str(ancestors[0])
    'test@example.com/test--test--0--base-0'
    >>> str(ancestors[1])
    'test@example.com/test--test--0--patch-1'
    >>> version = pybaz.Version("test@example.com/test--test--0.5")
    >>> ancestors = version_ancestry(version)
    Traceback (most recent call last):
    NoSuchVersion: The version test@example.com/test--test--0.5 does not exist.
    >>> teardown_environ(q)
    """
    try:
        revision = version.iter_revisions(reverse=True).next()
    except StopIteration:
        return ()
    except:
        print version
        if not version.exists():
            raise NoSuchVersion(version)
        else:
            raise
    ancestors = list(revision.iter_ancestors(metoo=True))
    ancestors.reverse()
    return ancestors

def get_last_revision(branch):
    last_patch = branch.last_revision()
    try:
        return arch_revision(last_patch)
    except NotArchRevision:
        raise UserError(
            "Directory \"%s\" already exists, and the last revision is not"
            " an Arch revision (%s)" % (branch.base, last_patch))

def do_branch(br_from, to_location, revision_id):
    """Derived from branch in builtins."""
    br_from.lock_read()
    try:
        try:
            os.mkdir(to_location)
        except OSError, e:
            if e.errno == errno.EEXIST:
                raise UserError('Target directory "%s" already'
                                      ' exists.' % to_location)
            if e.errno == errno.ENOENT:
                raise UserError('Parent of "%s" does not exist.' %
                                      to_location)
            else:
                raise
        try:
            copy_branch(br_from, to_location, revision_id, None)
        except NoSuchRevision:
            rmtree(to_location)
            msg = "The branch %s has no revision %s." % (from_location, revision_id)
            raise UserError(msg)
    finally:
        br_from.unlock()

def get_remaining_revisions(output_dir, version, reuse_history_from=[]):
    last_patch = None
    old_revno = None
    output_exists = os.path.exists(output_dir)
    if output_exists:
        # We are starting from an existing directory, figure out what
        # the current version is
        branch = Branch.open(output_dir)
        last_patch = get_last_revision(branch)
        if last_patch is None:
            raise NotPreviousImport(branch.base)
        if version is None:
            version = last_patch.version
    elif version is None:
        raise UserError("No version specified, and directory does not exist.")

    try:
        ancestors = version_ancestry(version)
        if not output_exists and reuse_history_from != []:
            for ancestor in reversed(ancestors):
                if last_patch is not None:
                    # found something to copy
                    break
                # try to grab a copy of ancestor
                # note that is not optimised: we could look for namespace
                # transitions and only look for the past after the 
                # transition.
                for history_root in reuse_history_from:
                    possible_source = os.path.join(history_root,
                        map_namespace(ancestor.version))
                    try:
                        source = Branch.open(possible_source)
                        rev_id = revision_id(ancestor)
                        if rev_id in source.revision_history():
                            do_branch(source, output_dir, rev_id)
                            last_patch = ancestor
                            break
                    except NotBranchError:
                        pass
    except NoSuchVersion, e:
        raise UserError(str(e))

    if last_patch:
        for i in range(len(ancestors)):
            if ancestors[i] == last_patch:
                break
        else:
            raise UserError("Directory \"%s\" already exists, and the last "
                "revision (%s) is not in the ancestry of %s" % 
                (output_dir, last_patch, version))
        # Strip off all of the ancestors which are already present
        # And get a directory starting with the latest ancestor
        latest_ancestor = ancestors[i]
        old_revno = Branch.open(output_dir).revno()
        ancestors = ancestors[i+1:]
    return ancestors, old_revno


###class Importer(object):
###    """An importer.
###    
###    Currently this is used as a parameter object, though more behaviour is
###    possible later.
###    """
###
###    def __init__(self, output_dir, version, printer, fancy=True, fast=False,
###                 verbose=False, dry_run=False, max_count=None, 
###                   reuse_history_from=[]):
###        self.output_dir = output_dir
###        self.version = version
###        self.


def import_version(output_dir, version, printer, fancy=True, fast=False,
                   verbose=False, dry_run=False, max_count=None,
                   reuse_history_from=[]):
    """
    >>> q = test_environ()
    >>> result_path = os.path.join(q, "result")
    >>> commit_test_revisions()
    >>> version = pybaz.Version("test@example.com/test--test--0.1")
    >>> def printer(message): print message
    >>> import_version('/', version, printer, fancy=False, dry_run=True)
    Traceback (most recent call last):
    NotPreviousImport: / is not the location of a previous import.
    >>> import_version(result_path, version, printer, fancy=False, dry_run=True)
    Traceback (most recent call last):
    UserError: The version test@example.com/test--test--0.1 does not exist.
    >>> version = pybaz.Version("test@example.com/test--test--0")
    >>> import_version(result_path, version, printer, fancy=False, dry_run=True)
    not fancy
    ....
    Dry run, not modifying output_dir
    Cleaning up
    >>> import_version(result_path, version, printer, fancy=False)
    not fancy
    ....
    Cleaning up
    Import complete.
    >>> import_version(result_path, version, printer, fancy=False)
    Tree is up-to-date with test@example.com/test--test--0--patch-2
    >>> commit_more_test_revisions()
    >>> import_version(result_path, version, printer, fancy=False)
    not fancy
    ..
    Cleaning up
    Import complete.
    >>> teardown_environ(q)
    """
    try:
        ancestors, old_revno = get_remaining_revisions(output_dir, version,
                                                       reuse_history_from)
    except NotBranchError, e:
        raise NotPreviousImport(e.path)
    if old_revno is None and len(ancestors) == 0:
        print 'Version %s has no revisions.' % version
        return
    if len(ancestors) == 0:
        last_revision = get_last_revision(Branch.open(output_dir))
        print 'Tree is up-to-date with %s' % last_revision
        return

    progress_bar = ProgressBar()
    tempdir = tempfile.mkdtemp(prefix="baz2bzr-",
                               dir=os.path.dirname(output_dir))
    try:
        if not fancy:
            print "not fancy"
        try:
            for result in iter_import_version(output_dir, ancestors, tempdir,
                    progress_bar, fast=fast, verbose=verbose, dry_run=dry_run,
                    max_count=max_count):
                if fancy:
                    show_progress(progress_bar, result)
                else:
                    sys.stdout.write('.')
        finally:
            if fancy:
                progress_bar.clear()
            else:
                sys.stdout.write('\n')

        if dry_run:
            print 'Dry run, not modifying output_dir'
            return
        if os.path.exists(output_dir):
            # Move the bzr control directory back, and update the working tree
            revdir = os.path.join(tempdir, "rd")
            if os.path.exists(revdir):
                # actual imports were done
                tmp_bzr_dir = os.path.join(tempdir, '.bzr')
                
                bzr_dir = os.path.join(output_dir, '.bzr')
                new_bzr_dir = os.path.join(tempdir, "rd", '.bzr')
    
                os.rename(bzr_dir, tmp_bzr_dir) # Move the original bzr out of the way
                os.rename(new_bzr_dir, bzr_dir)
                try:
                    bzrlib.merge.merge((output_dir, -1), (output_dir, None), # old_revno), 
                                       check_clean=False, this_dir=output_dir, 
                                       ignore_zero=True)
                except:
                    # If something failed, move back the original bzr directory
                    os.rename(bzr_dir, new_bzr_dir)
                    os.rename(tmp_bzr_dir, bzr_dir)
                    raise
            else:
                # no imports - perhaps just append_revisions
                # should not fail:
                bzrlib.merge.merge((output_dir, -1), (output_dir, None), # old_revno), 
                                   check_clean=False, this_dir=output_dir, 
                                   ignore_zero=True)
        else:
            revdir = os.path.join(tempdir, "rd")
            os.rename(revdir, output_dir)

    finally:
        printer('Cleaning up')
        shutil.rmtree(tempdir)
    printer("Import complete.")
            
class UserError(BzrCommandError):
    def __init__(self, message):
        """Exception to throw when a user makes an impossible request
        :param message: The message to emit when printing this exception
        :type message: string
        """
        BzrCommandError.__init__(self, message)

class NotPreviousImport(UserError):
    def __init__(self, path):
        UserError.__init__(self, "%s is not the location of a previous import."
                           % path)


def revision_id(arch_revision):
    """
    Generate a Bzr revision id from an Arch revision id.  'x' in the id
    designates a revision imported with an experimental algorithm.  A number
    would indicate a particular standardized version.

    :param arch_revision: The Arch revision to generate an ID for.

    >>> revision_id(pybaz.Revision("you@example.com/cat--br--0--base-0"))
    'Arch-1:you@example.com%cat--br--0--base-0'
    """
    return "Arch-1:%s" % str(arch_revision).replace('/', '%')

class NotArchRevision(Exception):
    def __init__(self, revision_id):
        msg = "The revision id %s does not look like it came from Arch."\
            % revision_id
        Exception.__init__(self, msg)

def arch_revision(revision_id):
    """
    >>> str(arch_revision("Arch-1:jrandom@example.com%test--test--0"))
    Traceback (most recent call last):
    NotArchRevision: The revision id Arch-1:jrandom@example.com%test--test--0 does not look like it came from Arch.
    >>> str(arch_revision("Arch-1:jrandom@example.com%test--test--0--base-5"))
    Traceback (most recent call last):
    NotArchRevision: The revision id Arch-1:jrandom@example.com%test--test--0--base-5 does not look like it came from Arch.
    >>> str(arch_revision("Arch-1:jrandom@example.com%test--test--0--patch-5"))
    'jrandom@example.com/test--test--0--patch-5'
    """
    if revision_id is None:
        return None
    if revision_id[:7] != 'Arch-1:':
        raise NotArchRevision(revision_id)
    else:
        try:
            return pybaz.Revision(revision_id[7:].replace('%', '/'))
        except pybaz.errors.NamespaceError, e:
            raise NotArchRevision(revision_id)
            
def iter_import_version(output_dir, ancestors, tempdir, pb, fast=False,
                        verbose=False, dry_run=False, max_count=None):
    revdir = None

    # Uncomment this for testing, it basically just has baz2bzr only update
    # 5 patches at a time
    if max_count:
        ancestors = ancestors[:max_count]

    # Not sure if I want this output. basically it tells you ahead of time
    # what it is going to do, but then later it tells you as it is doing it.
    # what probably would be best would be to collapse it into ranges, so that
    # this gives the simple view, and then later it gives the blow by blow.
    #if verbose:
    #    print 'Adding the following revisions:'
    #    for a in ancestors:
    #        print '\t%s' % a

    previous_version=None
    missing_ancestor = None

    for i in range(len(ancestors)):
        revision = ancestors[i]
        rev_id = revision_id(revision)
        direct_merges = []
        if verbose:
            version = str(revision.version)
            if version != previous_version:
                clear_progress_bar()
                print '\rOn version: %s' % version
            yield Progress(str(revision.patchlevel), i, len(ancestors))
            previous_version = version
        else:
            yield Progress("revisions", i, len(ancestors))
        if revdir is None and os.path.exists(output_dir):
            # check for imported revisions and if present just append immediately
            branch = Branch.open(output_dir)
            if branch.has_revision(rev_id):
                branch.append_revision(rev_id)
                continue
        if revdir is None:
            revdir = os.path.join(tempdir, "rd")
            try:
                tree, baz_inv, log = get_revision(revdir, revision)
            except pybaz.errors.ExecProblem, e:
                if ("%s" % e.args).find('could not connect') == -1:
                    raise
                missing_ancestor = revision
                revdir = None
                print ("unable to access ancestor %s, making into a merge."
                       % missing_ancestor)
                continue
            if os.path.exists(output_dir):
                bzr_dir = os.path.join(output_dir, '.bzr')
                new_bzr_dir = os.path.join(tempdir, "rd", '.bzr')
                # This would be much faster with a simple os.rename(), but if
                # we fail, we have corrupted the original .bzr directory.  Is
                # that a big problem, as we can just back out the last
                # revisions in .bzr/revision_history I don't really know
                # RBC20051024 - yes, it would be a problem as we could not then
                # apply the corrupted revision.
                shutil.copytree(bzr_dir, new_bzr_dir)
                # Now revdir should have a tree with the latest .bzr, and the
                # next revision of the baz tree
                branch = Branch.open(revdir)
            else:
                branch = Branch.initialize(revdir)
        else:
            old = os.path.join(revdir, ".bzr")
            new = os.path.join(tempdir, ".bzr")
            os.rename(old, new)
            baz_inv, log = apply_revision(tree, revision)
            os.rename(new, old)
            branch = Branch.open(revdir)
        # cached so we can delete the log
        log_date = log.date
        log_summary = log.summary
        log_description = log.description
        is_continuation = log.continuation_of is not None
        log_creator = log.creator
        direct_merges = get_direct_merges(revdir, revision, log)

        timestamp = email.Utils.mktime_tz(log_date + (0,))
        if log_summary is None:
            log_summary = ""
        # log_descriptions of None and "" are ignored.
        if not is_continuation and log_description:
            log_message = "\n".join((log_summary, log_description))
        else:
            log_message = log_summary
        branch.lock_write()
        target_tree = WorkingTree(revdir ,branch=branch)
        target_tree.lock_write()
        try:
            if missing_ancestor:
                # if we want it to be in revision-history, do that here.
                target_tree.add_pending_merge(revision_id(missing_ancestor))
                missing_ancestor = None
            for merged_rev in direct_merges:
                target_tree.add_pending_merge(revision_id(merged_rev))
            target_tree.set_inventory(baz_inv)
            commitobj = Commit(reporter=ImportCommitReporter(pb))
            commitobj.commit(branch, log_message.decode('ascii', 'replace'), 
                             verbose=False, committer=log_creator,
                             timestamp=timestamp, timezone=0, rev_id=rev_id)
        finally:
            target_tree.unlock()
            branch.unlock()
    yield Progress("revisions", len(ancestors), len(ancestors))
    unlink_unversioned(branch, revdir)

def get_direct_merges(revdir, revision, log):
    continuation = log.continuation_of
    previous_version = revision.version
    if pybaz.WorkingTree(revdir).tree_version != previous_version:
        pybaz.WorkingTree(revdir).set_tree_version(previous_version)
    log_path = "%s/{arch}/%s/%s/%s/%s/patch-log/%s" % (revdir, 
        revision.category.nonarch, revision.branch.nonarch, 
        revision.version.nonarch, revision.archive, revision.patchlevel)
    temp_path = tempfile.mktemp(dir=os.path.dirname(revdir))
    os.rename(log_path, temp_path)
    merges = list(iter_new_merges(revdir, revision.version))
    direct = direct_merges(merges, [continuation])
    os.rename(temp_path, log_path)
    return direct

def unlink_unversioned(branch, revdir):
    for unversioned in branch.working_tree().extras():
        path = os.path.join(revdir, unversioned)
        if os.path.isdir(path):
            shutil.rmtree(path)
        else:
            os.unlink(path)

def get_log(tree, revision):
    log = pybaz.Patchlog(revision, tree=tree)
    assert str(log.revision) == str(revision), (log.revision, revision)
    return log

def get_revision(revdir, revision):
    tree = revision.get(revdir)
    log = get_log(tree, revision)
    try:
        return tree, bzr_inventory_data(tree), log 
    except BadFileKind, e:
        raise UserError("Cannot convert %s because %s is a %s" % (revision,e.path, e.kind) )


def apply_revision(tree, revision):
    revision.apply(tree)
    log = get_log(tree, revision)
    try:
        return bzr_inventory_data(tree), log
    except BadFileKind, e:
        raise UserError("Cannot convert %s because %s is a %s" % (revision,e.path, e.kind) )


class BadFileKind(Exception):
    """The file kind is not permitted in bzr inventories"""
    def __init__(self, tree_root, path, kind):
        self.tree_root = tree_root
        self.path = path
        self.kind = kind
        Exception.__init__(self, "File %s is of forbidden type %s" %
                           (os.path.join(tree_root, path), kind))


def bzr_inventory_data(tree):
    inv_iter = tree.iter_inventory_ids(source=True, both=True)
    inv_map = {}
    for arch_id, path in inv_iter:
        bzr_file_id = map_file_id(arch_id)
        inv_map[path] = bzr_file_id 

    bzr_inv = []
    for path, file_id in inv_map.iteritems():
        full_path = os.path.join(tree, path)
        kind = bzrlib.osutils.file_kind(full_path)
        if kind not in ("file", "directory", "symlink"):
            raise BadFileKind(tree, path, kind)
        parent_dir = os.path.dirname(path)
        if parent_dir != "":
            parent_id = inv_map[parent_dir]
        else:
            parent_id = bzrlib.inventory.ROOT_ID
        bzr_inv.append((path, file_id, parent_id, kind))
    bzr_inv.sort()
    return bzr_inv

_global_option('max-count', type = int)
class cmd_baz_import_branch(Command):
    """Import an Arch or Baz branch into a bzr branch"""
    takes_args = ['to_location', 'from_branch?', 'reuse_history*']
    takes_options = ['verbose', 'max-count']

    def printer(self, name):
        print name

    def run(self, to_location, from_branch=None, fast=False, max_count=None,
            verbose=False, dry_run=False, reuse_history_list=[]):
        to_location = os.path.realpath(str(to_location))
        if from_branch is not None:
            try:
                from_branch = pybaz.Version(from_branch)
            except pybaz.errors.NamespaceError:
                print "%s is not a valid Arch branch." % from_branch
                return 1
        if reuse_history_list is None:
            reuse_history_list = []
        import_version(to_location, from_branch, self.printer, 
                       max_count=max_count, 
                       reuse_history_from=reuse_history_list)


class NotInABranch(Exception):
    def __init__(self, path):
        Exception.__init__(self, "%s is not in a branch." % path)
        self.path = path


class cmd_baz_import(Command):
    """Import an Arch or Baz archive into bzr branches.
    
    reuse_history allows you to specify any previous imports you 
    have done of different archives, which this archive has branches
    tagged from. This will dramatically reduce the time to convert 
    the archive as it will not have to convert the history already
    converted in that other branch.
    """
    takes_args = ['to_root_dir', 'from_archive', 'reuse_history*']
    takes_options = ['verbose']

    def printer(self, name):
        print name

    def run(self, to_root_dir, from_archive, verbose=False,
            reuse_history_list=[]):
        if reuse_history_list is None:
            reuse_history_list = []
        to_root = str(os.path.realpath(to_root_dir))
        if not os.path.exists(to_root):
            os.mkdir(to_root)
        import_archive(to_root, from_archive, verbose, self.printer, 
                       reuse_history_list)


def import_archive(to_root, from_archive, verbose, printer,
                   reuse_history_from=[]):
    real_to = os.path.realpath(to_root)
    history_locations = [real_to] + reuse_history_from
    for version in pybaz.Archive(str(from_archive)).iter_versions():
        target = os.path.join(to_root, map_namespace(version))
        printer("importing %s into %s" % (version, target))
        if not os.path.exists(os.path.dirname(target)):
            os.makedirs(os.path.dirname(target))
        try:
            import_version(target, version, printer,
                           reuse_history_from=reuse_history_from)
        except pybaz.errors.ExecProblem,e:
            if str(e).find('The requested revision cannot be built.') != -1:
                printer("Skipping version %s as it cannot be built due"
                        " to a missing parent archive." % version)
            else:
                raise
        except UserError, e:
            if str(e).find('already exists, and the last revision ') != -1:
                printer("Skipping version %s as it has had commits made"
                        " since it was converted to bzr." % version)
            else:
                raise


def map_namespace(a_version):
    a_version = pybaz.Version("%s" % a_version)
    parser = NameParser(a_version)
    version = parser.get_version()
    branch = parser.get_branch()
    category = parser.get_category()
    if branch is None or branch == '':
        branch = "+trunk"
    if version == '0':
        return "%s/%s" % (category, branch)
    return "%s/%s/%s" % (category, version, branch)

def map_file_id(file_id):
    """Convert a baz file id to a bzr one."""
    return file_id.replace('%', '%25').replace('/', '%2f')