~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
# Copyright (C) 2004 Aaron Bentley
# <aaron.bentley@utoronto.ca>
#
#    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 pybaz as arch
import paths
import os
import errors
import util
import re
import urlparse
import httplib

__docformat__ = "restructuredtext"
__doc__ = "Native implementation of Arch functionality"

def cat_log(dir, revision):
    """Return a string containing the patchlog for a revision.

    :param dir: The tree-root directory
    :type dir: str
    :param revision: The revision of the log to get
    :type revision: str
    """
    return open(paths.tree_log(dir, arch.Revision(revision))).read()


class ArchParams:
    """Provide list-style access to Arch parameters."""
    def __init__(self, dir=None):
        if dir is None:
            self.dir = os.path.expanduser("~/.arch-params")
            if not os.access(self.dir, os.R_OK):
                raise errors.NoArchParams(self.dir)
        else:
            self.dir = dir

    def name_path(self, param_name):
        """Produce the path associated with the param name"""
        return self.dir + "/" + param_name

    def __getitem__(self, name):
        """Return the value of the parameter.  For directories, this is another
        ArchParam instance.

        :param name: The name of the parameter
        :type name: str
        :rtype: str or `ArchParams`
        """
        path = self.name_path(name)
        if not os.access(path, os.R_OK):
            raise KeyError
        if os.path.isdir(path):
            return ArchParams(path)
        else:
            return open(path).read()

    def exists(self, name):
        """Determine whether a given parameter exists"""
        return os.access(self.name_path(name), os.R_OK)

    def value(self, name):
        """Get the value of the parameter, or None if it doesn't exist

        :param name: The name of the parameter
        :type name: str
        :rtype: str, ArchParams, or NoneType
        """
        try: 
            return self.__getitem__(name)
        except KeyError:
            return None
                   
    has_key = exists
    
    def __iter__(self):
        return os.listdir(self.dir).__iter__()

    iterkeys = __iter__

# Override standard cat_log, so automatic patchlog reading is faster
arch.backends.baz.cat_log = cat_log


def _tree_root_dir(path):
    if os.path.exists(os.path.join(path, "{arch}")):
        return path
    else:
        newpath = (path+"/..")
        if not os.path.samefile(newpath, path):
            return _tree_root_dir(newpath)
        else:
            return None


def is_arch_dir(path):
    """Determine whether the specified path is in an Arch tree
    :param path: The path to examine
    :type path: str
    :return: bool
    """
    return _tree_root_dir(path) is not None 


class BinaryFiles(Exception):
    def __init__(self, orig, mod):
        msg = "Binary files %s and %s differ" % (orig, mod)
        Exception.__init__(self, msg)
        self.orig = orig
        self.mod = mod


def invoke_diff(orig_dir, orig_name, mod_dir, mod_name, diff_args=None):
    """Invoke diff on files using tla style

    :orig_dir: The old arch tree
    :orig_name: The old relative filename
    :mod_dir: The new arch tree
    :mod_name: The new relative filename
    :diff_args: Optional diff parameters ("-u") by default
    :return: The diffs produced
    :rtype: str
    """
    if orig_name is not None:
        orig_filename = orig_dir+'/'+orig_name
        orig_display = "orig"+orig_name[1:]
    else:
        orig_filename = "/dev/null"
        orig_display = "/dev/null"
    if mod_name is not None:
        mod_filename = mod_dir+'/'+mod_name
        mod_display = "mod"+mod_name[1:]
    else:
        mod_filename = "/dev/null"
        mod_display = "/dev/null"

    if diff_args is None:
        diff_args = ("-u",)
    args = ["--binary", "-L", orig_display, "-L", mod_display]
    args.extend(diff_args)
    args.extend((orig_filename, mod_filename))
    try:
        return arch.util.exec_safe_stdout('diff', args, expected=(0, 1))
    except arch.errors.ExecProblem, e:
        if not e.proc.status == 2:
            raise
        raise BinaryFiles(orig_filename, mod_filename)
    
def invoke_patch(file, diff, out_file, reverse=False):
    args = ["-f", "-s", "--posix", "--binary"]
    if reverse:
        args.append("--reverse")
    args.extend(("-i", diff, "-o", out_file, file))
    status = arch.util.exec_safe_silent('patch', args, expected=(0, 1))
    return status

def invoke_diff3(out_file, mine_path, older_path, yours_path):
    def add_label(args, label):
        args.extend(("-L", label))
    args = ["-E", "--merge"]
    add_label(args, "TREE")
    add_label(args, "ANCESTOR")
    add_label(args, "MERGE-SOURCE")
    args.extend((mine_path, older_path, yours_path))
    (status, output) = arch.util.exec_safe_status_stdout('diff3', args, 
        expected=(0,1))
    out_file.write(output)
    if status == 1:
        open(mine_path+".rej", "wb").write(
            "Conflicts occured, diff3 conflict markers left in file.\n")
    return status


class MungeOpts:
    """A set of options for changeset munging"""
    def __init__(self, value=False):
        """Initializes, sets all types of change to True or False.

        hunk_prompt is not included.
        :param value: The value to set everything to
        :type value: bool"""
        self.all_types(value)
        self.hunk_prompt = False
        self.keep_pattern = None

    def set_hunk_prompt(self, display, confirm, active=True):
        """Initializes the hunk-prompting settings
        :param display: The function to use for displaying hunk lines
        :param confirm: The function to use for confirming hunks
        :param active: If true, use hunk prompting
        """
        self.hunk_prompt = active
        self.hunk_confirm = confirm
        self.hunk_display = display


    def all_types(self, value):
        """Sets all types of change to True or False.

        hunk_prompt is not included.
        :param value: The value to set everything to
        :type value: bool"""
        self.file_perms = value
        self.file_contents = value
        self.deletions = value
        self.additions = value
        self.renames = value


    def add_keep_file(self, new_file):
        """Adds a filename to the keep_pattern string.

        :param new_file: The new file to add.  (from tree root)
        :type new_file: str
        """
        self.add_keep_pattern("^"+util.regex_escape(new_file)+"$")

    def add_keep_pattern(self, new_pattern):
        """Adds a pattern to the keep_pattern string.  Patterns are ORed.

        :param new_pattern: The pattern to add
        :type new_pattern: str
        """
        if self.keep_pattern is not None:
            self.keep_pattern += "|"
        else: 
            self.keep_pattern = ""
        self.keep_pattern += new_pattern
        return self.keep_pattern


class ChangesetEntry:
    """Represents the changes performed to a file or directory by a changeset"""
    def __init__(self, changeset, id):
        """Initial set-up.  Sets id, orig_name, orig_type, mod_name, mod_type
        
        :param changeset: The changeset the file is in
        :type changeset: `ChangesetMunger`
        :param id: The inventory id of the file
        :type id: str
        """
        self.id = id
        if changeset.orig_files_index.has_key(id):
            self.orig_name = changeset.orig_files_index[id]
            self.orig_type = "file"
        elif changeset.orig_dirs_index.has_key(id):
            self.orig_name = changeset.orig_dirs_index[id]
            self.orig_type = "dir"
        else:
            self.orig_name = None
            self.orig_type = None

        if changeset.mod_files_index.has_key(id):
            self.mod_name = changeset.mod_files_index[id]
            self.mod_type = "file"
        elif changeset.mod_dirs_index.has_key(id):
            self.mod_name = changeset.mod_dirs_index[id]
            self.mod_type = "dir"
        else:
            self.mod_name = None
            self.mod_type = None

        self.init_attribs(changeset)

    def init_attribs(self, changeset):
        """Uses the mod and orig info to determine which change files exist

        :param changeset: The changeset containing the changes
        :type changeset: `ChangesetMunger`
        """
        self.removed_file = None
        self.orig_perms = None
        self.original = None
        self.modified = None
        if self.orig_name:
            if self.orig_type == "file":
                self.removed_file = changeset.path_exists(self.orig_name,
                                                      "removed-files-archive")
            else:
                self.old_perms = changeset.orig_dir_metadata.get(self.orig_name)

        self.new_file = None
        self.mod_perms = None
        self.diff = None
        if self.mod_name and self.mod_type == "file":
            self.new_file = changeset.path_exists(self.mod_name,
                                                      "new-files-archive")
            self.mod_perms = changeset.path_exists(self.mod_name, "patches",
                                                   ".meta-mod")
            self.orig_perms = changeset.path_exists(self.mod_name, "patches",
                                                   ".meta-orig")
            self.diff = changeset.path_exists(self.mod_name, "patches", 
                                              ".patch")
            self.original = changeset.path_exists(self.mod_name, "patches", 
                                              ".original")
            self.modified = changeset.path_exists(self.mod_name, "patches", 
                                              ".modified")

        elif self.mod_name and self.mod_type == "dir":
            self.mod_perms = changeset.path_exists(self.mod_name, "patches",
                                                   "/=dir-meta-mod")
            self.orig_perms = changeset.path_exists(self.mod_name, "patches",
                                                   "/=dir-meta-orig")
            self.new_perms = changeset.mod_dir_metadata.get(self.mod_name)


    def rename(self, old_name, changeset, new_file, topdir, extension=""):
        """Rename a changeset and return its new pathname.

        :param old_name: The old full pathname
        :type old_name: str or NoneType
        :param changeset: The changeset containing this entry
        :type changeset: `ChangesetMunger`
        :param topdir: The top directory containing the file
        :type topdir: str
        :param extension: The file extension, if any
        :type extension: str
        :return: The new full pathname of the files
        :rtype: str
        """
        if old_name is None:
            return None
        tmp = changeset.path(new_file, topdir, extension)
        os.rename(old_name, tmp)
        return tmp
        

    def rename_mod(self, new_name, changeset):
        """Change the modified name of this entry.  This undoes renames,
        but probably not the way you'd like.

        :param new_name: the new file name
        :type new_name: str
        :param changeset: the changeset this entry is part of
        :type changeset: `ChangesetMunger`
        """
        self.new_file = self.rename(self.new_file, changeset, new_name,
                                    "new-files-archive")
        self.mod_perms = self.rename(self.mod_perms, changeset, new_name, 
                                     "patches", ".meta-mod")
        self.orig_perms = self.rename(self.orig_perms, changeset, new_name, 
                                     "patches", ".meta-orig")
        self.diff = self.rename(self.diff, changeset, new_name, "patches",
                                ".patch")
        self.original = self.rename(self.original, changeset, new_name, 
                                    "patches", ".original")
        self.modified = self.rename(self.modified, changeset, new_name, 
                                    "patches", ".modified")
        self.mod_name = new_name

    def rename_orig(self, new_name, changeset):
        """Change the original name of this entry.  This undoes renames.

        :param new_name: the new file name
        :type new_name: str
        :param changeset: the changeset this entry is part of
        :type changeset: `ChangesetMunger`
        """
        self.new_file = self.rename(self.new_file, changeset, new_name,
                                    "new-files-archive")
        self.orig_name = new_name

    def delete_contents_files(self):
        """delete the contents change files for this entry"""
        if self.mod_name is not None:
            util.safe_unlink(self.original)
            util.safe_unlink(self.diff)
            util.safe_unlink(self.modified)

    def delete_perms_files(self):
        """Delete the permissions files for this entry"""
        util.safe_unlink(self.orig_perms)
        util.safe_unlink(self.mod_perms)
        
    def delete_files(self):
        """Delete all change files for this ID"""
        util.safe_unlink(self.removed_file)
        util.safe_unlink(self.new_file)
        self.delete_contents_files()
        self.delete_perms_files()

    def get_print_name(self):
        if self.mod_name is not None:
            return self.mod_name
        else:
            return self.orig_name

    def get_perm_change(self):
        orig = int(open(self.orig_perms).read().split()[1], 8)
        mod = int(open(self.mod_perms).read().split()[1], 8)
        return (orig, mod)


class ChangesetMunger:
    """An abstraction of a changeset that can edit it"""
    def __init__(self, changeset):
        self.changeset = str(changeset)

    def parse_index(self, filename):
        index = {}
        for line in open(self.changeset+filename):
            (value,key) = line.split(' ')
            index[key.rstrip('\n')] = value
        return index

    def parse_dir_metadata(self, filename):
        index = {}
        for line in open(self.changeset+filename):
            data = line.split()
            index[data[2]] = int(data[1], 8)
        return index


    def write_index(self, filename, index):
        os.unlink(self.changeset+filename)
        my_file = open(self.changeset+filename, 'w')
        for (key, value) in index.iteritems():
            my_file.write(' '.join((value, key))+'\n')
        my_file.flush()
        my_file.close()

    def remove_unique(self, mod_files_index, orig_files_index):
        keys = []
        for (key,value) in mod_files_index.iteritems():
            if not orig_files_index.has_key(key):
                keys.append(key)
        for key in keys:
            del mod_files_index[key]
        return mod_files_index
    
    def copy_values(self, mod_files_index, orig_files_index):
        for (key, value) in orig_files_index.iteritems():
            if mod_files_index.has_key(key):
                mod_files_index[key] = value

    def read_indices(self):
        try:
            self.orig_files_index = self.parse_index("/orig-files-index")
            self.mod_files_index = self.parse_index("/mod-files-index")
            self.orig_dirs_index = self.parse_index("/orig-dirs-index")
            self.mod_dirs_index = self.parse_index("/mod-dirs-index")
            try:
                self.orig_dir_metadata = \
                    self.parse_dir_metadata("/original-only-dir-metadata")
                self.mod_dir_metadata = \
                    self.parse_dir_metadata("/modified-only-dir-metadata")
            except IOError, e:
                if e.errno == 2:
                    print "Old changeset: no dir-metatdata"
                    self.mod_dir_metadata = {}
                    self.orig_dir_metadata = {}
                else:
                    raise
        except IOError:
            raise errors.InvalidChangeset(self.changeset)
            

    def write_indices(self):
        self.write_index("/orig-files-index", self.orig_files_index)
        self.write_index("/mod-files-index", self.mod_files_index)
        self.write_index("/mod-dirs-index", self.mod_dirs_index)
        self.write_index("/orig-dirs-index", self.orig_dirs_index)

    def remove_additions(self):
        for (root, dirs, files) in os.walk(self.changeset+"/new-files-archive"):
            for my_file in files:
                os.unlink("/".join((root,my_file)))
        self.remove_unique(self.mod_files_index, self.orig_files_index)
        self.remove_unique(self.mod_dirs_index, self.orig_dirs_index)

    def remove_deletions(self):
        for (root, dirs, files) in \
            os.walk(self.changeset+"/removed-files-archive"):
                for my_file in files:
                    os.unlink("/".join((root,my_file)))
        self.remove_unique(self.orig_files_index, self.mod_files_index)
        self.remove_unique(self.orig_dirs_index, self.mod_dirs_index)

    def munge(self, opts=None):
        """Munges this changeset according to the specified options.

        :param opts: The options to munge with
        :type opts: `MungeOpts`
        :return: The number of entries that matched the keep pattern
        """
        self.read_indices()
        matches = 0

        if opts.keep_pattern:
            keep_pattern = re.compile(opts.keep_pattern)
        else:
            keep_pattern = None

        for entry in self.get_entries().itervalues():
            if keep_pattern is not None and \
                not self.entry_matches_pattern(entry, keep_pattern):
                    self.remove_entry(entry)
                    continue
            else:
                matches+=1
                    
            if not opts.file_contents or opts.hunk_prompt:
                if opts.hunk_prompt:
                    if entry.diff is not None:
                        patch_trim(entry.diff, opts.hunk_display, 
                                   opts.hunk_confirm)
                else:
                    entry.delete_contents_files()
            if not opts.file_perms:
                entry.delete_perms_files()
                        
        if not opts.additions:
            self.remove_additions()

        if not opts.deletions:
            self.remove_deletions()

        if not opts.renames:
            self.copy_values(self.orig_files_index, self.mod_files_index)
        self.write_indices()
        return matches

    def entry_matches_pattern(self, entry, pattern):
        """Determine whether any of an entry's names matches the pattern.
        
        :param entry: The ChangesetEntry to check
        :type entry: `ChangesetEntry`
        :param pattern: The pattern to check
        :type pattern: Compiled regex
        """
        return (entry.orig_name is not None and \
            pattern.search(entry.orig_name) is not None) or \
            (entry.mod_name is not None and \
             pattern.search(entry.mod_name) is not None)

    def add_unique_entries(self, entries, index):
        for file_id in index.iterkeys():
            if not entries.has_key(file_id):
                entries[file_id] = ChangesetEntry(self, file_id)

    def safe_remove(self, index, id):
        if index.has_key(id):
            del index[id]
        

    def get_entries(self):
        """Returns a map of ChangesetEntries
        """
        entries = {}
        self.add_unique_entries(entries, self.orig_files_index)
        self.add_unique_entries(entries, self.orig_dirs_index)
        self.add_unique_entries(entries, self.mod_files_index)
        self.add_unique_entries(entries, self.mod_dirs_index)
        return entries

    def remove_entry(self, entry):
        """
        Remove all files and index entries for an ChangesetEntry.

        :param entry: The entry to remove
        :type entry: `ChangesetEntry`
        """
        entry.delete_files()
        self.safe_remove(self.orig_files_index, entry.id)
        self.safe_remove(self.orig_dirs_index, entry.id)
        self.safe_remove(self.mod_files_index, entry.id)
        self.safe_remove(self.mod_dirs_index, entry.id)

    def patchfile(self, id):
        if not self.mod_files_index.has_key(id):
            print "no key%s" % id
            return None
        path = self.changeset+"/patches"+self.mod_files_index[id][1:]+".patch"

        if os.access(path, os.R_OK):
            return path
        else:
            return None


    def path(self, name, topdir, extension=""):
        return self.changeset + "/" + topdir + name[1:] + extension
        

    def path_exists(self, name, topdir, extension=""):
        pth = self.path(name, topdir, extension)
        try:
            os.lstat(pth)
            return pth
        except:
            return None

    def files_to_ids(self, filenames, type="mod"):
        f_idx = misc.invert_dict(self.__dict__[type+"_files_index"])
        d_idx = misc.invert_dict(self.__dict__[type+"_dirs_index"])
        idlist = []
        for my_file in filenames:
            if f_idx.has_key(my_file):
                idlist.append(f_idx[my_file])
            elif d_idx.has_key(my_file):
                idlist.append(d_idx[my_file])
        return idlist


def patch_trim(filename, display_func, confirm_func):
    """Remove hunks from a patch according to confirm_func
    
    :param filename: The name of the patch file
    :type filename: str
    :param confirm_func: The function to use for selecting hunks
    :type confirm_func: 1-parameter callable returning bool
    """
    source = open(filename)
    output = util.NewFileVersion(filename)
    header = source.next()
    header += source.next()
    for line in diff_classifier(header.split('\n')):
        display_func(line)
    
    hunk = None
    for line in source:
        if line.startswith("@@"):
            if maybe_write_hunk(output, hunk, header, confirm_func):
                header = None
            hunk = ""
        hunk += line

    if maybe_write_hunk(output, hunk, header, confirm_func):
        header = None
    output.commit()
    if header is not None:
        os.unlink(filename)


def maybe_write_hunk(output, hunk, header, confirm_func):
    """Writes a hunk to a file, if it passes the confirmation function.

    :param output: The place to write confirmed hunks
    :type output: file
    :param hunk: The hunk to write
    :type hunk: str
    :param header: The hunk header (if this would be the first in file)
    :type header: str
    :param confirm_func: The function to test hunks with
    :type confirm_func: 1-parameter callable that returns bool
    """
    if hunk is not None:
        if confirm_func(hunk):
            if header is not None:
                output.write(header)
            output.write(hunk)
            return True
    return False


def get_pfs_type(location):
    if location.startswith("cached:"):
        location=location[len("cached:"):]
    if location.startswith("/"):
        return PfsFilesystem, location
    elif location.startswith("http://"):
        return PfsHttp, location
    elif location.startswith("https://"):
        return PfsHttp
    else:
        raise errors.UnsupportedScheme(location)

def get_pfs(location):
    type,location = get_pfs_type(location)
    return type(location)

class PfsFilesystem:
    def __init__(self, location):
        self.location = location

    def full_path(path):
        return os.path.join(self.location, path)

    def get(path):
        return file(self.full_path(path), "rb")

    def exists(path):
        try:
            stat(self.full_path(path))
            return True
        except:
            return False

def spliturl(location):
    loc = urlparse.urlparse(location)
    scheme = loc[0]
    netloc = loc[1].split(':')
    host = netloc[0]
    if len(netloc) > 1:
        port = int(netloc[1])
    else:
        port = None
    return (scheme, host, port, loc[2])

class HttpError(Exception):
    def __init__(self, response):
        self.response = response
        msg = "Unexpected status: %s" % self.response.reason
        Exception.__init__(self, msg)

class PfsHttp:
    def __init__(self, location):
        (scheme, self.host, self.port, self.path) = spliturl(location)
        assert (scheme in ["http", "https"])
        if scheme == "http":
            self.ConnectionType = httplib.HTTPConnection
            if self.port is None:
                self.port = httplib.HTTP_PORT
        else:
            self.ConnectionType = httplib.HTTPSConnection
            if self.port is None:
                self.port = httplib.HTTPS_PORT
        self.path = self.path.rstrip('/')
        self.connection = self.ConnectionType(self.host, self.port)

    def absolute_path(self, path):
        return "%s/%s" % (self.path, path)
        
    def get(self, path):
        try:
            self.connection.request("GET", self.absolute_path(path))
            response = self.connection.getresponse()
        except:
            self.connection = self.ConnectionType(self.host, self.port)        
            self.connection.request("GET", self.absolute_path(path))
            response = self.connection.getresponse()
        if response.status != 200:
            raise HttpError(response)
        return response

    def exists(self, path):
        try:
            self.connection.request("HEAD", self.absolute_path(path))
            response = self.connection.getresponse()
        except Exception, e:
            self.connection = self.ConnectionType(self.host, self.port)        
            self.connection.request("HEAD", self.absolute_path(path))
            response = self.connection.getresponse()
        if response.status == 200:
            response.read()
            return True
        elif response.status == 404:
            response.read()
            return False
        else:
            raise HttpError(response)

    def list(self, path):
        l_path = path.rstrip('/')+'/'+'.listing'
        try:
            return self.get(l_path).read().splitlines()
        except HttpError, e:
            if not e.response.status == 404:
                raise
            raise Exception("No listing file for %s" % l_path)

class ArchPath:
    def __init__(self):
        self.name = "=meta-info/name"

    def get_category_path(self, category):
        return category.nonarch

    def get_branch_path(self, branch):
        return "%s/%s" % (self.get_category_path(branch.category), 
                          branch.nonarch)

    def get_version_path(self, version):
        return "%s/%s" % (self.get_branch_path(version.branch), version.nonarch)

    def get_revision_path(self, revision):
        return "%s/%s" % (self.get_version_path(revision.version),
                          str(revision.patchlevel))

    def get_revision_file(self, revision, file):
        return "%s/%s" % (self.get_revision_path(revision), file)
        
        
        
class BazPath:
     def __init__(self):
        ArchPath.__init__(self)

path_generator = {
"Hackerlab arch archive directory, format version 2.": ArchPath,
"Bazaar archive format 1 0": BazPath,
}

archives = {}

def get_pfs_archive(location, name):
    archive = archives.get(location)
    if archive is not None:
        if archive.name != name:
            raise Exception("Archive has wrong name %s (expected %s)" \
                % (archive.name, name))
        return archive
    else:
        archives[location] = PfsArchive(location, name)
        return archives[location]


class PfsArchive:
    def __init__(self, location, name):
        self.pfs = get_pfs(location)
        self.archive_type = self.pfs.get(".archive-version").read().strip()
        self.path_generator = path_generator[self.archive_type]()
        self.name = self.pfs.get(self.path_generator.name).read().strip()
        if name is not None and self.name != name:
            raise Exception("Archive has wrong name %s (expected %s)" % \
                (self.name, name))

    def get_patch(self, revision):
        myfile = revision.nonarch+".patches.tar.gz"
        path = self.path_generator.get_revision_file(revision, myfile)
        return self.pfs.get(path)
            

    def exists(self, revision):
        path = self.path_generator.get_revision_file(revision, "log")
        return self.pfs.exists(path)


def cache_path():
    params = ArchParams()
    if not params.exists('=arch-cache'):
        return None
    return params['=arch-cache'].strip()

def cache_revision_query(revision, rfile=None):
    path = os.path.join("archives/",str(revision))
    if rfile is not None:
        path = os.path.join(path, rfile)
    return path

def cache_get(query):
    try:
        return open(os.path.join(cache_path(), query), "rb")
    except IOError, e:
        if e.errno == 2:
            return None
        else:
            raise

def cache_get_revision(revision, rfile):
    return cache_get(cache_revision_query(revision, rfile))


class DiffFilenames:
    def __init__(self, origline, modline):
        self.orig = origline[3:]
        self.mod = modline[3:]

    def __str__(self):
        return "---%s\n+++%s" % (self.orig, self.mod)


class DiffHunk:
    def __init__(self, line):
        self.line=line

    def __str__(self):
        return self.line


class DiffLine:
    def __init__(self, line):
        self.line = line[1:]

    def __str__(self):
        return " "+self.line


class DiffAddLine(DiffLine):
    def __init__(self, line):
        DiffLine.__init__(self, line)
    
    def __str__(self):
        return "+"+self.line


class DiffRemoveLine(DiffLine):
    def __init__(self, line):
        DiffLine.__init__(self, line)
    
    def __str__(self):
        return "-"+self.line


def diff_classifier(iter):
    for line in iter:
        if isinstance(line, arch.Chatter):
            yield line
        elif line.startswith("---"):
            origname=line
        elif line.startswith("+++"):
            yield DiffFilenames(origname, line)
        elif line.startswith("@"):
            yield DiffHunk(line)
        elif line.startswith("+"):
            yield DiffAddLine(line)
        elif line.startswith("-"):
            yield DiffRemoveLine(line)
        elif line.startswith(" "):
            yield DiffLine(line)
        else:
            yield line

# arch-tag: b082ccd9-db04-422a-94d6-fb7fedcaabf0