-
Notifications
You must be signed in to change notification settings - Fork 1
/
workingtree.py
1990 lines (1765 loc) · 73.3 KB
/
workingtree.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (C) 2005-2009 Jelmer Vernooij <[email protected]>
# 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
"""Checkouts and working trees (working copies)."""
from __future__ import absolute_import
from bisect import bisect_left
from collections import (
defaultdict,
deque,
)
import errno
import os
import operator
import posixpath
from six import string_types
import stat
import subvertpy
from subvertpy import (
ERR_BAD_FILENAME,
ERR_WC_UNSUPPORTED_FORMAT,
ERR_WC_NODE_KIND_CHANGE,
properties,
)
from subvertpy.ra import (
DEPTH_INFINITY,
)
from subvertpy.wc import (
SCHEDULE_ADD,
SCHEDULE_DELETE,
SCHEDULE_NORMAL,
SCHEDULE_REPLACE,
CommittedQueue,
Adm,
cleanup,
get_adm_dir,
is_adm_dir,
match_ignore_list,
revision_status,
)
import breezy.add
from breezy import (
conflicts as _mod_conflicts,
errors as bzr_errors,
hashcache,
location as _mod_location,
osutils,
rio as _mod_rio,
transport as _mod_transport,
urlutils,
)
from breezy.branch import BranchWriteLockResult
from breezy.errors import (
BadFilenameEncoding,
BzrError,
MergeModifiedFormatError,
NotBranchError,
NoSuchFile,
NoSuchId,
NoSuchRevision,
NoRepositoryPresent,
NoWorkingTree,
ReadOnlyError,
TokenLockingNotSupported,
TransportNotPossible,
UnsupportedFormatError,
UnsupportedOperation,
UninitializableFormat,
)
from breezy.lock import (
LogicalLockResult,
)
from breezy.lockable_files import (
TransportLock,
)
from breezy.revision import (
CURRENT_REVISION,
NULL_REVISION,
)
from six import (
text_type,
)
from breezy.trace import (
mutter,
note,
)
from breezy.bzr.workingtree import (
MERGE_MODIFIED_HEADER_1,
)
from breezy.workingtree import (
WorkingTree,
WorkingTreeFormat,
)
from . import (
SvnWorkingTreeProber,
svk,
)
from .commit import (
_revision_id_to_svk_feature,
)
from .errors import (
convert_svn_error,
NotSvnBranchPath,
NoSvnRepositoryPresent,
)
from .mapping import (
escape_svn_path,
)
from .transport import (
SvnRaTransport,
svn_config,
)
from .tree import (
BasisTreeIncomplete,
SvnBasisTree,
SubversionTree,
SubversionTreeDirectory,
SubversionTreeLink,
SubversionTreeFile,
)
from breezy.controldir import Converter
from breezy.controldir import (
ControlDirFormat,
ControlDir,
)
class RepositoryRootUnknown(BzrError):
_fmt = ("The working tree does not store the root of the Subversion "
"repository.")
class LocalRepositoryOpenFailed(BzrError):
_fmt = ("Unable to open local repository at %(url)s")
def __init__(self, url):
self.url = url
class CorruptWorkingTree(BzrError):
_fmt = ("Unable to open working tree at %(path)s: %(msg)s")
def __init__(self, path, msg):
self.path = path
self.msg = msg
def update_wc(adm, basedir, conn, url, revnum):
# FIXME: honor SVN_CONFIG_SECTION_HELPERS:SVN_CONFIG_OPTION_DIFF3_CMD
# FIXME: honor SVN_CONFIG_SECTION_MISCELLANY:SVN_CONFIG_OPTION_USE_COMMIT_TIMES
# FIXME: honor SVN_CONFIG_SECTION_MISCELLANY:SVN_CONFIG_OPTION_PRESERVED_CF_EXTS
print(basedir)
editor = adm.get_switch_editor(
"", url, use_commit_times=False,
depth=DEPTH_INFINITY, notify_func=None, diff3_cmd=None,
depth_is_sticky=False, allow_unver_obstructions=True)
reporter = conn.do_switch(revnum, "", True, url, editor)
try:
adm.crawl_revisions(basedir, reporter, restore_files=False,
recurse=True, use_commit_times=True)
except subvertpy.SubversionException as e:
msg, num = e.args
if num == subvertpy.ERR_RA_ILLEGAL_URL:
raise BzrError(msg)
raise
# FIXME: handle externals
def apply_prop_changes(orig_props, prop_changes):
"""Apply a set of property changes to a properties dictionary.
:param orig_props: Dictionary with original properties (will be modified)
:param prop_changes: Dictionary of new property values (None for deletion)
:return: New dictionary
"""
for k,v in prop_changes:
if v is None:
del orig_props[k]
else:
orig_props[k] = v
return orig_props
class Walker(object):
"""Iterator of a Subversion working copy.
This follows the Tree.iter_entries_by_dir order:
* Parents before children
* Ordered by name
"""
def __init__(self, workingtree, start=u"", recursive=True):
"""Create a new walker.
:param workingtree: bzr-svn working tree to walk over
:param start: Start path, relative to tree root
:param recursive: Whether to be recursive
"""
self.workingtree = workingtree
self.todo = list([start])
self.pending = deque()
self.recursive = recursive
def __iter__(self):
return iter(self.__next__, None)
def __next__(self):
while not self.pending:
try:
p = self.todo.pop()
except IndexError:
return None
try:
wc = self.workingtree._get_wc(p)
except subvertpy.SubversionException as e:
msg, num = e.args
if num == subvertpy.ERR_WC_NOT_DIRECTORY:
continue
raise
try:
entries = wc.entries_read(True)
for name in sorted(entries):
entry = entries[name]
if isinstance(name, bytes):
name = name.decode('utf-8')
subp = osutils.pathjoin(p, name).rstrip("/")
if entry.kind == subvertpy.NODE_DIR and name != "":
if self.recursive:
self.todo.append(subp)
if name != '' or subp == '':
self.pending.append((subp, entry))
finally:
wc.close()
return self.pending.popleft()
class SvnWorkingTree(SubversionTree, WorkingTree):
"""WorkingTree implementation that uses a svn working copy for storage."""
def __init__(self, controldir, format, local_path, entry):
self._reset_data()
if not isinstance(local_path, text_type):
raise TypeError(local_path)
self.entry = entry
self.basedir = local_path
self._format = format
self.controldir = controldir
self._branch = None
self._cached_base_tree = None
self._detect_case_handling()
self.bzr_controldir = os.path.join(controldir.local_path, controldir._adm_dir, 'bzr')
try:
os.makedirs(self.bzr_controldir)
os.makedirs(os.path.join(self.bzr_controldir, 'lock'))
except OSError:
pass
control_transport = controldir.transport.clone('bzr')
self._transport = control_transport
cache_filename = control_transport.local_abspath('stat-cache')
self._hashcache = hashcache.HashCache(self.basedir, cache_filename,
self.controldir._get_file_mode(),
self._content_filter_stack_provider())
self._hashcache.read()
self._lock_count = 0
self._lock_mode = None
self._control_files = None
self.views = self._make_views()
def _cleanup(self):
pass
@property
def mapping(self):
"""bzr-svn mapping to use."""
return self.branch.mapping
def stored_kind(self, path, file_id=None):
assert path is not None
try:
return self.basis_tree().kind(path, file_id)
except NoSuchFile:
return None
def kind(self, path, file_id=None):
abspath = self.abspath(path)
try:
return osutils.file_kind(abspath)
except NoSuchFile:
return None
def _detect_case_handling(self):
try:
self.controldir.transport.stat("FoRmAt")
except NoSuchFile:
self.case_sensitive = True
else:
self.case_sensitive = False
def _set_root_id(self, file_id):
self._change_fileid_mapping(file_id, u"")
def get_file_mtime(self, path, file_id=None):
"""See Tree.get_file_mtime."""
try:
return os.lstat(self.abspath(path)).st_mtime
except EnvironmentError as e:
if e.errno == errno.ENOENT:
raise NoSuchFile(path=path)
raise
def _setup_directory_is_tree_reference(self):
self._directory_is_tree_reference = self._directory_is_never_tree_reference
def get_file_sha1(self, path, file_id=None, stat_value=None):
return self._hashcache.get_sha1(path, stat_value)
@property
def basis_idmap(self):
if self._cached_base_idmap is not None:
return self._cached_base_idmap
idmap = self.branch.repository.get_fileid_map(
self._get_base_revmeta(),
self.mapping)
if self.is_locked():
self._cached_base_idmap = idmap
return idmap
def get_branch_path(self, revnum=None):
if revnum is None:
try:
return self.controldir.get_branch_path()
except RepositoryRootUnknown:
pass
return self.branch.get_branch_path(revnum)
@property
def branch(self):
if self._branch is None:
self._branch = self.controldir.open_branch(revnum=self.base_revnum)
return self._branch
def __repr__(self):
return "<%s of %s>" % (self.__class__.__name__, self.basedir.encode('utf-8'))
def conflicts(self):
# FIXME: Retrieve conflicts
return _mod_conflicts.ConflictList()
def get_ignore_list(self):
"""Obtain the list of ignore patterns for this working tree.
:note: Will interpret the svn:ignore properties, rather than read
.bzrignore
"""
ignores = set([get_adm_dir()])
ignores.update(svn_config.get_default_ignores())
def dir_add(wc, prefix, patprefix):
if not isinstance(prefix, text_type):
raise TypeError(prefix)
if not isinstance(patprefix, bytes):
raise TypeError(patprefix)
ignorestr = wc.prop_get(properties.PROP_IGNORE,
self.abspath(prefix).rstrip("/").encode("utf-8"))
if ignorestr is not None:
for pat in ignorestr.splitlines():
ignores.add(urlutils.joinpath(patprefix, pat))
entries = wc.entries_read(False)
for entry in entries:
if entry == "":
continue
# Ignore ignores on things that aren't directories
if entries[entry].kind != subvertpy.NODE_DIR:
continue
subprefix = osutils.pathjoin(prefix, entry.decode("utf-8"))
try:
subwc = self._get_wc(subprefix, base=wc)
except subvertpy.SubversionException as e:
msg, num = e.args
if num == subvertpy.ERR_WC_NOT_DIRECTORY:
continue
raise
try:
dir_add(subwc, subprefix, urlutils.joinpath(patprefix,
entry))
finally:
subwc.close()
with self._get_wc() as wc:
dir_add(wc, u"", ".")
return ignores
def is_ignored(self, path):
dirname = os.path.dirname(path)
with self._get_wc(relpath=dirname) as wc:
ignores = svn_config.get_default_ignores()
ignorestr = wc.prop_get(properties.PROP_IGNORE,
self.abspath(dirname))
if ignorestr is not None:
ignores.extend(ignorestr.splitlines())
return match_ignore_list(os.path.basename(path), ignores)
def flush(self):
pass
def is_control_filename(self, path):
"""Check whether path is a control file (used by bzr or svn)."""
return is_adm_dir(path)
def _update(self, branch_path, revnum, show_base):
if revnum is None:
# FIXME: should be able to use -1 here
revnum = self.branch.get_revnum()
old_branch_path = self.get_branch_path()
with self._get_wc(write_lock=True, depth=-1) as adm:
conn = self.branch.repository.svn_transport.get_connection(old_branch_path)
try:
update_wc(adm, self.basedir.encode("utf-8"), conn,
urlutils.join(self.branch.repository.svn_transport.svn_url, branch_path),
revnum)
finally:
self.branch.repository.svn_transport.add_connection(conn)
return revnum
def update(self, change_reporter=None, possible_transports=None,
revision=None, old_tip=None, show_base=False, revnum=None):
"""Update the workingtree to a new Bazaar revision number.
"""
orig_revnum = self.base_revnum
if revision is not None and revnum is not None:
raise AssertionError("revision and revnum are mutually exclusive")
if revision is not None:
((uuid, branch_path, revnum), mapping) = self.branch.lookup_bzr_revision_id(revision)
else:
branch_path = self.branch.get_branch_path()
self._cached_base_revnum = self._update(branch_path, revnum,
show_base=show_base)
self._cached_base_revid = None
self._cached_base_idmap = None
return self.base_revnum - orig_revnum
def remove(self, files, verbose=False, to_file=None, keep_files=True,
force=False):
"""Remove files from the working tree."""
if not isinstance(files, list):
files = [files]
# FIXME: Use to_file argument
# FIXME: Use verbose argument
assert isinstance(files, list)
with self._get_wc(write_lock=True) as wc:
for file in files:
try:
wc.delete(osutils.safe_utf8(self.abspath(file)),
keep_local=keep_files)
except subvertpy.SubversionException as e:
msg, num = e.args
if num == ERR_BAD_FILENAME:
note("%s does not exist." % file)
else:
raise
for file in files:
self._change_fileid_mapping(None, file)
def unversion(self, paths, file_ids=None):
with self._get_wc(write_lock=True) as wc:
for path in paths:
wc.delete(osutils.safe_utf8(self.abspath(path)),
keep_local=True)
def all_versioned_paths(self):
ret = set()
w = Walker(self)
for path, entry in w:
ret.add(path)
return ret
def all_file_ids(self):
"""See Tree.all_file_ids"""
ret = set()
w = Walker(self)
for path, entry in w:
try:
ret.add(self.lookup_id(path)[0])
except KeyError:
pass
return ret
@convert_svn_error
def _get_wc(self, relpath=u"", write_lock=False, depth=0, base=None):
"""Open a working copy handle."""
return Adm(base,
self.abspath(relpath).rstrip("/"),
write_lock, depth)
def _get_rel_wc(self, relpath, write_lock=False):
if not isinstance(relpath, text_type):
raise TypeError(relpath)
dir = os.path.dirname(relpath)
file = os.path.basename(relpath)
return (self._get_wc(dir, write_lock), file)
def _rename_fileid(self, old_path, new_path, wc=None):
self._change_fileid_mapping(self.path2id(old_path), new_path, wc)
self._change_fileid_mapping(None, old_path, wc)
if not os.path.isdir(self.abspath(old_path)):
return
for from_subpath, entry in Walker(self, old_path):
from_subpath = from_subpath.strip("/")
to_subpath = osutils.pathjoin(new_path,
from_subpath[len(old_path):].strip("/"))
self._change_fileid_mapping(self.path2id(from_subpath), to_subpath,
wc)
self._change_fileid_mapping(None, from_subpath, wc)
def move(self, from_paths, to_dir=None, after=False, **kwargs):
"""Move files to a new location."""
# FIXME: Use after argument
if after:
raise NotImplementedError("move after not supported")
for from_path in from_paths:
from_abspath = osutils.safe_utf8(self.abspath(from_path))
new_path = osutils.pathjoin(
osutils.safe_utf8(to_dir),
osutils.safe_utf8(os.path.basename(from_path)))
self._rename_fileid(from_path, new_path)
with self._get_wc(osutils.safe_unicode(to_dir), write_lock=True) as to_wc:
to_wc.copy(from_abspath,
osutils.safe_utf8(os.path.basename(from_path)))
with self._get_wc(write_lock=True) as from_wc:
from_wc.delete(from_abspath)
def rename_one(self, from_rel, to_rel, after=False):
from_rel = osutils.safe_unicode(from_rel)
to_rel = osutils.safe_unicode(to_rel)
# FIXME: Use after
if after:
raise NotImplementedError("rename_one after not supported")
from_wc = None
self._rename_fileid(from_rel, to_rel)
(to_wc, to_file) = self._get_rel_wc(to_rel, write_lock=True)
try:
if os.path.dirname(from_rel) == os.path.dirname(to_rel):
# Prevent lock contention
from_wc = to_wc
else:
(from_wc, _) = self._get_rel_wc(from_rel, write_lock=True)
try:
to_wc.copy(self.abspath(from_rel), to_file)
from_wc.delete(self.abspath(from_rel))
finally:
from_wc.close()
finally:
if from_wc != to_wc:
to_wc.close()
def path_to_file_id(self, revnum, current_revnum, path):
"""Generate a bzr file id from a Subversion file name.
:param revnum: Revision number.
:param path: Path of the file
:return: Tuple with file id and revision id.
"""
if not isinstance(path, text_type):
raise TypeError(path)
path = osutils.normpath(path)
if path == u".":
path = u""
return self.lookup_id(path)
def _find_ids(self, relpath, entry):
if not isinstance(relpath, text_type):
raise TypeError(relpath)
assert entry.schedule in (SCHEDULE_NORMAL,
SCHEDULE_DELETE,
SCHEDULE_ADD,
SCHEDULE_REPLACE)
if entry.schedule == SCHEDULE_NORMAL:
# Keep old id
try:
return self.path_to_file_id(
entry.cmt_rev, entry.revision, relpath)
except KeyError:
if entry.revision == self._cached_base_revnum:
raise AssertionError(
"file %s:%d not in fileid map for %d" % (
relpath, entry.revision, self._cached_base_revnum))
# For some reason a file that doesn't exist in the current
# revision has ended up here. Let's just generate a NEW- file
# id
elif entry.schedule == SCHEDULE_DELETE:
return (None, None)
elif (entry.schedule == SCHEDULE_ADD or
entry.schedule == SCHEDULE_REPLACE):
ids = self._get_new_file_ids()
if relpath in ids:
return (ids[relpath], None)
else:
raise AssertionError("unknown schedule value %r for %s" % (
entry.schedule, relpath))
# FIXME: Generate more random but consistent file ids
return (
b"NEW-" + escape_svn_path(relpath.strip("/")),
None)
def path2id(self, path):
if isinstance(path, list):
path = "/".join(path)
with self._get_wc() as wc:
try:
entry = self._get_entry(wc, path)
(file_id, revision) = self._find_ids(
osutils.safe_unicode(path), entry)
except KeyError:
return None
else:
if not isinstance(file_id, bytes):
raise TypeError(file_id)
return file_id
def _get_entry(self, wc, path):
path = osutils.safe_utf8(self.abspath(path))
related_wc = wc.probe_try(path)
if related_wc is None:
raise KeyError
try:
return related_wc.entry(path)
finally:
related_wc.close()
def filter_unversioned_files(self, paths):
ret = set()
with self._get_wc() as wc:
for p in paths:
try:
entry = self._get_entry(wc, p)
except KeyError:
ret.add(p)
else:
if entry.schedule == SCHEDULE_DELETE:
ret.add(p)
return ret
def id2path(self, file_id):
ids = self._get_new_file_ids()
for path, fid in ids.items():
if file_id == fid:
return path
try:
return self.basis_idmap.reverse_lookup(self.mapping, file_id)
except KeyError:
pass
if file_id.startswith("NEW-"):
return urlutils.unescape(file_id[4:])
if file_id == self.path2id(''):
# Special case if self.last_revision() == 'null:'
return ""
raise NoSuchId(self, file_id)
def _ie_from_entry(self, relpath, entry, parent_id):
assert type(parent_id) is bytes or parent_id is None
if not isinstance(relpath, text_type):
raise TypeError(relpath)
(file_id, revid) = self._find_ids(relpath, entry)
abspath = self.abspath(relpath)
basename = os.path.basename(relpath)
if entry.kind == subvertpy.NODE_DIR:
ie = SubversionTreeDirectory(file_id, basename, parent_id)
ie.revision = revid
return ie
elif os.path.islink(abspath):
ie = SubversionTreeLink(file_id, basename, parent_id)
ie.revision = revid
target_path = os.readlink(abspath.encode(osutils._fs_enc))
ie.symlink_target = target_path.decode(osutils._fs_enc)
return ie
else:
ie = SubversionTreeFile(file_id, basename, parent_id)
ie.revision = revid
try:
data = osutils.fingerprint_file(
open(abspath.encode(osutils._fs_enc), 'rb'))
except IOError as e:
if e.errno == errno.EISDIR:
ie = SubversionTreeDirectory(file_id, basename, parent_id)
ie.revision = None
return ie
elif e.errno == errno.ENOENT:
return None
raise
else:
ie.text_sha1 = data['sha1']
ie.text_size = data['size']
ie.executable = self.is_executable(relpath)
return ie
def iter_child_entries(self, path, file_id=None):
"""See Tree.iter_child_entries."""
entry = next(self.iter_entries_by_dir(specific_files=[path]))[1]
return getattr(entry, 'children', {}).values()
def iter_entries_by_dir(self, specific_files=None):
"""See WorkingTree.iter_entries_by_dir."""
if specific_files is not None:
with self._get_wc() as wc:
for path in specific_files:
parent = os.path.dirname(path)
parent_id = self.lookup_id(parent)
try:
entry = self._get_entry(wc, path)
except KeyError:
raise NoSuchFile(path, self)
if entry.schedule == SCHEDULE_DELETE:
continue
if not isinstance(path, text_type):
path = path.decode('utf-8')
ie = self._ie_from_entry(path, entry, parent_id[0])
if ie is not None:
yield path, ie
else:
fileids = {}
w = Walker(self)
for relpath, entry in w:
if entry.schedule == SCHEDULE_DELETE:
continue
if not isinstance(relpath, text_type):
raise TypeError(relpath)
if relpath == u"":
parent_id = None
else:
parent_id = fileids[os.path.dirname(relpath)]
ie = self._ie_from_entry(relpath, entry, parent_id)
if ie is not None:
fileids[relpath] = ie.file_id
yield relpath, ie
def extras(self):
"""See WorkingTree.extras."""
w = Walker(self)
versioned_files = set()
all_files = set()
for path, dir_entry in w:
versioned_files.add(path)
dirabs = self.abspath(path)
if not osutils.isdir(dirabs):
# e.g. directory deleted
continue
for subf in os.listdir(dirabs):
if self.controldir.is_control_filename(subf):
continue
try:
(subf_norm, can_access) = osutils.normalized_filename(subf)
except UnicodeDecodeError:
path_os_enc = path.encode(osutils._fs_enc)
relpath = path_os_enc + '/' + subf
raise BadFilenameEncoding(relpath, osutils._fs_enc)
subp = os.path.join(path, subf_norm)
all_files.add(subp)
return iter(all_files - versioned_files)
def set_last_revision(self, revid):
mutter('setting last revision to %r', revid)
if revid == NULL_REVISION:
# If there is a hidden revision at the beginning of the branch,
# use that as the NULL revision.
foreign_revid = None
for revmeta, hidden, mapping in self.branch._iter_revision_meta_ancestry():
if hidden:
foreign_revid = revmeta.metarev.get_foreign_revid()
else:
foreign_revid = None
if foreign_revid is None:
raise NotImplementedError("unable to set NULL_REVISION if there is "
"no hidden initial revision")
self._cached_base_revnum = foreign_revid[2]
self._cached_base_idmap = None
else:
(foreign_revid, mapping) = self.branch.lookup_bzr_revision_id(revid)
self._cached_base_revnum = foreign_revid[2]
self._cached_base_idmap = None
# FIXME: set any items that are no longer versioned to SCHEDULE_ADD,
# but remove their versioning information
self._cached_base_revid = revid
def set_parent_trees(self, parents_list, allow_leftmost_as_ghost=False):
"""See MutableTree.set_parent_trees."""
self.set_parent_ids([rev for (rev, tree) in parents_list])
def get_parent_ids(self):
"""See Tree.get_parent_ids.
This implementation reads the pending merges list and last_revision
value and uses that to decide what the parents list should be.
"""
last_rev = self._last_revision()
if NULL_REVISION == last_rev:
parents = []
else:
parents = [last_rev]
if not self._cached_merges:
try:
merges_bytes = self._transport.get_bytes('pending-merges')
except NoSuchFile:
merges = []
else:
merges = []
for l in osutils.split_lines(merges_bytes):
revision_id = l.rstrip('\n')
merges.append(revision_id)
if self.is_locked():
self._cached_merges = merges
else:
merges = self._cached_merges
parents.extend(merges)
return parents
def set_parent_ids(self, parent_ids, allow_leftmost_as_ghost=False):
"""See MutableTree.set_parent_ids."""
if parent_ids == []:
merges = []
self.set_last_revision(NULL_REVISION)
else:
merges = parent_ids[1:]
self.set_last_revision(parent_ids[0])
if self.is_locked():
self._cached_merges = merges
self._transport.put_bytes('pending-merges', '\n'.join(merges),
mode=self.controldir._get_file_mode())
with self._get_wc(write_lock=True) as adm:
old_svk_merges = svk.parse_svk_features(self._get_svk_merges(
self._get_base_branch_props()))
svk_merges = set(old_svk_merges)
# Set svk:merge
for merge in merges:
try:
svk_merges.add(_revision_id_to_svk_feature(merge,
self.branch.repository.lookup_bzr_revision_id))
except NoSuchRevision:
pass
if old_svk_merges != svk_merges:
adm.prop_set(
svk.SVN_PROP_SVK_MERGE,
svk.serialize_svk_features(svk_merges),
self.basedir.encode("utf-8"))
def smart_add(self, file_list, recurse=True, action=None, save=True):
"""See MutableTree.smart_add()."""
assert isinstance(recurse, bool)
if action is None:
action = breezy.add.AddAction()
# TODO: use action
if not file_list:
# no paths supplied: add the entire tree.
file_list = [u'.']
ignored = defaultdict(list)
added = []
for file_path in file_list:
todo = []
file_path = os.path.abspath(osutils.safe_unicode(file_path))
f = self.relpath(file_path)
with self._get_wc(os.path.dirname(f.encode(osutils._fs_enc)).decode(osutils._fs_enc), write_lock=True) as wc:
if self.filter_unversioned_files([f]):
if save:
mutter('adding %r', file_path)
wc.add(file_path)
self._fix_special(wc, file_path, f)
added.append(file_path)
if (recurse and
osutils.file_kind(file_path.encode(osutils._fs_enc)) == 'directory'):
# Filter out ignored files and update ignored
for c in os.listdir(file_path.encode(osutils._fs_enc)):
if self.is_control_filename(c):
continue
c = c.decode(osutils._fs_enc)
c_path = osutils.pathjoin(file_path, c)
ignore_glob = self.is_ignored(c)
if ignore_glob is not None:
ignored[ignore_glob].append(c_path)
todo.append(c_path)
if todo != []:
cadded, cignored = self.smart_add(todo, recurse, action, save)
added.extend(cadded)
ignored.update(cignored)
return added, ignored
def _fix_special(self, adm, abspath, relpath, kind=None):
if kind is None:
kind = self.kind(relpath)
if kind == "file":
value = None
elif kind == "symlink":
value = properties.PROP_SPECIAL_VALUE
else:
return
adm.prop_set(properties.PROP_SPECIAL, value, abspath)
def _fix_kind(self, adm, abspath, relpath, entry):
kind = self.kind(relpath)
if ((entry.kind == subvertpy.NODE_DIR and kind in ('file', 'symlink')) or
(entry.kind == subvertpy.NODE_FILE and kind == 'directory')):
try:
adm.delete(abspath, keep_local=True)
adm.add(abspath)
except subvertpy.SubversionException as e:
msg, num = e.args
if num == ERR_WC_NODE_KIND_CHANGE:
if entry.kind == subvertpy.NODE_DIR:
from_kind = "directory"
else:
from_kind = "file or symlink"
raise bzr_errors.UnsupportedKindChange(relpath,
from_kind, kind, self._format)
raise
self._fix_special(adm, abspath, relpath, kind)
def add(self, files, ids=None, kinds=None, _copyfrom=None):
"""Add files to the working tree."""
# TODO: Use kinds
if isinstance(files, string_types):
files = [files]
if isinstance(ids, bytes):
ids = [ids]
if ids is None:
ids = [None] * len(files)
if _copyfrom is None:
_copyfrom = [(None, -1)] * len(files)
if kinds is None:
kinds = [self.kind(file) for file in files]
assert isinstance(files, list)
for f, kind, file_id, copyfrom in zip(files, kinds, ids, _copyfrom):
f = f.rstrip('/')
with self._get_wc(os.path.dirname(f), write_lock=True) as wc:
try:
abspath = self.abspath(f)
wc.add(abspath, copyfrom[0], copyfrom[1])
except subvertpy.SubversionException as e:
msg, num = e.args
if num in (subvertpy.ERR_ENTRY_EXISTS,
subvertpy.ERR_WC_SCHEDULE_CONFLICT):
continue
elif num == subvertpy.ERR_WC_PATH_NOT_FOUND:
raise NoSuchFile(path=f)
raise
self._fix_special(wc, abspath, f)
if file_id is not None:
self._change_fileid_mapping(file_id, f)
def basis_tree(self):
"""Return the basis tree for a working tree."""
try:
return SvnBasisTree(self)
except BasisTreeIncomplete:
return self.branch.basis_tree()
def list_files(self, include_root=False, from_dir=None, recursive=True):
"""See ``Tree.list_files``."""
# TODO: This doesn't sort the output
# TODO: This ignores unversioned files at the moment
if from_dir is None:
from_dir = u""
else:
from_dir = osutils.safe_unicode(from_dir)
w = Walker(self, from_dir, recursive=recursive)
fileids = {}
for path, entry in w:
relpath = path.decode("utf-8")
if entry.schedule in (SCHEDULE_NORMAL, SCHEDULE_ADD,
SCHEDULE_REPLACE):
versioned = 'V'
else:
versioned = '?'