forked from chenkaie/Tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsvnmerge.py
executable file
·2188 lines (1914 loc) · 81.2 KB
/
svnmerge.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2005, Giovanni Bajo
# Copyright (c) 2004-2005, Awarix, Inc.
# All rights reserved.
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
#
# Author: Archie Cobbs <archie at awarix dot com>
# Rewritten in Python by: Giovanni Bajo <rasky at develer dot com>
#
# Acknowledgments:
# John Belmonte <john at neggie dot net> - metadata and usability
# improvements
# Blair Zajac <blair at orcaware dot com> - random improvements
# Raman Gupta <rocketraman at fastmail dot fm> - bidirectional and transitive
# merging support
#
# $HeadURL$
# $LastChangedDate$
# $LastChangedBy$
# $LastChangedRevision$
#
# Requisites:
# svnmerge.py has been tested with all SVN major versions since 1.1 (both
# client and server). It is unknown if it works with previous versions.
#
# Differences from svnmerge.sh:
# - More portable: tested as working in FreeBSD and OS/2.
# - Add double-verbose mode, which shows every svn command executed (-v -v).
# - "svnmerge avail" now only shows commits in source, not also commits in
# other parts of the repository.
# - Add "svnmerge block" to flag some revisions as blocked, so that
# they will not show up anymore in the available list. Added also
# the complementary "svnmerge unblock".
# - "svnmerge avail" has grown two new options:
# -B to display a list of the blocked revisions
# -A to display both the blocked and the available revisions.
# - Improved generated commit message to make it machine parsable even when
# merging commits which are themselves merges.
# - Add --force option to skip working copy check
# - Add --record-only option to "svnmerge merge" to avoid performing
# an actual merge, yet record that a merge happened.
#
# TODO:
# - Add "svnmerge avail -R": show logs in reverse order
#
# Information for Hackers:
#
# Identifiers for branches:
# A branch is identified in three ways within this source:
# - as a working copy (variable name usually includes 'dir')
# - as a fully qualified URL
# - as a path identifier (an opaque string indicating a particular path
# in a particular repository; variable name includes 'pathid')
# A "target" is generally user-specified, and may be a working copy or
# a URL.
import sys, os, getopt, re, types, tempfile, time, popen2, locale
from bisect import bisect
from xml.dom import pulldom
NAME = "svnmerge"
if not hasattr(sys, "version_info") or sys.version_info < (2, 0):
error("requires Python 2.0 or newer")
# Set up the separator used to separate individual log messages from
# each revision merged into the target location. Also, create a
# regular expression that will find this same separator in already
# committed log messages, so that the separator used for this run of
# svnmerge.py will have one more LOG_SEPARATOR appended to the longest
# separator found in all the commits.
LOG_SEPARATOR = 8 * '.'
LOG_SEPARATOR_RE = re.compile('^((%s)+)' % re.escape(LOG_SEPARATOR),
re.MULTILINE)
# Each line of the embedded log messages will be prefixed by LOG_LINE_PREFIX.
LOG_LINE_PREFIX = 2 * ' '
# Set python to the default locale as per environment settings, same as svn
# TODO we should really parse config and if log-encoding is specified, set
# the locale to match that encoding
locale.setlocale(locale.LC_ALL, '')
# We want the svn output (such as svn info) to be non-localized
# Using LC_MESSAGES should not affect localized output of svn log, for example
if os.environ.has_key("LC_ALL"):
del os.environ["LC_ALL"]
os.environ["LC_MESSAGES"] = "C"
###############################################################################
# Support for older Python versions
###############################################################################
# True/False constants are Python 2.2+
try:
True, False
except NameError:
True, False = 1, 0
def lstrip(s, ch):
"""Replacement for str.lstrip (support for arbitrary chars to strip was
added in Python 2.2.2)."""
i = 0
try:
while s[i] == ch:
i = i+1
return s[i:]
except IndexError:
return ""
def rstrip(s, ch):
"""Replacement for str.rstrip (support for arbitrary chars to strip was
added in Python 2.2.2)."""
try:
if s[-1] != ch:
return s
i = -2
while s[i] == ch:
i = i-1
return s[:i+1]
except IndexError:
return ""
def strip(s, ch):
"""Replacement for str.strip (support for arbitrary chars to strip was
added in Python 2.2.2)."""
return lstrip(rstrip(s, ch), ch)
def rsplit(s, sep, maxsplits=0):
"""Like str.rsplit, which is Python 2.4+ only."""
L = s.split(sep)
if not 0 < maxsplits <= len(L):
return L
return [sep.join(L[0:-maxsplits])] + L[-maxsplits:]
###############################################################################
def kwextract(s):
"""Extract info from a svn keyword string."""
try:
return strip(s, "$").strip().split(": ")[1]
except IndexError:
return "<unknown>"
__revision__ = kwextract('$Rev$')
__date__ = kwextract('$Date$')
# Additional options, not (yet?) mapped to command line flags
default_opts = {
"svn": "svn",
"prop": NAME + "-integrated",
"block-prop": NAME + "-blocked",
"commit-verbose": True,
}
logs = {}
def console_width():
"""Get the width of the console screen (if any)."""
try:
return int(os.environ["COLUMNS"])
except (KeyError, ValueError):
pass
try:
# Call the Windows API (requires ctypes library)
from ctypes import windll, create_string_buffer
h = windll.kernel32.GetStdHandle(-11)
csbi = create_string_buffer(22)
res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
if res:
import struct
(bufx, bufy,
curx, cury, wattr,
left, top, right, bottom,
maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)
return right - left + 1
except ImportError:
pass
# Parse the output of stty -a
if os.isatty(1):
out = os.popen("stty -a").read()
m = re.search(r"columns (\d+);", out)
if m:
return int(m.group(1))
# sensible default
return 80
def error(s):
"""Subroutine to output an error and bail."""
print >> sys.stderr, "%s: %s" % (NAME, s)
sys.exit(1)
def report(s):
"""Subroutine to output progress message, unless in quiet mode."""
if opts["verbose"]:
print "%s: %s" % (NAME, s)
def prefix_lines(prefix, lines):
"""Given a string representing one or more lines of text, insert the
specified prefix at the beginning of each line, and return the result.
The input must be terminated by a newline."""
assert lines[-1] == "\n"
return prefix + lines[:-1].replace("\n", "\n"+prefix) + "\n"
def recode_stdout_to_file(s):
if locale.getdefaultlocale()[1] is None or not hasattr(sys.stdout, "encoding") \
or sys.stdout.encoding is None:
return s
u = s.decode(sys.stdout.encoding)
return u.encode(locale.getdefaultlocale()[1])
class LaunchError(Exception):
"""Signal a failure in execution of an external command. Parameters are the
exit code of the process, the original command line, and the output of the
command."""
try:
"""Launch a sub-process. Return its output (both stdout and stderr),
optionally split by lines (if split_lines is True). Raise a LaunchError
exception if the exit code of the process is non-zero (failure).
This function has two implementations, one based on subprocess (preferred),
and one based on popen (for compatibility).
"""
import subprocess
import shlex
def launch(cmd, split_lines=True):
# Requiring python 2.4 or higher, on some platforms we get
# much faster performance from the subprocess module (where python
# doesn't try to close an exhorbitant number of file descriptors)
stdout = ""
stderr = ""
try:
if os.name == 'nt':
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, \
close_fds=False, stderr=subprocess.PIPE)
else:
# Use shlex to break up the parameters intelligently,
# respecting quotes. shlex can't handle unicode.
args = shlex.split(cmd.encode('ascii'))
p = subprocess.Popen(args, stdout=subprocess.PIPE, \
close_fds=False, stderr=subprocess.PIPE)
stdoutAndErr = p.communicate()
stdout = stdoutAndErr[0]
stderr = stdoutAndErr[1]
except OSError, inst:
# Using 1 as failure code; should get actual number somehow? For
# examples see svnmerge_test.py's TestCase_launch.test_failure and
# TestCase_launch.test_failurecode.
raise LaunchError(1, cmd, stdout + " " + stderr + ": " + str(inst))
if p.returncode == 0:
if split_lines:
# Setting keepends=True for compatibility with previous logic
# (where file.readlines() preserves newlines)
return stdout.splitlines(True)
else:
return stdout
else:
raise LaunchError(p.returncode, cmd, stdout + stderr)
except ImportError:
# support versions of python before 2.4 (slower on some systems)
def launch(cmd, split_lines=True):
if os.name not in ['nt', 'os2']:
p = popen2.Popen4(cmd)
p.tochild.close()
if split_lines:
out = p.fromchild.readlines()
else:
out = p.fromchild.read()
ret = p.wait()
if ret == 0:
ret = None
else:
ret >>= 8
else:
i,k = os.popen4(cmd)
i.close()
if split_lines:
out = k.readlines()
else:
out = k.read()
ret = k.close()
if ret is None:
return out
raise LaunchError(ret, cmd, out)
def launchsvn(s, show=False, pretend=False, **kwargs):
"""Launch SVN and grab its output."""
username = password = configdir = ""
if opts.get("username", None):
username = "--username=" + opts["username"]
if opts.get("password", None):
password = "--password=" + opts["password"]
if opts.get("config-dir", None):
configdir = "--config-dir=" + opts["config-dir"]
cmd = ' '.join(filter(None, [opts["svn"], "--non-interactive",
username, password, configdir, s]))
if show or opts["verbose"] >= 2:
print cmd
if pretend:
return None
return launch(cmd, **kwargs)
def svn_command(s):
"""Do (or pretend to do) an SVN command."""
out = launchsvn(s, show=opts["show-changes"] or opts["dry-run"],
pretend=opts["dry-run"],
split_lines=False)
if not opts["dry-run"]:
print out
def check_dir_clean(dir):
"""Check the current status of dir for local mods."""
if opts["force"]:
report('skipping status check because of --force')
return
report('checking status of "%s"' % dir)
# Checking with -q does not show unversioned files or external
# directories. Though it displays a debug message for external
# directories, after a blank line. So, practically, the first line
# matters: if it's non-empty there is a modification.
out = launchsvn("status -q %s" % dir)
if out and out[0].strip():
error('"%s" has local modifications; it must be clean' % dir)
class RevisionLog:
"""
A log of the revisions which affected a given URL between two
revisions.
"""
def __init__(self, url, begin, end, find_propchanges=False):
"""
Create a new RevisionLog object, which stores, in self.revs, a list
of the revisions which affected the specified URL between begin and
end. If find_propchanges is True, self.propchange_revs will contain a
list of the revisions which changed properties directly on the
specified URL. URL must be the URL for a directory in the repository.
"""
self.url = url
# Setup the log options (--quiet, so we don't show log messages)
log_opts = '--xml --quiet -r%s:%s "%s"' % (begin, end, url)
if find_propchanges:
# The --verbose flag lets us grab merge tracking information
# by looking at propchanges
log_opts = "--verbose " + log_opts
# Read the log to look for revision numbers and merge-tracking info
self.revs = []
self.propchange_revs = []
repos_pathid = target_to_pathid(url)
for chg in SvnLogParser(launchsvn("log %s" % log_opts,
split_lines=False)):
self.revs.append(chg.revision())
for p in chg.paths():
if p.action() == 'M' and p.pathid() == repos_pathid:
self.propchange_revs.append(chg.revision())
# Save the range of the log
self.begin = int(begin)
if end == "HEAD":
# If end is not provided, we do not know which is the latest
# revision in the repository. So we set 'end' to the latest
# known revision.
self.end = self.revs[-1]
else:
self.end = int(end)
self._merges = None
self._blocks = None
def merge_metadata(self):
"""
Return a VersionedProperty object, with a cached view of the merge
metadata in the range of this log.
"""
# Load merge metadata if necessary
if not self._merges:
self._merges = VersionedProperty(self.url, opts["prop"])
self._merges.load(self)
return self._merges
def block_metadata(self):
if not self._blocks:
self._blocks = VersionedProperty(self.url, opts["block-prop"])
self._blocks.load(self)
return self._blocks
class VersionedProperty:
"""
A read-only, cached view of a versioned property.
self.revs contains a list of the revisions in which the property changes.
self.values stores the new values at each corresponding revision. If the
value of the property is unknown, it is set to None.
Initially, we set self.revs to [0] and self.values to [None]. This
indicates that, as of revision zero, we know nothing about the value of
the property.
Later, if you run self.load(log), we cache the value of this property over
the entire range of the log by noting each revision in which the property
was changed. At the end of the range of the log, we invalidate our cache
by adding the value "None" to our cache for any revisions which fall out
of the range of our log.
Once self.revs and self.values are filled, we can find the value of the
property at any arbitrary revision using a binary search on self.revs.
Once we find the last revision during which the property was changed,
we can lookup the associated value in self.values. (If the associated
value is None, the associated value was not cached and we have to do
a full propget.)
An example: We know that the 'svnmerge' property was added in r10, and
changed in r21. We gathered log info up until r40.
revs = [0, 10, 21, 40]
values = [None, "val1", "val2", None]
What these values say:
- From r0 to r9, we know nothing about the property.
- In r10, the property was set to "val1". This property stayed the same
until r21, when it was changed to "val2".
- We don't know what happened after r40.
"""
def __init__(self, url, name):
"""View the history of a versioned property at URL with name"""
self.url = url
self.name = name
# We know nothing about the value of the property. Setup revs
# and values to indicate as such.
self.revs = [0]
self.values = [None]
# We don't have any revisions cached
self._initial_value = None
self._changed_revs = []
self._changed_values = []
def load(self, log):
"""
Load the history of property changes from the specified
RevisionLog object.
"""
# Get the property value before the range of the log
if log.begin > 1:
self.revs.append(log.begin-1)
try:
self._initial_value = self.raw_get(log.begin-1)
except LaunchError:
# The specified URL might not exist before the
# range of the log. If so, we can safely assume
# that the property was empty at that time.
self._initial_value = { }
self.values.append(self._initial_value)
else:
self._initial_value = { }
self.values[0] = self._initial_value
# Cache the property values in the log range
old_value = self._initial_value
for rev in log.propchange_revs:
new_value = self.raw_get(rev)
if new_value != old_value:
self._changed_revs.append(rev)
self._changed_values.append(new_value)
self.revs.append(rev)
self.values.append(new_value)
old_value = new_value
# Indicate that we know nothing about the value of the property
# after the range of the log.
if log.revs:
self.revs.append(log.end+1)
self.values.append(None)
def raw_get(self, rev=None):
"""
Get the property at revision REV. If rev is not specified, get
the property at revision HEAD.
"""
return get_revlist_prop(self.url, self.name, rev)
def get(self, rev=None):
"""
Get the property at revision REV. If rev is not specified, get
the property at revision HEAD.
"""
if rev is not None:
# Find the index using a binary search
i = bisect(self.revs, rev) - 1
# Return the value of the property, if it was cached
if self.values[i] is not None:
return self.values[i]
# Get the current value of the property
return self.raw_get(rev)
def changed_revs(self, key=None):
"""
Get a list of the revisions in which the specified dictionary
key was changed in this property. If key is not specified,
return a list of revisions in which any key was changed.
"""
if key is None:
return self._changed_revs
else:
changed_revs = []
old_val = self._initial_value
for rev, val in zip(self._changed_revs, self._changed_values):
if val.get(key) != old_val.get(key):
changed_revs.append(rev)
old_val = val
return changed_revs
def initialized_revs(self):
"""
Get a list of the revisions in which keys were added or
removed in this property.
"""
initialized_revs = []
old_len = len(self._initial_value)
for rev, val in zip(self._changed_revs, self._changed_values):
if len(val) != old_len:
initialized_revs.append(rev)
old_len = len(val)
return initialized_revs
class RevisionSet:
"""
A set of revisions, held in dictionary form for easy manipulation. If we
were to rewrite this script for Python 2.3+, we would subclass this from
set (or UserSet). As this class does not include branch
information, it's assumed that one instance will be used per
branch.
"""
def __init__(self, parm):
"""Constructs a RevisionSet from a string in property form, or from
a dictionary whose keys are the revisions. Raises ValueError if the
input string is invalid."""
self._revs = {}
revision_range_split_re = re.compile('[-:]')
if isinstance(parm, types.DictType):
self._revs = parm.copy()
elif isinstance(parm, types.ListType):
for R in parm:
self._revs[int(R)] = 1
else:
parm = parm.strip()
if parm:
for R in parm.split(","):
rev_or_revs = re.split(revision_range_split_re, R)
if len(rev_or_revs) == 1:
self._revs[int(rev_or_revs[0])] = 1
elif len(rev_or_revs) == 2:
for rev in range(int(rev_or_revs[0]),
int(rev_or_revs[1])+1):
self._revs[rev] = 1
else:
raise ValueError, 'Ill formatted revision range: ' + R
def sorted(self):
revnums = self._revs.keys()
revnums.sort()
return revnums
def normalized(self):
"""Returns a normalized version of the revision set, which is an
ordered list of couples (start,end), with the minimum number of
intervals."""
revnums = self.sorted()
revnums.reverse()
ret = []
while revnums:
s = e = revnums.pop()
while revnums and revnums[-1] in (e, e+1):
e = revnums.pop()
ret.append((s, e))
return ret
def __str__(self):
"""Convert the revision set to a string, using its normalized form."""
L = []
for s,e in self.normalized():
if s == e:
L.append(str(s))
else:
L.append(str(s) + "-" + str(e))
return ",".join(L)
def __contains__(self, rev):
return self._revs.has_key(rev)
def __sub__(self, rs):
"""Compute subtraction as in sets."""
revs = {}
for r in self._revs.keys():
if r not in rs:
revs[r] = 1
return RevisionSet(revs)
def __and__(self, rs):
"""Compute intersections as in sets."""
revs = {}
for r in self._revs.keys():
if r in rs:
revs[r] = 1
return RevisionSet(revs)
def __nonzero__(self):
return len(self._revs) != 0
def __len__(self):
"""Return the number of revisions in the set."""
return len(self._revs)
def __iter__(self):
return iter(self.sorted())
def __or__(self, rs):
"""Compute set union."""
revs = self._revs.copy()
revs.update(rs._revs)
return RevisionSet(revs)
def merge_props_to_revision_set(merge_props, pathid):
"""A converter which returns a RevisionSet instance containing the
revisions from PATH as known to BRANCH_PROPS. BRANCH_PROPS is a
dictionary of pathid -> revision set branch integration information
(as returned by get_merge_props())."""
if not merge_props.has_key(pathid):
error('no integration info available for path "%s"' % pathid)
return RevisionSet(merge_props[pathid])
def dict_from_revlist_prop(propvalue):
"""Given a property value as a string containing per-source revision
lists, return a dictionary whose key is a source path identifier
and whose value is the revisions for that source."""
prop = {}
# Multiple sources are separated by any whitespace.
for L in propvalue.split():
# We use rsplit to play safe and allow colons in pathids.
source, revs = rsplit(L.strip(), ":", 1)
prop[source] = revs
return prop
def get_revlist_prop(url_or_dir, propname, rev=None):
"""Given a repository URL or working copy path and a property
name, extract the values of the property which store per-source
revision lists and return a dictionary whose key is a source path
identifier, and whose value is the revisions for that source."""
# Note that propget does not return an error if the property does
# not exist, it simply does not output anything. So we do not need
# to check for LaunchError here.
args = '--strict "%s" "%s"' % (propname, url_or_dir)
if rev:
args = '-r %s %s' % (rev, args)
out = launchsvn('propget %s' % args, split_lines=False)
return dict_from_revlist_prop(out)
def get_merge_props(dir):
"""Extract the merged revisions."""
return get_revlist_prop(dir, opts["prop"])
def get_block_props(dir):
"""Extract the blocked revisions."""
return get_revlist_prop(dir, opts["block-prop"])
def get_blocked_revs(dir, source_pathid):
p = get_block_props(dir)
if p.has_key(source_pathid):
return RevisionSet(p[source_pathid])
return RevisionSet("")
def format_merge_props(props, sep=" "):
"""Formats the hash PROPS as a string suitable for use as a
Subversion property value."""
assert sep in ["\t", "\n", " "] # must be a whitespace
props = props.items()
props.sort()
L = []
for h, r in props:
L.append(h + ":" + r)
return sep.join(L)
def _run_propset(dir, prop, value):
"""Set the property 'prop' of directory 'dir' to value 'value'. We go
through a temporary file to not run into command line length limits."""
try:
fd, fname = tempfile.mkstemp()
f = os.fdopen(fd, "wb")
except AttributeError:
# Fallback for Python <= 2.3 which does not have mkstemp (mktemp
# suffers from race conditions. Not that we care...)
fname = tempfile.mktemp()
f = open(fname, "wb")
try:
f.write(value)
f.close()
report("property data written to temp file: %s" % value)
svn_command('propset "%s" -F "%s" "%s"' % (prop, fname, dir))
finally:
os.remove(fname)
def set_props(dir, name, props):
props = format_merge_props(props)
if props:
_run_propset(dir, name, props)
else:
svn_command('propdel "%s" "%s"' % (name, dir))
def set_merge_props(dir, props):
set_props(dir, opts["prop"], props)
def set_block_props(dir, props):
set_props(dir, opts["block-prop"], props)
def set_blocked_revs(dir, source_pathid, revs):
props = get_block_props(dir)
if revs:
props[source_pathid] = str(revs)
elif props.has_key(source_pathid):
del props[source_pathid]
set_block_props(dir, props)
def is_url(url):
"""Check if url is a valid url."""
return re.search(r"^[a-zA-Z][-+\.\w]*://[^\s]+$", url) is not None
def is_wc(dir):
"""Check if a directory is a working copy."""
return os.path.isdir(os.path.join(dir, ".svn")) or \
os.path.isdir(os.path.join(dir, "_svn"))
_cache_svninfo = {}
def get_svninfo(target):
"""Extract the subversion information for a target (through 'svn info').
This function uses an internal cache to let clients query information
many times."""
if _cache_svninfo.has_key(target):
return _cache_svninfo[target]
info = {}
for L in launchsvn('info "%s"' % target):
L = L.strip()
if not L:
continue
key, value = L.split(": ", 1)
info[key] = value.strip()
_cache_svninfo[target] = info
return info
def target_to_url(target):
"""Convert working copy path or repos URL to a repos URL."""
if is_wc(target):
info = get_svninfo(target)
return info["URL"]
return target
_cache_reporoot = {}
def get_repo_root(target):
"""Compute the root repos URL given a working-copy path, or a URL."""
# Try using "svn info WCDIR". This works only on SVN clients >= 1.3
if not is_url(target):
try:
info = get_svninfo(target)
root = info["Repository Root"]
_cache_reporoot[root] = None
return root
except KeyError:
pass
url = target_to_url(target)
assert url[-1] != '/'
else:
url = target
# Go through the cache of the repository roots. This avoids extra
# server round-trips if we are asking the root of different URLs
# in the same repository (the cache in get_svninfo() cannot detect
# that of course and would issue a remote command).
assert is_url(url)
for r in _cache_reporoot:
if url.startswith(r):
return r
# Try using "svn info URL". This works only on SVN clients >= 1.2
try:
info = get_svninfo(url)
root = info["Repository Root"]
_cache_reporoot[root] = None
return root
except LaunchError:
pass
# Constrained to older svn clients, we are stuck with this ugly
# trial-and-error implementation. It could be made faster with a
# binary search.
while url:
temp = os.path.dirname(url)
try:
launchsvn('proplist "%s"' % temp)
except LaunchError:
_cache_reporoot[url] = None
return url
url = temp
assert False, "svn repos root not found"
def target_to_pathid(target):
"""Convert a target (either a working copy path or an URL) into a
path identifier."""
root = get_repo_root(target)
url = target_to_url(target)
assert root[-1] != "/"
assert url[:len(root)] == root, "url=%r, root=%r" % (url, root)
return url[len(root):]
class SvnLogParser:
"""
Parse the "svn log", going through the XML output and using pulldom (which
would even allow streaming the command output).
"""
def __init__(self, xml):
self._events = pulldom.parseString(xml)
def __getitem__(self, idx):
for event, node in self._events:
if event == pulldom.START_ELEMENT and node.tagName == "logentry":
self._events.expandNode(node)
return self.SvnLogRevision(node)
raise IndexError, "Could not find 'logentry' tag in xml"
class SvnLogRevision:
def __init__(self, xmlnode):
self.n = xmlnode
def revision(self):
return int(self.n.getAttribute("revision"))
def author(self):
return self.n.getElementsByTagName("author")[0].firstChild.data
def paths(self):
return [self.SvnLogPath(n)
for n in self.n.getElementsByTagName("path")]
class SvnLogPath:
def __init__(self, xmlnode):
self.n = xmlnode
def action(self):
return self.n.getAttribute("action")
def pathid(self):
return self.n.firstChild.data
def copyfrom_rev(self):
try: return self.n.getAttribute("copyfrom-rev")
except KeyError: return None
def copyfrom_pathid(self):
try: return self.n.getAttribute("copyfrom-path")
except KeyError: return None
def get_copyfrom(target):
"""Get copyfrom info for a given target (it represents the directory from
where it was branched). NOTE: repos root has no copyfrom info. In this case
None is returned.
Returns the:
- source file or directory from which the copy was made
- revision from which that source was copied
- revision in which the copy was committed
"""
repos_path = target_to_pathid(target)
for chg in SvnLogParser(launchsvn('log -v --xml --stop-on-copy "%s"'
% target, split_lines=False)):
for p in chg.paths():
if p.action() == 'A' and p.pathid() == repos_path:
# These values will be None if the corresponding elements are
# not found in the log.
return p.copyfrom_pathid(), p.copyfrom_rev(), chg.revision()
return None,None,None
def get_latest_rev(url):
"""Get the latest revision of the repository of which URL is part."""
try:
return get_svninfo(url)["Revision"]
except LaunchError:
# Alternative method for latest revision checking (for svn < 1.2)
report('checking latest revision of "%s"' % url)
L = launchsvn('proplist --revprop -r HEAD "%s"' % opts["source-url"])[0]
rev = re.search("revision (\d+)", L).group(1)
report('latest revision of "%s" is %s' % (url, rev))
return rev
def get_created_rev(url):
"""Lookup the revision at which the path identified by the
provided URL was first created."""
oldest_rev = -1
report('determining oldest revision for URL "%s"' % url)
### TODO: Refactor this to use a modified RevisionLog class.
lines = None
cmd = "log -r1:HEAD --stop-on-copy -q " + url
try:
lines = launchsvn(cmd + " --limit=1")
except LaunchError:
# Assume that --limit isn't supported by the installed 'svn'.
lines = launchsvn(cmd)
if lines and len(lines) > 1:
i = lines[1].find(" ")
if i != -1:
oldest_rev = int(lines[1][1:i])
if oldest_rev == -1:
error('unable to determine oldest revision for URL "%s"' % url)
return oldest_rev
def get_commit_log(url, revnum):
"""Return the log message for a specific integer revision
number."""
out = launchsvn("log --incremental -r%d %s" % (revnum, url))
return recode_stdout_to_file("".join(out[1:]))
def construct_merged_log_message(url, revnums):
"""Return a commit log message containing all the commit messages
in the specified revisions at the given URL. The separator used
in this log message is determined by searching for the longest
svnmerge separator existing in the commit log messages and
extending it by one more separator. This results in a new commit
log message that is clearer in describing merges that contain
other merges. Trailing newlines are removed from the embedded
log messages."""
messages = ['']
longest_sep = ''
for r in revnums.sorted():
message = get_commit_log(url, r)
if message:
message = re.sub(r'(\r\n|\r|\n)', "\n", message)
message = rstrip(message, "\n") + "\n"
messages.append(prefix_lines(LOG_LINE_PREFIX, message))
for match in LOG_SEPARATOR_RE.findall(message):
sep = match[1]
if len(sep) > len(longest_sep):
longest_sep = sep
longest_sep += LOG_SEPARATOR + "\n"
messages.append('')
return longest_sep.join(messages)
def get_default_source(branch_target, branch_props):
"""Return the default source for branch_target (given its branch_props).
Error out if there is ambiguity."""
if not branch_props:
error("no integration info available")
props = branch_props.copy()
pathid = target_to_pathid(branch_target)
# To make bidirectional merges easier, find the target's
# repository local path so it can be removed from the list of
# possible integration sources.
if props.has_key(pathid):
del props[pathid]
if len(props) > 1:
err_msg = "multiple sources found. "
err_msg += "Explicit source argument (-S/--source) required.\n"
err_msg += "The merge sources available are:"
for prop in props:
err_msg += "\n " + prop
error(err_msg)