File: wc.py

package info (click to toggle)
cvs2svn 2.4.0-4
  • links: PTS
  • area: main
  • in suites: stretch
  • size: 3,720 kB
  • sloc: python: 22,383; sh: 512; perl: 121; makefile: 84
file content (861 lines) | stat: -rw-r--r-- 28,800 bytes parent folder | download | duplicates (2)
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
#
#  wc.py: functions for interacting with a Subversion working copy
#
#  Subversion is a tool for revision control.
#  See http://subversion.tigris.org for more information.
#
# ====================================================================
#    Licensed to the Apache Software Foundation (ASF) under one
#    or more contributor license agreements.  See the NOTICE file
#    distributed with this work for additional information
#    regarding copyright ownership.  The ASF licenses this file
#    to you under the Apache License, Version 2.0 (the
#    "License"); you may not use this file except in compliance
#    with the License.  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing,
#    software distributed under the License is distributed on an
#    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
#    KIND, either express or implied.  See the License for the
#    specific language governing permissions and limitations
#    under the License.
######################################################################

import os
import sys
import re
import urllib

import svntest


#
# 'status -v' output looks like this:
#
#      "%c%c%c%c%c%c%c %c   %6s   %6s %-12s %s\n"
#
# (Taken from 'print_status' in subversion/svn/status.c.)
#
# Here are the parameters.  The middle number or string in parens is the
# match.group(), followed by a brief description of the field:
#
#    - text status           (1)  (single letter)
#    - prop status           (1)  (single letter)
#    - wc-lockedness flag    (2)  (single letter: "L" or " ")
#    - copied flag           (3)  (single letter: "+" or " ")
#    - switched flag         (4)  (single letter: "S", "X" or " ")
#    - repos lock status     (5)  (single letter: "K", "O", "B", "T", " ")
#    - tree conflict flag    (6)  (single letter: "C" or " ")
#
#    [one space]
#
#    - out-of-date flag      (7)  (single letter: "*" or " ")
#
#    [three spaces]
#
#    - working revision ('wc_rev') (either digits or "-", "?" or " ")
#
#    [one space]
#
#    - last-changed revision      (either digits or "?" or " ")
#
#    [one space]
#
#    - last author                (optional string of non-whitespace
#                                  characters)
#
#    [spaces]
#
#    - path              ('path') (string of characters until newline)
#
# Working revision, last-changed revision, and last author are whitespace
# only if the item is missing.
#
_re_parse_status = re.compile('^([?!MACDRUGI_~ ][MACDRUG_ ])'
                              '([L ])'
                              '([+ ])'
                              '([SX ])'
                              '([KOBT ])'
                              '([C ]) '
                              '([* ]) +'
                              '((?P<wc_rev>\d+|-|\?) +(\d|-|\?)+ +(\S+) +)?'
                              '(?P<path>.+)$')

_re_parse_skipped = re.compile("^Skipped.* '(.+)'\n")

_re_parse_summarize = re.compile("^([MAD ][M ])      (.+)\n")

_re_parse_checkout = re.compile('^([RMAGCUDE_ ][MAGCUDE_ ])'
                                '([B ])'
                                '([C ])\s+'
                                '(.+)')
_re_parse_co_skipped = re.compile('^(Restored|Skipped)\s+\'(.+)\'')
_re_parse_co_restored = re.compile('^(Restored)\s+\'(.+)\'')

# Lines typically have a verb followed by whitespace then a path.
_re_parse_commit = re.compile('^(\w+(  \(bin\))?)\s+(.+)')


class State:
  """Describes an existing or expected state of a working copy.

  The primary metaphor here is a dictionary of paths mapping to instances
  of StateItem, which describe each item in a working copy.

  Note: the paths should be *relative* to the root of the working copy,
  using '/' for the separator (see to_relpath()), and the root of the
  working copy is identified by the empty path: ''.
  """

  def __init__(self, wc_dir, desc):
    "Create a State using the specified description."
    assert isinstance(desc, dict)

    self.wc_dir = wc_dir
    self.desc = desc      # dictionary: path -> StateItem

  def add(self, more_desc):
    "Add more state items into the State."
    assert isinstance(more_desc, dict)

    self.desc.update(more_desc)

  def add_state(self, parent, state):
    "Import state items from a State object, reparent the items to PARENT."
    assert isinstance(state, State)

    if parent and parent[-1] != '/':
      parent += '/'
    for path, item in state.desc.items():
      path = parent + path
      self.desc[path] = item

  def remove(self, *paths):
    "Remove a path from the state (the path must exist)."
    for path in paths:
      del self.desc[to_relpath(path)]

  def copy(self, new_root=None):
    """Make a deep copy of self.  If NEW_ROOT is not None, then set the
    copy's wc_dir NEW_ROOT instead of to self's wc_dir."""
    desc = { }
    for path, item in self.desc.items():
      desc[path] = item.copy()
    if new_root is None:
      new_root = self.wc_dir
    return State(new_root, desc)

  def tweak(self, *args, **kw):
    """Tweak the items' values.

    Each argument in ARGS is the path of a StateItem that already exists in
    this State. Each keyword argument in KW is a modifiable property of
    StateItem.

    The general form of this method is .tweak([paths...,] key=value...). If
    one or more paths are provided, then those items' values are
    modified.  If no paths are given, then all items are modified.
    """
    if args:
      for path in args:
        try:
          path_ref = self.desc[to_relpath(path)]
        except KeyError, e:
          e.args = ["Path '%s' not present in WC state descriptor" % path]
          raise
        path_ref.tweak(**kw)
    else:
      for item in self.desc.values():
        item.tweak(**kw)

  def tweak_some(self, filter, **kw):
    "Tweak the items for which the filter returns true."
    for path, item in self.desc.items():
      if list(filter(path, item)):
        item.tweak(**kw)

  def subtree(self, subtree_path):
    """Return a State object which is a deep copy of the sub-tree
    identified by SUBTREE_PATH (which is assumed to contain only one
    element rooted at the tree of this State object's WC_DIR)."""
    desc = { }
    for path, item in self.desc.items():
      path_elements = path.split("/")
      if len(path_elements) > 1 and path_elements[0] == subtree_path:
        desc["/".join(path_elements[1:])] = item.copy()
    return State(self.wc_dir, desc)

  def write_to_disk(self, target_dir):
    """Construct a directory structure on disk, matching our state.

    WARNING: any StateItem that does not have contents (.contents is None)
    is assumed to be a directory.
    """
    if not os.path.exists(target_dir):
      os.makedirs(target_dir)

    for path, item in self.desc.items():
      fullpath = os.path.join(target_dir, path)
      if item.contents is None:
        # a directory
        if not os.path.exists(fullpath):
          os.makedirs(fullpath)
      else:
        # a file

        # ensure its directory exists
        dirpath = os.path.dirname(fullpath)
        if not os.path.exists(dirpath):
          os.makedirs(dirpath)

        # write out the file contents now
        open(fullpath, 'wb').write(item.contents)

  def normalize(self):
    """Return a "normalized" version of self.

    A normalized version has the following characteristics:

      * wc_dir == ''
      * paths use forward slashes
      * paths are relative

    If self is already normalized, then it is returned. Otherwise, a
    new State is constructed with (shallow) references to self's
    StateItem instances.

    If the caller needs a fully disjoint State, then use .copy() on
    the result.
    """
    if self.wc_dir == '':
      return self

    base = to_relpath(os.path.normpath(self.wc_dir))

    desc = dict([(repos_join(base, path), item)
                 for path, item in self.desc.items()])
    return State('', desc)

  def compare(self, other):
    """Compare this State against an OTHER State.

    Three new set objects will be returned: CHANGED, UNIQUE_SELF, and
    UNIQUE_OTHER. These contain paths of StateItems that are different
    between SELF and OTHER, paths of items unique to SELF, and paths
    of item that are unique to OTHER, respectively.
    """
    assert isinstance(other, State)

    norm_self = self.normalize()
    norm_other = other.normalize()

    # fast-path the easy case
    if norm_self == norm_other:
      fs = frozenset()
      return fs, fs, fs

    paths_self = set(norm_self.desc.keys())
    paths_other = set(norm_other.desc.keys())
    changed = set()
    for path in paths_self.intersection(paths_other):
      if norm_self.desc[path] != norm_other.desc[path]:
        changed.add(path)

    return changed, paths_self - paths_other, paths_other - paths_self

  def compare_and_display(self, label, other):
    """Compare this State against an OTHER State, and display differences.

    Information will be written to stdout, displaying any differences
    between the two states. LABEL will be used in the display. SELF is the
    "expected" state, and OTHER is the "actual" state.

    If any changes are detected/displayed, then SVNTreeUnequal is raised.
    """
    norm_self = self.normalize()
    norm_other = other.normalize()

    changed, unique_self, unique_other = norm_self.compare(norm_other)
    if not changed and not unique_self and not unique_other:
      return

    # Use the shortest path as a way to find the "root-most" affected node.
    def _shortest_path(path_set):
      shortest = None
      for path in path_set:
        if shortest is None or len(path) < len(shortest):
          shortest = path
      return shortest

    if changed:
      path = _shortest_path(changed)
      display_nodes(label, path, norm_self.desc[path], norm_other.desc[path])
    elif unique_self:
      path = _shortest_path(unique_self)
      default_singleton_handler('actual ' + label, path, norm_self.desc[path])
    elif unique_other:
      path = _shortest_path(unique_other)
      default_singleton_handler('expected ' + label, path,
                                norm_other.desc[path])

    raise svntest.tree.SVNTreeUnequal

  def tweak_for_entries_compare(self):
    for path, item in self.desc.copy().items():
      if item.status:
        # If this is an unversioned tree-conflict, remove it.
        # These are only in their parents' THIS_DIR, they don't have entries.
        if item.status[0] in '!?' and item.treeconflict == 'C':
          del self.desc[path]
        else:
          # when reading the entry structures, we don't examine for text or
          # property mods, so clear those flags. we also do not examine the
          # filesystem, so we cannot detect missing or obstructed files.
          if item.status[0] in 'M!~':
            item.status = ' ' + item.status[1]
          if item.status[1] == 'M':
            item.status = item.status[0] + ' '
          # under wc-ng terms, we may report a different revision than the
          # backwards-compatible code should report. if there is a special
          # value for compatibility, then use it.
          if item.entry_rev is not None:
            item.wc_rev = item.entry_rev
            item.entry_rev = None
      if item.writelocked:
        # we don't contact the repository, so our only information is what
        # is in the working copy. 'K' means we have one and it matches the
        # repos. 'O' means we don't have one but the repos says the item
        # is locked by us, elsewhere. 'T' means we have one, and the repos
        # has one, but it is now owned by somebody else. 'B' means we have
        # one, but the repos does not.
        #
        # for each case of "we have one", set the writelocked state to 'K',
        # and clear it to None for the others. this will match what is
        # generated when we examine our working copy state.
        if item.writelocked in 'TB':
          item.writelocked = 'K'
        elif item.writelocked == 'O':
          item.writelocked = None

  def old_tree(self):
    "Return an old-style tree (for compatibility purposes)."
    nodelist = [ ]
    for path, item in self.desc.items():
      nodelist.append(item.as_node_tuple(os.path.join(self.wc_dir, path)))

    tree = svntest.tree.build_generic_tree(nodelist)
    if 0:
      check = tree.as_state()
      if self != check:
        import pprint
        pprint.pprint(self.desc)
        pprint.pprint(check.desc)
        # STATE -> TREE -> STATE is lossy.
        # In many cases, TREE -> STATE -> TREE is not.
        # Even though our conversion from a TREE has lost some information, we
        # may be able to verify that our lesser-STATE produces the same TREE.
        svntest.tree.compare_trees('mismatch', tree, check.old_tree())

    return tree

  def __str__(self):
    return str(self.old_tree())

  def __eq__(self, other):
    if not isinstance(other, State):
      return False
    norm_self = self.normalize()
    norm_other = other.normalize()
    return norm_self.desc == norm_other.desc

  def __ne__(self, other):
    return not self.__eq__(other)

  @classmethod
  def from_status(cls, lines):
    """Create a State object from 'svn status' output."""

    def not_space(value):
      if value and value != ' ':
        return value
      return None

    desc = { }
    for line in lines:
      if line.startswith('DBG:'):
        continue

      # Quit when we hit an externals status announcement.
      ### someday we can fix the externals tests to expect the additional
      ### flood of externals status data.
      if line.startswith('Performing'):
        break

      match = _re_parse_status.search(line)
      if not match or match.group(10) == '-':
        # ignore non-matching lines, or items that only exist on repos
        continue

      item = StateItem(status=match.group(1),
                       locked=not_space(match.group(2)),
                       copied=not_space(match.group(3)),
                       switched=not_space(match.group(4)),
                       writelocked=not_space(match.group(5)),
                       treeconflict=not_space(match.group(6)),
                       wc_rev=not_space(match.group('wc_rev')),
                       )
      desc[to_relpath(match.group('path'))] = item

    return cls('', desc)

  @classmethod
  def from_skipped(cls, lines):
    """Create a State object from 'Skipped' lines."""

    desc = { }
    for line in lines:
      if line.startswith('DBG:'):
        continue

      match = _re_parse_skipped.search(line)
      if match:
        desc[to_relpath(match.group(1))] = StateItem()

    return cls('', desc)

  @classmethod
  def from_summarize(cls, lines):
    """Create a State object from 'svn diff --summarize' lines."""

    desc = { }
    for line in lines:
      if line.startswith('DBG:'):
        continue

      match = _re_parse_summarize.search(line)
      if match:
        desc[to_relpath(match.group(2))] = StateItem(status=match.group(1))

    return cls('', desc)

  @classmethod
  def from_checkout(cls, lines, include_skipped=True):
    """Create a State object from 'svn checkout' lines."""

    if include_skipped:
      re_extra = _re_parse_co_skipped
    else:
      re_extra = _re_parse_co_restored

    desc = { }
    for line in lines:
      if line.startswith('DBG:'):
        continue

      match = _re_parse_checkout.search(line)
      if match:
        if match.group(3) == 'C':
          treeconflict = 'C'
        else:
          treeconflict = None
        desc[to_relpath(match.group(4))] = StateItem(status=match.group(1),
                                                     treeconflict=treeconflict)
      else:
        match = re_extra.search(line)
        if match:
          desc[to_relpath(match.group(2))] = StateItem(verb=match.group(1))

    return cls('', desc)

  @classmethod
  def from_commit(cls, lines):
    """Create a State object from 'svn commit' lines."""

    desc = { }
    for line in lines:
      if line.startswith('DBG:') or line.startswith('Transmitting'):
        continue

      match = _re_parse_commit.search(line)
      if match:
        desc[to_relpath(match.group(3))] = StateItem(verb=match.group(1))

    return cls('', desc)

  @classmethod
  def from_wc(cls, base, load_props=False, ignore_svn=True):
    """Create a State object from a working copy.

    Walks the tree at PATH, building a State based on the actual files
    and directories found. If LOAD_PROPS is True, then the properties
    will be loaded for all nodes (Very Expensive!). If IGNORE_SVN is
    True, then the .svn subdirectories will be excluded from the State.
    """
    if not base:
      # we're going to walk the base, and the OS wants "."
      base = '.'

    desc = { }
    dot_svn = svntest.main.get_admin_name()

    for dirpath, dirs, files in os.walk(base):
      parent = path_to_key(dirpath, base)
      if ignore_svn and dot_svn in dirs:
        dirs.remove(dot_svn)
      for name in dirs + files:
        node = os.path.join(dirpath, name)
        if os.path.isfile(node):
          contents = open(node, 'r').read()
        else:
          contents = None
        desc[repos_join(parent, name)] = StateItem(contents=contents)

    if load_props:
      paths = [os.path.join(base, to_ospath(p)) for p in desc.keys()]
      paths.append(base)
      all_props = svntest.tree.get_props(paths)
      for node, props in all_props.items():
        if node == base:
          desc['.'] = StateItem(props=props)
        else:
          if base == '.':
            # 'svn proplist' strips './' from the paths. put it back on.
            node = os.path.join('.', node)
          desc[path_to_key(node, base)].props = props

    return cls('', desc)

  @classmethod
  def from_entries(cls, base):
    """Create a State object from a working copy, via the old "entries" API.

    Walks the tree at PATH, building a State based on the information
    provided by the old entries API, as accessed via the 'entries-dump'
    program.
    """
    if not base:
      # we're going to walk the base, and the OS wants "."
      base = '.'

    if os.path.isfile(base):
      # a few tests run status on a single file. quick-and-dirty this. we
      # really should analyze the entry (similar to below) to be general.
      dirpath, basename = os.path.split(base)
      entries = svntest.main.run_entriesdump(dirpath)
      return cls('', {
          to_relpath(base): StateItem.from_entry(entries[basename]),
          })

    desc = { }
    dot_svn = svntest.main.get_admin_name()

    for dirpath, dirs, files in os.walk(base):
      if dot_svn in dirs:
        # don't visit the .svn subdir
        dirs.remove(dot_svn)
      else:
        # this is not a versioned directory. remove all subdirectories since
        # we don't want to visit them. then skip this directory.
        dirs[:] = []
        continue

      entries = svntest.main.run_entriesdump(dirpath)

      if dirpath == '.':
        parent = ''
      elif dirpath.startswith('.' + os.sep):
        parent = to_relpath(dirpath[2:])
      else:
        parent = to_relpath(dirpath)

      parent_url = entries[''].url

      for name, entry in entries.items():
        # if the entry is marked as DELETED *and* it is something other than
        # schedule-add, then skip it. we can add a new node "over" where a
        # DELETED node lives.
        if entry.deleted and entry.schedule != 1:
          continue
        if name and entry.kind == 2:
          # stub subdirectory. leave a "missing" StateItem in here. note
          # that we can't put the status as "! " because that gets tweaked
          # out of our expected tree.
          item = StateItem(status='  ', wc_rev='?')
          desc[repos_join(parent, name)] = item
          continue
        item = StateItem.from_entry(entry)
        if name:
          desc[repos_join(parent, name)] = item
          implied_url = repos_join(parent_url, svn_url_quote(name))
        else:
          item._url = entry.url  # attach URL to directory StateItems
          desc[parent] = item

          grandpa, this_name = repos_split(parent)
          if grandpa in desc:
            implied_url = repos_join(desc[grandpa]._url,
                                     svn_url_quote(this_name))
          else:
            implied_url = None

        if implied_url and implied_url != entry.url:
          item.switched = 'S'

      # only recurse into directories found in this entries. remove any
      # which are not mentioned.
      unmentioned = set(dirs) - set(entries.keys())
      for subdir in unmentioned:
        dirs.remove(subdir)

    return cls('', desc)


class StateItem:
  """Describes an individual item within a working copy.

  Note that the location of this item is not specified. An external
  mechanism, such as the State class, will provide location information
  for each item.
  """

  def __init__(self, contents=None, props=None,
               status=None, verb=None, wc_rev=None, entry_rev=None,
               locked=None, copied=None, switched=None, writelocked=None,
               treeconflict=None):
    # provide an empty prop dict if it wasn't provided
    if props is None:
      props = { }

    ### keep/make these ints one day?
    if wc_rev is not None:
      wc_rev = str(wc_rev)

    # Any attribute can be None if not relevant, unless otherwise stated.

    # A string of content (if the node is a file).
    self.contents = contents
    # A dictionary mapping prop name to prop value; never None.
    self.props = props
    # A two-character string from the first two columns of 'svn status'.
    self.status = status
    # The action word such as 'Adding' printed by commands like 'svn update'.
    self.verb = verb
    # The base revision number of the node in the WC, as a string.
    self.wc_rev = wc_rev
    # This one will be set when we expect the wc_rev to differ from the one
    # found ni the entries code.
    self.entry_rev = entry_rev
    # For the following attributes, the value is the status character of that
    # field from 'svn status', except using value None instead of status ' '.
    self.locked = locked
    self.copied = copied
    self.switched = switched
    self.writelocked = writelocked
    # Value 'C' or ' ', or None as an expected status meaning 'do not check'.
    self.treeconflict = treeconflict

  def copy(self):
    "Make a deep copy of self."
    new = StateItem()
    vars(new).update(vars(self))
    new.props = self.props.copy()
    return new

  def tweak(self, **kw):
    for name, value in kw.items():
      # Refine the revision args (for now) to ensure they are strings.
      if value is not None and name == 'wc_rev':
        value = str(value)
      setattr(self, name, value)

  def __eq__(self, other):
    if not isinstance(other, StateItem):
      return False
    v_self = dict([(k, v) for k, v in vars(self).items()
                   if not k.startswith('_')])
    v_other = dict([(k, v) for k, v in vars(other).items()
                    if not k.startswith('_')])
    if self.treeconflict is None:
      v_other = v_other.copy()
      v_other['treeconflict'] = None
    if other.treeconflict is None:
      v_self = v_self.copy()
      v_self['treeconflict'] = None
    return v_self == v_other

  def __ne__(self, other):
    return not self.__eq__(other)

  def as_node_tuple(self, path):
    atts = { }
    if self.status is not None:
      atts['status'] = self.status
    if self.verb is not None:
      atts['verb'] = self.verb
    if self.wc_rev is not None:
      atts['wc_rev'] = self.wc_rev
    if self.locked is not None:
      atts['locked'] = self.locked
    if self.copied is not None:
      atts['copied'] = self.copied
    if self.switched is not None:
      atts['switched'] = self.switched
    if self.writelocked is not None:
      atts['writelocked'] = self.writelocked
    if self.treeconflict is not None:
      atts['treeconflict'] = self.treeconflict

    return (os.path.normpath(path), self.contents, self.props, atts)

  @classmethod
  def from_entry(cls, entry):
    status = '  '
    if entry.schedule == 1:  # svn_wc_schedule_add
      status = 'A '
    elif entry.schedule == 2:  # svn_wc_schedule_delete
      status = 'D '
    elif entry.schedule == 3:  # svn_wc_schedule_replace
      status = 'R '
    elif entry.conflict_old:
      ### I'm assuming we only need to check one, rather than all conflict_*
      status = 'C '

    ### is this the sufficient? guessing here w/o investigation.
    if entry.prejfile:
      status = status[0] + 'C'

    if entry.locked:
      locked = 'L'
    else:
      locked = None

    if entry.copied:
      wc_rev = '-'
      copied = '+'
    else:
      if entry.revision == -1:
        wc_rev = '?'
      else:
        wc_rev = entry.revision
      copied = None

    ### figure out switched
    switched = None

    if entry.lock_token:
      writelocked = 'K'
    else:
      writelocked = None

    return cls(status=status,
               wc_rev=wc_rev,
               locked=locked,
               copied=copied,
               switched=switched,
               writelocked=writelocked,
               )


if os.sep == '/':
  to_relpath = to_ospath = lambda path: path
else:
  def to_relpath(path):
    """Return PATH but with all native path separators changed to '/'."""
    return path.replace(os.sep, '/')
  def to_ospath(path):
    """Return PATH but with each '/' changed to the native path separator."""
    return path.replace('/', os.sep)


def path_to_key(path, base):
  """Return the relative path that represents the absolute path PATH under
  the absolute path BASE.  PATH must be a path under BASE.  The returned
  path has '/' separators."""
  if path == base:
    return ''

  if base.endswith(os.sep) or base.endswith('/') or base.endswith(':'):
    # Special path format on Windows:
    #  'C:/' Is a valid root which includes its separator ('C:/file')
    #  'C:'  is a valid root which isn't followed by a separator ('C:file')
    #
    # In this case, we don't need a separator between the base and the path.
    pass
  else:
    # Account for a separator between the base and the relpath we're creating
    base += os.sep

  assert path.startswith(base), "'%s' is not a prefix of '%s'" % (base, path)
  return to_relpath(path[len(base):])


def repos_split(repos_relpath):
  """Split a repos path into its directory and basename parts."""
  idx = repos_relpath.rfind('/')
  if idx == -1:
    return '', repos_relpath
  return repos_relpath[:idx], repos_relpath[idx+1:]


def repos_join(base, path):
  """Join two repos paths. This generally works for URLs too."""
  if base == '':
    return path
  if path == '':
    return base
  return base + '/' + path


def svn_url_quote(url):
  # svn defines a different set of "safe" characters than Python does, so
  # we need to avoid escaping them. see subr/path.c:uri_char_validity[]
  return urllib.quote(url, "!$&'()*+,-./:=@_~")


# ------------

def text_base_path(file_path):
  """Return the path to the text-base file for the versioned file
     FILE_PATH."""
  dot_svn = svntest.main.get_admin_name()
  return os.path.join(os.path.dirname(file_path), dot_svn, 'text-base',
                      os.path.basename(file_path) + '.svn-base')


# ------------
### probably toss these at some point. or major rework. or something.
### just bootstrapping some changes for now.
#

def item_to_node(path, item):
  tree = svntest.tree.build_generic_tree([item.as_node_tuple(path)])
  while tree.children:
    assert len(tree.children) == 1
    tree = tree.children[0]
  return tree

### yanked from tree.compare_trees()
def display_nodes(label, path, expected, actual):
  'Display two nodes, expected and actual.'
  expected = item_to_node(path, expected)
  actual = item_to_node(path, actual)
  print("=============================================================")
  print("Expected '%s' and actual '%s' in %s tree are different!"
        % (expected.name, actual.name, label))
  print("=============================================================")
  print("EXPECTED NODE TO BE:")
  print("=============================================================")
  expected.pprint()
  print("=============================================================")
  print("ACTUAL NODE FOUND:")
  print("=============================================================")
  actual.pprint()

### yanked from tree.py
def default_singleton_handler(description, path, item):
  node = item_to_node(path, item)
  print("Couldn't find node '%s' in %s tree" % (node.name, description))
  node.pprint()
  raise svntest.tree.SVNTreeUnequal