/
tfs.py
1518 lines (1193 loc) · 48.7 KB
/
tfs.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
"""A client for Team Foundation Server."""
from __future__ import annotations
import argparse
import io
import logging
import os
import re
import sys
import tempfile
import xml.etree.ElementTree as ET
from typing import Any, Dict, List, Optional, cast
from urllib.parse import unquote
from housekeeping import deprecate_non_keyword_only_args
from rbtools.clients import BaseSCMClient, RepositoryInfo
from rbtools.clients.base.scmclient import (SCMClientDiffResult,
SCMClientRevisionSpec)
from rbtools.clients.errors import (InvalidRevisionSpecError,
SCMClientDependencyError,
SCMError,
TooManyRevisionsError)
from rbtools.deprecation import RemovedInRBTools50Warning
from rbtools.diffs.writers import UnifiedDiffWriter
from rbtools.utils.appdirs import user_data_dir
from rbtools.utils.checks import check_install
from rbtools.utils.diffs import filename_match_any_patterns
from rbtools.utils.filesystem import make_tempfile
from rbtools.utils.process import (RunProcessError,
RunProcessResult,
run_process)
class BaseTFWrapper:
"""Base class for TF wrappers.
Version Added:
4.0
"""
def __init__(
self,
*,
config: Optional[Dict[str, Any]] = None,
options: Optional[argparse.Namespace] = None,
) -> None:
"""Initialize the wrapper.
Args:
config (dict, optional):
The loaded configuration.
options (argparse.Namespace, optional):
The command line options.
"""
self.config = config
self.options = options
def check_dependencies(self) -> None:
"""Check whether all dependencies for the client are available.
By default, no dependencies are checked.
"""
pass
def get_local_path(self) -> Optional[str]:
"""Return the local path to the working tree.
Returns:
str:
The filesystem path of the repository on the client system.
"""
raise NotImplementedError
def get_repository_info(self) -> Optional[RepositoryInfo]:
"""Return repository information for the current working tree.
Returns:
rbtools.clients.base.repository.RepositoryInfo:
The repository info structure.
"""
raise NotImplementedError
def parse_revision_spec(
self,
revisions: List[str],
) -> SCMClientRevisionSpec:
"""Parse the given revision spec.
These will be used to generate the diffs to upload to Review Board
(or print). The diff for review will include the changes in (base,
tip], and the parent diff (if necessary) will include (parent,
base].
If a single revision is passed in, this will return the parent of
that revision for "base" and the passed-in revision for "tip".
If zero revisions are passed in, this will return revisions
relevant for the "current change" (changes in the work folder which
have not yet been checked in).
Args:
revisions (list of str):
A list of revisions as specified by the user.
Items in the list do not necessarily represent a single
revision, since the user can use the TFS-native syntax of
``r1~r2``. Versions passed in can be any versionspec, such as a
changeset number, ``L``-prefixed label name, ``W`` (latest
workspace version), or ``T`` (latest upstream version).
Returns:
dict:
The parsed revision spec.
See :py:class:`~rbtools.clients.base.scmclient.
SCMClientRevisionSpec` for the format of this dictionary.
This always populates ``base`` and ``tip``.
Raises:
rbtools.clients.errors.TooManyRevisionsError:
Too many revisions were specified.
rbtools.clients.errors.InvalidRevisionSpecError:
The given revision spec could not be parsed.
"""
raise NotImplementedError
def diff(
self,
*,
client: TFSClient,
revisions: SCMClientRevisionSpec,
include_files: List[str],
exclude_patterns: List[str],
) -> SCMClientDiffResult:
"""Return the generated diff.
Args:
client (TFSClient):
The client performing the diff.
revisions (dict):
A dictionary containing ``base`` and ``tip`` keys.
include_files (list):
A list of file paths to include in the diff.
exclude_patterns (list):
A list of file paths to exclude from the diff.
**kwargs (dict, unused):
Unused keyword arguments.
Returns:
dict:
A dictionary of diff results.
See :py:class:`~rbtools.clients.base.scmclient.SCMClientDiffResult`
for the format of this dictionary.
"""
raise NotImplementedError
class TFExeWrapper(BaseTFWrapper):
"""Implementation wrapper for using VS2017's tf.exe."""
REVISION_WORKING_COPY = '--rbtools-working-copy'
def check_dependencies(self) -> None:
"""Check whether all dependencies for the client are available.
This will check for ``tf.exe``.
Raises:
rbtools.clients.errors.SCMClientDependencyError:
A :command:`tf` tool could not be found.
"""
tf_vc_output: bytes
try:
tf_vc_output = (
run_process(['tf', 'vc', 'help'])
.stdout_bytes
.read()
)
except Exception:
tf_vc_output = b''
# VS2015 has a tf.exe but it's not good enough.
if (not tf_vc_output or
b'Version Control Tool, Version 15' not in tf_vc_output):
raise SCMClientDependencyError(missing_exes=['tf'])
def get_local_path(self) -> Optional[str]:
"""Return the local path to the working tree.
Returns:
str:
The filesystem path of the repository on the client system.
"""
workfold = (
self._run_tf(['vc', 'workfold', os.getcwd()])
.stdout
.read()
)
m = re.search('^Collection: (.*)$', workfold, re.MULTILINE)
if m:
return unquote(m.group(1))
logging.debug('Could not find the collection from "tf vc workfold"')
return None
def get_repository_info(self) -> Optional[RepositoryInfo]:
"""Return repository information for the current working tree.
Returns:
rbtools.clients.base.repository.RepositoryInfo:
The repository info structure.
"""
path = self.get_local_path()
if path:
return RepositoryInfo(path=path, local_path=path)
return None
def parse_revision_spec(
self,
revisions: List[str],
) -> SCMClientRevisionSpec:
"""Parse the given revision spec.
These will be used to generate the diffs to upload to Review Board
(or print). The diff for review will include the changes in (base,
tip], and the parent diff (if necessary) will include (parent,
base].
If a single revision is passed in, this will return the parent of
that revision for "base" and the passed-in revision for "tip".
If zero revisions are passed in, this will return revisions
relevant for the "current change" (changes in the work folder which
have not yet been checked in).
Versions passed in can be any versionspec, such as a changeset number,
``L``-prefixed label name, ``W`` (latest workspace version), or ``T``
(latest upstream version).
Args:
revisions (list of str):
A list of revisions as specified by the user.
Items in the list do not necessarily represent a single
revision, since the user can use the TFS-native syntax of
``r1~r2``. Versions passed in can be any versionspec, such as a
changeset number, ``L``-prefixed label name, ``W`` (latest
workspace version), or ``T`` (latest upstream version).
Returns:
dict:
The parsed revision spec.
See :py:class:`~rbtools.clients.base.scmclient.
SCMClientRevisionSpec` for the format of this dictionary.
This always populates ``base`` and ``tip``.
Raises:
rbtools.clients.errors.TooManyRevisionsError:
Too many revisions were specified.
rbtools.clients.errors.InvalidRevisionSpecError:
The given revision spec could not be parsed.
"""
n_revisions = len(revisions)
if n_revisions == 1 and '~' in revisions[0]:
revisions = revisions[0].split('~')
n_revisions = len(revisions)
if n_revisions == 0:
# Most recent checked-out revision -- working copy
return {
'base': str(self._convert_symbolic_revision('W')),
'tip': self.REVISION_WORKING_COPY,
}
elif n_revisions == 1:
# Either a numeric revision (n-1:n) or a changelist
revision = self._convert_symbolic_revision(revisions[0])
return {
'base': str(revision - 1),
'tip': str(revision),
}
elif n_revisions == 2:
# Diff between two numeric revisions
return {
'base': str(self._convert_symbolic_revision(revisions[0])),
'tip': str(self._convert_symbolic_revision(revisions[1])),
}
else:
raise TooManyRevisionsError
def _convert_symbolic_revision(
self,
revision: str,
path: Optional[str] = None,
) -> int:
"""Convert a symbolic revision into a numeric changeset.
Args:
revision (str):
The TFS versionspec to convert.
path (str, optional):
The itemspec that the revision applies to.
Returns:
int:
The changeset number corresponding to the versionspec.
"""
data = (
self._run_tf([
'vc',
'history',
'/stopafter:1',
'/recursive',
'/format:detailed',
'/version:%s' % revision,
path or os.getcwd(),
])
.stdout_bytes
.read()
)
m = re.search(br'^Changeset: (\d+)$', data, re.MULTILINE)
if not m:
logging.debug('Failed to parse output from "tf vc history":\n%s',
data)
raise InvalidRevisionSpecError(
'"%s" does not appear to be a valid versionspec' % revision)
return int(m.group(1))
def diff(
self,
*,
client: TFSClient,
revisions: SCMClientRevisionSpec,
include_files: List[str],
exclude_patterns: List[str],
) -> SCMClientDiffResult:
"""Return the generated diff.
Args:
client (TFSClient):
The client performing the diff.
revisions (dict):
A dictionary containing ``base`` and ``tip`` keys.
include_files (list):
A list of file paths to include in the diff.
exclude_patterns (list):
A list of file paths to exclude from the diff.
Returns:
dict:
A dictionary of diff results.
See :py:class:`~rbtools.clients.base.scmclient.SCMClientDiffResult`
for the format of this dictionary.
"""
base = revisions['base']
tip = revisions['tip']
assert isinstance(base, str)
assert isinstance(tip, str)
if tip == self.REVISION_WORKING_COPY:
# TODO: support committed revisions
return self._diff_working_copy(client=client,
base=base,
include_files=include_files,
exclude_patterns=exclude_patterns)
raise SCMError('Posting committed changes is not yet supported '
'for TFS when using the tf.exe wrapper.')
def _diff_working_copy(
self,
*,
client: TFSClient,
base: str,
include_files: List[str],
exclude_patterns: List[str],
) -> SCMClientDiffResult:
"""Return a diff of the working copy.
Args:
client (TFSClient):
The client performing the diff.
base (str):
The base revision to diff against.
include_files (list of str, unused):
A list of file paths to include in the diff.
exclude_patterns (list of str):
A list of file paths to exclude from the diff.
Returns:
dict:
A dictionary of diff results.
See :py:class:`~rbtools.clients.base.scmclient.SCMClientDiffResult`
for the format of this dictionary.
``parent_diff`` will always be ``None``.
"""
diff_tool = client.get_diff_tool()
assert diff_tool is not None
status = (
self._run_tf(['vc', 'status', '/format:xml'])
.stdout_bytes
.read()
)
root = ET.fromstring(status)
stream = io.BytesIO()
diff_writer = UnifiedDiffWriter(stream)
for pending_change in root.findall(
'./PendingSet/PendingChanges/PendingChange'):
action = pending_change.attrib['chg'].split(' ')
old_filename = \
pending_change.attrib.get('srcitem', '').encode('utf-8')
new_filename = pending_change.attrib['item'].encode('utf-8')
local_filename = pending_change.attrib['local']
old_version = \
pending_change.attrib.get('svrfm', '0').encode('utf-8')
file_type = pending_change.attrib['type']
encoding = pending_change.attrib['enc']
new_version = b'(pending)'
old_data = b''
new_data = b''
binary = (encoding == '-1')
copied = 'Branch' in action
if (not file_type or (not os.path.isfile(local_filename) and
'Delete' not in action)):
continue
if (exclude_patterns and
filename_match_any_patterns(local_filename,
exclude_patterns)):
continue
if 'Add' in action:
old_filename = b'/dev/null'
if not binary:
with open(local_filename, 'rb') as f:
new_data = f.read()
old_data = b''
elif 'Delete' in action:
if not binary:
old_data = (
self._run_tf([
'vc',
'view',
old_filename.decode('utf-8'),
'/version:%s' % old_version.decode('utf-8'),
])
.stdout_bytes
.read()
)
new_data = b''
new_version = b'(deleted)'
elif 'Edit' in action:
if not binary:
old_data = (
self._run_tf([
'vc',
'view',
old_filename.decode('utf-8'),
'/version:%s' % old_version.decode('utf-8'),
])
.stdout_bytes
.read()
)
with open(local_filename, 'rb') as f:
new_data = f.read()
if copied:
diff_writer.write_line(b'Copied from: %s' % old_filename)
if binary:
diff_writer.write_file_headers(
orig_path=old_filename,
orig_extra=old_version,
modified_path=new_filename,
modified_extra=new_version)
if 'Add' in action:
old_filename = new_filename
diff_writer.write_binary_files_differ(
orig_path=old_filename,
modified_path=new_filename)
elif old_filename != new_filename and old_data == new_data:
# Renamed file with no changes.
diff_writer.write_file_headers(
orig_path=old_filename,
orig_extra=old_version,
modified_path=new_filename,
modified_extra=new_version)
else:
old_tmp = make_tempfile(content=old_data)
new_tmp = make_tempfile(content=new_data)
diff_result = diff_tool.run_diff_file(
orig_path=old_tmp,
modified_path=new_tmp)
if diff_result.has_text_differences:
diff_writer.write_file_headers(
orig_path=old_filename,
orig_extra=old_version,
modified_path=new_filename,
modified_extra=new_version)
diff_writer.write_diff_file_result_hunks(diff_result)
os.unlink(old_tmp)
os.unlink(new_tmp)
return {
'diff': stream.getvalue(),
'parent_diff': None,
'base_commit_id': base,
}
def _run_tf(
self,
args: List[str],
) -> RunProcessResult:
"""Run the "tf" command.
Args:
args (list of str):
A list of arguments to pass to rb-tfs.
Returns:
rbtools.utils.process.RunProcessResult:
The result of the command.
"""
command = ['tf'] + args + ['/noprompt']
tfs_login = getattr(self.options, 'tfs_login', None)
if tfs_login:
command.append('/login:%s' % tfs_login)
return run_process(command, ignore_errors=True)
class TEEWrapper(BaseTFWrapper):
"""Implementation wrapper for using Team Explorer Everywhere."""
REVISION_WORKING_COPY = '--rbtools-working-copy'
@classmethod
def get_default_tf_locations(
cls,
target_platform: str = sys.platform
) -> List[str]:
"""Return default locations for tf.cmd for the given platform.
Version Added:
4.0
Args:
target_platform (str):
The platform to return paths for.
Returns:
list of str:
The list of possible platforms.
"""
tf_locations: List[str] = []
if target_platform.startswith('win'):
# First check in the system path. If that doesn't work, look in the
# two standard install locations.
tf_locations.extend([
'tf.cmd',
(r'%programfiles(x86)%\Microsoft Visual Studio 12.0\Common7'
r'\IDE\tf.cmd'),
(r'%programfiles%\Microsoft Team Foundation Server 12.0\Tools'
r'\tf.cmd'),
])
else:
tf_locations.append('tf')
return tf_locations
def __init__(self, **kwargs) -> None:
"""Initialize the wrapper.
Args:
**kwargs (dict):
Keyword arguments to pass to the parent class.
"""
super().__init__(**kwargs)
self.tf: Optional[str] = None
def check_dependencies(self) -> None:
"""Check whether all dependencies for the client are available.
This checks for the presence of :command:`tf` or :command:`tf.cmd`
in known locations and in the system path.
It will also include the :option:`--tf-cmd` location, if provided.
Version Added:
4.0
Raises:
rbtools.clients.errors.SCMClientDependencyError:
A :command:`tf` tool could not be found.
"""
options = self.options
tf_locations = []
if options and getattr(options, 'tf_cmd', None):
tf_locations.append(options.tf_cmd)
tf_locations += self.get_default_tf_locations()
for location in tf_locations:
location = os.path.expandvars(location)
if check_install([location, 'help']):
self.tf = location
return
# To help with debugging, we'll include the full path on each.
raise SCMClientDependencyError(missing_exes=[tuple(tf_locations)])
def get_local_path(self) -> Optional[str]:
"""Return the local path to the working tree.
Returns:
str:
The filesystem path of the repository on the client system.
"""
assert self.tf is not None
workfold = (
self._run_tf(['workfold', os.getcwd()])
.stdout
.read()
)
m = re.search('^Collection: (.*)$', workfold, re.MULTILINE)
if m:
return unquote(m.group(1))
logging.debug('Could not find the collection from "tf workfold"')
return None
def get_repository_info(self) -> Optional[RepositoryInfo]:
"""Return repository information for the current working tree.
Returns:
rbtools.clients.base.repository.RepositoryInfo:
The repository info structure.
"""
path = self.get_local_path()
if path:
return RepositoryInfo(path=path, local_path=path)
return None
def parse_revision_spec(
self,
revisions: List[str],
) -> SCMClientRevisionSpec:
"""Parse the given revision spec.
These will be used to generate the diffs to upload to Review Board
(or print). The diff for review will include the changes in (base,
tip], and the parent diff (if necessary) will include (parent,
base].
If a single revision is passed in, this will return the parent of
that revision for "base" and the passed-in revision for "tip".
If zero revisions are passed in, this will return revisions
relevant for the "current change" (changes in the work folder which
have not yet been checked in).
Args:
revisions (list of str):
A list of revisions as specified by the user.
Items in the list do not necessarily represent a single
revision, since the user can use the TFS-native syntax of
``r1~r2``. Versions passed in can be any versionspec, such as a
changeset number, ``L``-prefixed label name, ``W`` (latest
workspace version), or ``T`` (latest upstream version).
Returns:
dict:
The parsed revision spec.
See :py:class:`~rbtools.clients.base.scmclient.
SCMClientRevisionSpec` for the format of this dictionary.
This always populates ``base`` and ``tip``.
Raises:
rbtools.clients.errors.TooManyRevisionsError:
Too many revisions were specified.
rbtools.clients.errors.InvalidRevisionSpecError:
The given revision spec could not be parsed.
"""
n_revisions = len(revisions)
if n_revisions == 1 and '~' in revisions[0]:
revisions = revisions[0].split('~')
n_revisions = len(revisions)
if n_revisions == 0:
# Most recent checked-out revision -- working copy
return {
'base': str(self._convert_symbolic_revision('W')),
'tip': self.REVISION_WORKING_COPY,
}
elif n_revisions == 1:
# Either a numeric revision (n-1:n) or a changelist
revision = self._convert_symbolic_revision(revisions[0])
return {
'base': str(revision - 1),
'tip': str(revision),
}
elif n_revisions == 2:
# Diff between two numeric revisions
return {
'base': str(self._convert_symbolic_revision(revisions[0])),
'tip': str(self._convert_symbolic_revision(revisions[1])),
}
else:
raise TooManyRevisionsError
def _convert_symbolic_revision(
self,
revision: str,
path: Optional[str] = None,
) -> int:
"""Convert a symbolic revision into a numeric changeset.
Args:
revision (str):
The TFS versionspec to convert.
path (str, optional):
The itemspec that the revision applies to.
Returns:
int:
The changeset number corresponding to the versionspec.
"""
args = ['history', '-stopafter:1', '-recursive', '-format:xml']
# 'tf history -version:W'` doesn't seem to work (even though it's
# supposed to). Luckily, W is the default when -version isn't passed,
# so just elide it.
if revision != 'W':
args.append('-version:%s' % revision)
args.append(path or os.getcwd())
# We access stdout_bytes, even though the XML results we get should
# always be UTF-8. They are well-formed with the encoding specified,
# so we can let ElementTree determine how to decode it.
data = (
self._run_tf(args)
.stdout_bytes
.read()
)
try:
root = ET.fromstring(data)
item = root.find('./changeset')
if item is not None:
return int(item.attrib['id'])
else:
raise Exception('No changesets found')
except Exception as e:
logging.debug('Failed to parse output from "tf history": %s\n%s',
e, data, exc_info=True)
raise InvalidRevisionSpecError(
'"%s" does not appear to be a valid versionspec' % revision)
def diff(
self,
*,
client: TFSClient,
revisions: SCMClientRevisionSpec,
include_files: List[str],
exclude_patterns: List[str],
) -> SCMClientDiffResult:
"""Return the generated diff.
Args:
client (TFSClient):
The client performing the diff.
revisions (dict):
A dictionary containing ``base`` and ``tip`` keys.
include_files (list):
A list of file paths to include in the diff.
exclude_patterns (list):
A list of file paths to exclude from the diff.
Returns:
dict:
A dictionary of diff results.
See :py:class:`~rbtools.clients.base.scmclient.SCMClientDiffResult`
for the format of this dictionary.
``parent_diff`` will always be ``None``.
"""
base = revisions['base']
tip = revisions['tip']
assert isinstance(base, str)
assert isinstance(tip, str)
if tip == self.REVISION_WORKING_COPY:
return self._diff_working_copy(client=client,
base=base,
include_files=include_files,
exclude_patterns=exclude_patterns)
raise SCMError('Posting committed changes is not yet supported '
'for TFS when using the Team Explorer Everywhere '
'wrapper.')
def _diff_working_copy(
self,
*,
client: TFSClient,
base: str,
include_files: List[str],
exclude_patterns: List[str],
) -> SCMClientDiffResult:
"""Return a diff of the working copy.
Args:
client (TFSClient):
The client performing the diff.
base (str):
The base revision to diff against.
include_files (list):
A list of file paths to include in the diff.
exclude_patterns (list):
A list of file paths to exclude from the diff.
Returns:
dict:
A dictionary of diff results.
See :py:class:`~rbtools.clients.base.scmclient.SCMClientDiffResult`
for the format of this dictionary.
``parent_diff`` will always be ``None``.
"""
diff_tool = client.get_diff_tool()
assert diff_tool is not None
# We access stdout_bytes, even though the XML results we get should
# always be UTF-8. They are well-formed with the encoding specified,
# so we can let ElementTree determine how to decode it.
status = (
self._run_tf(['status', '-format:xml'])
.stdout_bytes
.read()
)
root = ET.fromstring(status)
stream = io.BytesIO()
diff_writer = UnifiedDiffWriter(stream)
for pending_change in root.findall('./pending-changes/pending-change'):
action = pending_change.attrib['change-type'].split(', ')
new_filename = pending_change.attrib['server-item'].encode('utf-8')
local_filename = pending_change.attrib['local-item']
old_version = pending_change.attrib['version'].encode('utf-8')
file_type = pending_change.attrib.get('file-type')
new_version = b'(pending)'
old_data = b''
new_data = b''
copied = 'branch' in action
if (not file_type or (not os.path.isfile(local_filename) and
'delete' not in action)):
continue
if (exclude_patterns and
filename_match_any_patterns(local_filename,
exclude_patterns)):
continue
if 'rename' in action:
old_filename = \
pending_change.attrib['source-item'].encode('utf-8')
else:
old_filename = new_filename
if copied:
old_filename = \
pending_change.attrib['source-item'].encode('utf-8')
old_version = (
'%d' % self._convert_symbolic_revision(
'W', old_filename.decode('utf-8'))).encode('utf-8')
if 'add' in action:
old_filename = b'/dev/null'
if file_type != 'binary':
with open(local_filename, 'rb') as f:
new_data = f.read()
old_data = b''
elif 'delete' in action:
if file_type != 'binary':
old_data = (
self._run_tf([
'print',
'-version:%s' % old_version.decode('utf-8'),
old_filename.decode('utf-8'),
])
.stdout_bytes
.read()
)
new_data = b''
new_version = b'(deleted)'
elif 'edit' in action:
if file_type != 'binary':
old_data = (
self._run_tf([
'print',
'-version:%s' % old_version.decode('utf-8'),
old_filename.decode('utf-8'),
])
.stdout_bytes
.read()
)
with open(local_filename, 'rb') as f:
new_data = f.read()
if copied:
diff_writer.write_line(b'Copied from: %s' % old_filename)
if file_type == 'binary':
diff_writer.write_file_headers(
orig_path=old_filename,
orig_extra=old_version,
modified_path=new_filename,