-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsvn.py
More file actions
1511 lines (1194 loc) · 50.7 KB
/
Copy pathsvn.py
File metadata and controls
1511 lines (1194 loc) · 50.7 KB
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
from __future__ import print_function
import os
import re
import sys
import tempfile
from datetime import datetime, timedelta
from cmdrunner import CommandException, default_returncode_handler, \
run_command, run_generator
from dictobject import DictObject
# Python3 redefined 'unicode' to be 'str'
if sys.version_info[0] >= 3:
unicode = str
LOG_PROP_PAT = re.compile(r"^r(\d+)\s+"
r"\|\s+([^\|]+)\s+"
r"\|\s+([^\|]+)\s+"
r"\|\s+(\d+)\s+lines?\s*$")
LOG_FILE_PAT = re.compile(r"^\s+(\S+)\s+(.*\S)\s*$")
class SVNException(CommandException):
"General Subversion exception"
class SVNBadAncestryException(SVNException):
"Branch/tag does not share common ancestry with repository"
class SVNConnectException(SVNException):
"'svn' could not connect to the remote repository"
class SVNMergeConflictException(SVNException):
"'svn' could merge the requested commit(s) into the sandbox"
class SVNNonexistentException(SVNException):
"Subversion URL is not valid"
def __init__(self, url):
self.url = url
msg = "Bad Subversion URL \"%s\"" % (url, )
super(SVNNonexistentException, self).__init__(msg)
class SVNDate(object):
SVNDATE_PAT = re.compile(r"(\d+-\d+-\d+)\s+(\d+:\d+:\d+)"
r"\s+([\-\+])(\d\d\d\d)(\s+\(.*\))?\s*$")
SQLDATE_PAT = re.compile(r"(\d+-\d+-\d+)\s+(\d+:\d+:\d+)")
DATE_EPOCH = datetime(1970, 1, 1)
def __init__(self, dateobj):
if isinstance(dateobj, datetime):
self.__datetime = dateobj
else:
self.__datetime = self.__string_to_datetime(dateobj)
self.__string = None
self.__float = None
def __str__(self):
return self.string
def __string_to_datetime(self, svn_date):
mtch = self.SVNDATE_PAT.match(svn_date)
if mtch is None:
mtch = self.SQLDATE_PAT.match(svn_date)
if mtch is None:
raise Exception("Bad SVN date \"%s\"" % (svn_date, ))
# parse the date/time string
dttm = datetime.strptime(mtch.group(1) + " " + mtch.group(2),
"%Y-%m-%d %H:%M:%S")
# if no timezone info was included, return the datetime object
if mtch.lastindex <= 2:
return dttm
# validate the timezone string
tzone = mtch.group(4)
if not tzone.startswith("0") or not tzone.endswith("00"):
raise Exception("Bad timezone string \"%s\" in SVN date \"%s\"" %
(tzone, svn_date))
# convert timezone to number of hours
tzval = int(tzone[1])
if mtch.group(3) == "-":
tzval = -tzval
elif mtch.group(3) != "+":
raise Exception("Bad timezone sign \"%s\" in SVN date \"%s\"" %
(mtch.group(3), svn_date))
return dttm + timedelta(hours=tzval)
@property
def datetime(self):
return self.__datetime
@property
def float(self):
if self.__float is None:
self.__float = (self.__datetime - self.DATE_EPOCH).total_seconds()
return self.__float
@property
def string(self):
if self.__string is None:
self.__string = self.__datetime.strftime("%Y-%m-%d %H:%M:%S")
return self.__string
class LogEntry(DictObject):
"""
All information for a single Subversion log entry
"""
def __init__(self, revision, author, date_string, num_lines):
super(LogEntry, self).__init__()
self.revision = revision
self.author = author
svn_date = SVNDate(date_string)
self.date = svn_date.datetime
self.date_string = svn_date.string
self.num_lines = num_lines
self.filedata = []
self.loglines = []
def __str__(self):
"Return a brief description of this entry"
return "r%d l%s [%s] %s" % (self.revision, self.num_lines,
self.author, self.date_string)
def add_filedata(self, modtype, filename):
"Add a tuple containing the modification type and the file name"
self.filedata.append((modtype, filename))
def add_log(self, logline):
"Add a line of text to the log message"
self.loglines.append(logline.rstrip())
def clean_data(self):
"Remove trailing blank lines from the log message"
while len(self.loglines) > 0 and self.loglines[-1] == "":
del self.loglines[-1]
def handle_connect_stderr(cmdname, line, verbose=False):
"Throw a special exception for SVN connection errors"
if verbose:
print("%s!! %s" % (cmdname, line, ), file=sys.stderr)
# E170013: Unable to connect to a repository
conn_err = line.find("E170013: ")
if conn_err >= 0:
raise SVNConnectException(line[conn_err+9:])
# E175012: Connection timed out
conn_err = line.find("E175012: ")
if conn_err >= 0:
raise SVNConnectException(line[conn_err+9:])
# E000110: Error running context: Connection timed out
conn_err = line.find("E000110: ")
if conn_err >= 0 and line.find("Connection timed out") > 0:
raise SVNConnectException(line[conn_err+9:])
if line.find("Not a versioned resource") >= 0:
raise SVNNonexistentException(line)
if line.startswith("svn: ") and \
line.find("connection was closed by server") > 0:
raise SVNConnectException(line[conn_err+4:])
if line.find("could not connect to server") >= 0:
raise SVNConnectException(line)
raise SVNException("%s failed: %s" % (cmdname, line))
def svnadmin_create(project_name, debug=False, dry_run=False, verbose=False):
cmd_args = ("svnadmin", "create", project_name)
run_command(cmd_args, cmdname=" ".join(cmd_args[:2]).upper(), debug=debug,
dry_run=dry_run, verbose=verbose)
def svn_add(filelist, sandbox_dir=None, debug=False, dry_run=False,
verbose=False):
"Add the specified files/directories to the SVN commit"
if isinstance(filelist, (tuple, list)):
if len(filelist) == 0:
raise SVNException("Empty list of files to add")
cmd_args = ["svn", "add"] + filelist
else:
if filelist == "":
raise SVNException("No files to add")
cmd_args = ("svn", "add", unicode(filelist))
run_command(cmd_args, cmdname=" ".join(cmd_args[:2]).upper(),
working_directory=sandbox_dir, debug=debug, dry_run=dry_run,
verbose=verbose)
def handle_chkout_stderr(cmdname, line, verbose=False):
if verbose:
print("%s!! %s" % (cmdname, line))
if line.startswith("svn: warning: "):
print("CHECKOUT WARNING: %s" % (line, ), file=sys.stderr)
return
# E170000: URL doesn't exist
conn_err = line.find("E170000: ")
if conn_err >= 0:
raise SVNNonexistentException(line[conn_err+9:])
if line.startswith("svn: URL ") and line.endswith(" doesn't exist"):
raise SVNNonexistentException(line[5:])
handle_connect_stderr(cmdname, line, verbose=False)
def svn_checkout(svn_url, revision=None, target_dir=None, force=False,
ignore_externals=False, debug=False, dry_run=False,
verbose=False):
"Check out a project in the current directory"
cmd_args = ["svn", "checkout"]
if revision is not None:
cmd_args.append("-r%d" % revision)
if force:
cmd_args.append("--force")
if ignore_externals:
cmd_args.append("--ignore-externals")
cmd_args.append(svn_url)
if target_dir is not None:
cmd_args.append(target_dir)
run_command(cmd_args, cmdname=" ".join(cmd_args[:2]).upper(),
stderr_handler=handle_chkout_stderr, debug=debug,
dry_run=dry_run, verbose=verbose)
def svn_commit(sandbox_dir, commit_message, debug=False, dry_run=False,
verbose=False):
"Commit all changes in the sandbox directory"
if dry_run:
print("SVN COMMIT %s" % (sandbox_dir, ))
return
logfile = tempfile.NamedTemporaryFile(mode="w", delete=False)
try:
# write log message to a temporary file
print(commit_message, file=logfile, end="")
logfile.close()
cmd_args = ("svn", "commit", "-F", logfile.name)
run_command(cmd_args, cmdname=" ".join(cmd_args[:2]).upper(),
working_directory=sandbox_dir, debug=debug,
dry_run=dry_run, verbose=verbose)
finally:
os.unlink(logfile.name)
def svn_copy(source, destination, log_message=None, revision=None,
pin_externals=False, sandbox_dir=None, debug=False,
dry_run=False, verbose=False):
"Copy source file/directory to destination"
logfile = tempfile.NamedTemporaryFile(mode="w", delete=False)
try:
if log_message is not None:
# write log message to a temporary file
print(log_message, file=logfile, end="")
logfile.close()
cmd_args = ["svn", "copy"]
if log_message is not None:
cmd_args.append("-F%s" % logfile.name)
if revision is not None:
cmd_args.append("-r%s" % revision)
if pin_externals:
cmd_args.append("--pin-externals")
cmd_args.append(source)
cmd_args.append(destination)
run_command(cmd_args, cmdname=" ".join(cmd_args[:2]).upper(),
working_directory=sandbox_dir, debug=debug,
dry_run=dry_run, verbose=verbose)
finally:
os.unlink(logfile.name)
def svn_diff(sandbox_dir=None, debug=False, dry_run=False, verbose=False):
"Compare two different revisions of a project"
cmd_args = ["svn", "diff"]
cmdname = " ".join(cmd_args[:2]).upper()
for line in run_generator(cmd_args, cmdname=cmdname,
working_directory=sandbox_dir,
stderr_handler=handle_connect_stderr,
debug=debug, dry_run=dry_run, verbose=verbose):
yield line
def svn_get_externals(svn_url=None, revision=None, sandbox_dir=None,
debug=False, dry_run=False, verbose=False):
"""
Generate a list of tuples containing
(revision, external_url, subdirectory)
"""
try:
for line in svn_propget(svn_url, "svn:externals", revision=revision,
sandbox_dir=sandbox_dir, debug=debug,
dry_run=dry_run, verbose=False):
# Python3 may need to convert bytes to string
try:
line = line.decode("utf-8")
except KeyboardInterrupt:
raise
except:
pass
line = line.rstrip()
if line == "":
continue
flds = line.split()
if len(flds) == 2:
rev = None
fld0 = flds[0]
fld1 = flds[1]
else:
fld0 = fld1 = None
for fld in flds:
if fld.startswith("-r"):
rev = int(fld[2:])
elif fld0 is None:
fld0 = fld
elif fld1 is None:
fld1 = fld
else:
raise SVNException("Bad external definition \"%s\""
" for %s" % (line, svn_url))
if fld0.startswith("http"):
ext_url = fld0
sub_dir = fld1
elif fld1.startswith("http"):
sub_dir = fld0
ext_url = fld1
else:
raise SVNException("Unrecognized externals line \"%s\""
" for %s" % (svn_url, line))
# extract embedded revision
at_sign = ext_url.find("@")
if at_sign > 0:
new_rev = int(ext_url[at_sign+1:])
if rev is not None and rev != new_rev:
raise SVNException("Found multiple revisions in externals"
" line \"%s\" (%s vs %s)" %
(line, rev, new_rev))
rev = new_rev
ext_url = ext_url[:at_sign]
yield (rev, ext_url, sub_dir)
except CommandException as cex:
cexstr = unicode(cex)
if cexstr.find("W200017") >= 0 or cexstr.find("E200017") >= 0:
# return None for projects with no externals
return
raise
def svn_get_properties(sandbox_dir, revision="HEAD", debug=False,
dry_run=False, verbose=False):
"Get the SVN properties for the specified revision"
(state_reading, state_save_author, state_save_date, state_save_log) = \
range(4)
author = None
date = None
log = None
state = state_reading
cmd_args = ("svn", "proplist", "--revprop", "-r", unicode(revision),
"-v", ".")
cmdname = " ".join(cmd_args[:2]).upper()
for line in run_generator(cmd_args, cmdname=cmdname,
working_directory=sandbox_dir,
stderr_handler=handle_connect_stderr,
debug=debug, dry_run=dry_run, verbose=verbose):
if state == state_reading:
svn_idx = line.find("svn:")
if svn_idx >= 0:
propname = line[svn_idx+4:]
if propname == "author":
state = state_save_author
elif propname == "date":
state = state_save_date
elif propname == "log":
state = state_save_log
else:
print("Unknown SVN property \"%s\"" %
(propname, ), file=sys.stderr)
continue
if state == state_save_author:
author = line.strip()
state = state_reading
elif state == state_save_date:
date = line.strip()
state = state_reading
elif state == state_save_log:
if log is None:
log = line.strip()
else:
log += "\n" + line
else:
print("Unknown get_properties state '%s'\n" %
(state, ), file=sys.stderr)
if author is None:
raise SVNException("No svn:author property for rev %s" % revision)
if date is None:
raise SVNException("No svn:date property for rev %s" % revision)
if log is None:
raise SVNException("No svn:log property for rev %s" % revision)
return (author, date, log)
def handle_info_stderr(cmdname, line, verbose=False):
if verbose:
print("%s!! %s" % (cmdname, line))
# E170000: URL doesn't exist
conn_err = line.find("W170000: ")
if conn_err >= 0:
raise SVNNonexistentException(line[conn_err+9:])
# older versions don't include error/warning code, match string instead
if line.find("(Not a valid URL)") > 0:
raise SVNNonexistentException(line)
handle_connect_stderr(cmdname, line, verbose=False)
def svn_info(svn_url=None, revision=None, sandbox_dir=None, debug=False,
dry_run=False, verbose=False):
"""
Return information about the SVN repository at 'svn_url', which is
either a Subversion URL or a path to a Subversion sandbox directory.
If no 'svn_url' is supplied, use the current directory.
"""
if svn_url is None:
svn_url = "."
info = DictObject()
cmd_args = ["svn", "info"]
if revision is None:
cmd_args.append(unicode(svn_url))
else:
cmd_args.append("%s@%d" % (svn_url, revision))
cmdname = " ".join(cmd_args[:2]).upper()
for line in run_generator(cmd_args, cmdname=cmdname,
working_directory=sandbox_dir,
stderr_handler=handle_info_stderr,
debug=debug, dry_run=dry_run, verbose=verbose):
if line == "":
continue
try:
name, value = line.rstrip().split(": ", 1)
except ValueError:
print("Cannot split \"%s\" at colon" % line.rstrip())
raise
info.set_value(name.lower().replace(" ", "_"), value)
if "relative_url" not in info:
if "url" in info and "repository_root" in info:
if not info.url.startswith(info.repository_root):
raise SVNException("Cannot generate Relative URL: URL \"%s\""
" does not start with Root URL \"%s\"" %
(info.url, info.repository_root))
rel_url = "^" + info.url[len(info.repository_root):]
info.set_value("relative_url", rel_url)
return info
class ListHandler(object):
"Retry 'svn ls' command if it times out"
VERBOSE_PAT = None
def __init__(self, svn_url, revision=None, list_verbose=False,
debug=False, dry_run=False, verbose=False):
if svn_url is None:
svn_url = "."
self.__cmd_args = ["svn", "ls", ]
if revision is not None:
self.__cmd_args.append("-r%s" % (revision, ))
if list_verbose:
self.__cmd_args.append("-v")
self.__cmd_args.append(svn_url)
self.__list_verbose = list_verbose
self.__debug = debug
self.__dry_run = dry_run
self.__verbose = verbose
self.__saw_error = False
def handle_rtncode(self, cmdname, rtncode, lines, verbose=False):
if not self.__saw_error:
default_returncode_handler(cmdname, rtncode, lines,
verbose=verbose)
def handle_stderr(self, cmdname, line, verbose=False):
try:
handle_connect_stderr(cmdname, line, verbose=verbose)
except SVNConnectException:
self.__saw_error = True
raise
def run(self):
cmdname = " ".join(self.__cmd_args[:2]).upper()
now_year = None
while True:
for line in run_generator(self.__cmd_args, cmdname,
returncode_handler=self.handle_rtncode,
stderr_handler=self.handle_stderr,
debug=self.__debug,
dry_run=self.__dry_run,
verbose=self.__verbose):
if not self.__list_verbose:
yield line
continue
mtch = self.verbose_pattern().match(line)
if mtch is not None:
size = int(mtch.group(1))
user = mtch.group(2)
month = mtch.group(3)
day = int(mtch.group(4))
year_or_time = mtch.group(5)
filename = mtch.group(6)
if year_or_time.find(":") < 0:
datestr = "%s %d %d" % (month, day, int(year_or_time))
date = datetime.strptime(datestr, "%b %d %Y")
else:
if now_year is None:
now = datetime.now()
now_year = now.year
datestr = "%s %d %d %s" % \
(month, day, now_year, year_or_time)
date = datetime.strptime(datestr, "%b %d %Y %H:%M")
yield (size, user, date, filename)
continue
print("ERROR: Bad verbose listing line: %s" % (line, ),
file=sys.stderr)
# no errors seen, we're done
if not self.__saw_error:
break
# reset flag and try again
self.__saw_error = False
@classmethod
def verbose_pattern(cls):
if cls.VERBOSE_PAT is None:
cls.VERBOSE_PAT = re.compile(r"^\s*(\d+)\s(.*\S)\s+(\S\S\S)"
r"\s(\d\d)\s+(\d\d\d\d|\d\d:\d\d)"
r"\s(.*)\s*$")
return cls.VERBOSE_PAT
def svn_list(svn_url=None, revision=None, list_verbose=False, debug=False,
dry_run=False, verbose=False):
"""
List all entries of the Subversion directory found at 'url'.
If `revision` is None, list the latest entries.
If `revision` is set to a number, list the entries for that revision.
If `list_verbose` is False, return each line of text.
If `list_verbose` is True, parse each line and return a tuple
containing (size_in_bytes, author_name, last_commit_date, filename)
"""
handler = ListHandler(svn_url, revision, list_verbose=list_verbose,
debug=debug, dry_run=dry_run, verbose=verbose)
for list_data in handler.run():
yield list_data
def svn_log(svn_url=None, revision=None, end_revision=None, num_entries=None,
stop_on_copy=False, sandbox_dir=None, debug=False, dry_run=False,
verbose=False):
"""
Return a list of all LogEntry objects, if an SVN revision is specified,
a list with the single LogEntry.
"""
if svn_url is None:
svn_url = "."
# build the command
cmd_args = ["svn", "log", "-v"]
if revision is None:
if end_revision is not None:
raise SVNException("Found end revision %s without start revision" %
(end_revision, ))
else:
if end_revision is None:
cmd_args.append("-r%s" % revision)
else:
cmd_args.append("-r%s:%s" % (revision, end_revision))
if num_entries is not None:
cmd_args.append("-l%d" % int(num_entries))
if stop_on_copy:
cmd_args.append("--stop-on-copy")
cmd_args.append(svn_url)
cmdname = " ".join(cmd_args[:2]).upper()
# set up some constants before we start parsing
(state_initial, state_saw_dashes, state_saw_props, state_file_list,
state_logmsg) = (1, 2, 3, 4, 5)
dashes = "-"*70
# variable holding the current log entry
logentry = None
# parse everything
state = state_initial
for line in run_generator(cmd_args, cmdname=cmdname,
working_directory=sandbox_dir,
stderr_handler=handle_connect_stderr,
debug=debug, dry_run=dry_run, verbose=verbose):
if state == state_initial:
if line.startswith(dashes):
state = state_saw_dashes
if debug:
print(dashes)
continue
if revision is None:
rstr = ""
else:
rstr = " rev %s" % (revision, )
raise SVNException("Bad initial line for %s%s: %s" %
(svn_url, rstr, line, ))
if state == state_saw_dashes:
if line == "":
break
mtch = LOG_PROP_PAT.match(line)
if mtch is None:
if revision is None:
rstr = ""
else:
rstr = " rev %s" % (revision, )
raise SVNException("Bad post-dashes line for %s%s: %s" %
(svn_url, rstr, line, ))
state = state_saw_props
trev = int(mtch.group(1))
tauthor = mtch.group(2)
tdatestr = mtch.group(3)
tnum_lines = int(mtch.group(4))
logentry = LogEntry(trev, tauthor, tdatestr, tnum_lines)
if debug:
print(unicode(logentry))
continue
if state == state_saw_props:
if line.find("Changed paths") >= 0:
state = state_file_list
continue
if revision is None:
rstr = ""
else:
rstr = " rev %s" % (revision, )
raise SVNException("Bad post-properties line for %s%s: %s" %
(svn_url, rstr, line, ))
if state == state_file_list:
if line == "":
state = state_logmsg
continue
mtch = LOG_FILE_PAT.match(line)
if mtch is not None:
modtype = mtch.group(1)
filename = mtch.group(2)
logentry.add_filedata(modtype, filename)
continue
if revision is None:
rstr = ""
else:
rstr = " rev %s" % (revision, )
raise SVNException("Bad file line for %s%s: %s" %
(svn_url, rstr, line, ))
if state == state_logmsg:
if line.startswith(dashes):
state = state_saw_dashes
logentry.clean_data()
yield logentry
logentry = None
continue
logentry.add_log(line)
continue
if logentry is not None:
logentry.clean_data()
yield logentry
def svn_mkdir(dirlist, create_parents=False, sandbox_dir=None, debug=False,
dry_run=False, verbose=False):
"Add the specified directories to the SVN workspace"
if isinstance(dirlist, (tuple, list)):
if len(dirlist) == 0:
raise SVNException("Empty list of files to add")
else:
if dirlist == "":
raise SVNException("No files to add")
dirlist = (unicode(dirlist), )
cmd_args = ["svn", "mkdir"]
if create_parents:
cmd_args.append("--parents")
cmd_args += dirlist
run_command(cmd_args, cmdname=" ".join(cmd_args[:2]).upper(),
working_directory=sandbox_dir, debug=debug, dry_run=dry_run,
verbose=verbose)
def svn_propget(svn_url, propname, revision=None, is_revision_property=False,
sandbox_dir=None, debug=False, dry_run=False, verbose=False):
"Return the value(s) associated with a Subversion property"
if svn_url is None:
svn_url = "."
cmd_args = ["svn", "propget", propname]
if revision is not None:
cmd_args += ("-r", unicode(revision))
if is_revision_property:
cmd_args.append("--revprop")
cmd_args.append(svn_url)
cmdname = " ".join(cmd_args[:2]).upper()
for _ in (0, 1, 2):
try:
for line in run_generator(cmd_args, cmdname=cmdname,
working_directory=sandbox_dir,
stderr_handler=handle_connect_stderr,
debug=debug, dry_run=dry_run,
verbose=verbose):
yield line
break
except SVNConnectException:
continue
def svn_propset(svn_url, propname, value, revision=None, sandbox_dir=None,
debug=False, dry_run=False, verbose=False):
"Set a Subversion property value"
if svn_url is None:
svn_url = "."
if value is None:
raise SVNException("Cannot set property \"%s\" to None for %s" %
(propname, svn_url))
propfile = tempfile.NamedTemporaryFile(mode="w", delete=False)
try:
print(value, end="", file=propfile)
propfile.close()
cmd_args = ["svn", "propset", propname]
if revision is not None:
cmd_args += ("--revprop", "-r", unicode(revision))
cmd_args += ("-F", propfile.name, svn_url)
for line in run_generator(cmd_args,
cmdname=" ".join(cmd_args[:2]).upper(),
working_directory=sandbox_dir,
debug=debug, dry_run=dry_run,
verbose=verbose):
if line.find("set on repository revision %d" % (revision, )) < 0:
raise SVNException("Bad 'propset' reply: %s" % (line, ))
finally:
os.unlink(propfile.name)
def svn_remove(filelist, sandbox_dir=None, debug=False, dry_run=False,
verbose=False):
"Remove the specified files/directories from the SVN commit"
if isinstance(filelist, (tuple, list)):
if len(filelist) == 0:
raise SVNException("Empty list of files to remove")
cmd_args = ["svn", "remove"] + filelist
else:
if filelist == "":
raise SVNException("No files to remove")
cmd_args = ("svn", "remove", unicode(filelist))
run_command(cmd_args, cmdname=" ".join(cmd_args[:2]).upper(),
working_directory=sandbox_dir, debug=debug, dry_run=dry_run,
verbose=verbose)
class AcceptType(object):
POSTPONE = 1
EDIT = 2
LAUNCH = 3
BASE = 4
WORKING = 5
MINE_FULL = 6
THEIRS_FULL = 7
MINE_CONFLICT = 8
THEIRS_CONFLICT = 9
ARGS = ["postpone", "edit", "launch", "base", "working", "mine-full",
"theirs-full", "mine-conflict", "theirs-conflict"]
@classmethod
def to_string(cls, accept_type):
if accept_type < 1 or accept_type >= len(cls.ARGS):
raise Exception("Bad --accept type #%s" % (accept_type, ))
return cls.ARGS[accept_type - 1]
def svn_resolve(accept_type, files=None, sandbox_dir=None, debug=False,
verbose=False):
"Resolve all merge conflicts for the specified files/directories"
cmd_args = ["svn", "resolve",
"--accept", AcceptType.to_string(accept_type)]
if files is not None:
cmd_args += files
for line in run_generator(cmd_args, cmdname=" ".join(cmd_args[:2]).upper(),
working_directory=sandbox_dir, debug=debug,
verbose=verbose):
yield line
def svn_revert(pathlist=None, recursive=False, sandbox_dir=None, debug=False,
dry_run=False, verbose=False):
"Revert all changes in the specified files/directories"
if pathlist is None:
pathlist = (".", )
elif not isinstance(pathlist, (tuple, list)):
pathlist = (unicode(pathlist), )
cmd_args = ["svn", "revert"]
if recursive:
cmd_args.append("-R")
cmd_args += pathlist
run_command(cmd_args, cmdname=" ".join(cmd_args[:2]).upper(),
working_directory=sandbox_dir, debug=debug,
dry_run=dry_run, verbose=verbose)
def svn_status(sandbox_dir=None, debug=False, dry_run=False, verbose=False):
"Return the lines describing the status of the Subversion sandbox"
cmd_args = ["svn", "status"]
for line in run_generator(cmd_args, cmdname=" ".join(cmd_args[:2]).upper(),
working_directory=sandbox_dir, debug=debug,
dry_run=dry_run, verbose=verbose):
yield line
class SwitchHandler(object):
def __init__(self, svn_url=None, revision=None, accept_type=None,
ignore_ancestry=False, ignore_bad_externals=False,
ignore_externals=False, sandbox_dir=None, debug=False,
dry_run=False, verbose=False):
cmd_args = ["svn", "switch"]
if accept_type is not None:
cmd_args += ("--accept", AcceptType.to_string(accept_type))
if ignore_ancestry:
cmd_args.append("--ignore-ancestry")
if ignore_externals:
cmd_args.append("--ignore-externals")
if revision is None:
self.__error_url = svn_url
else:
cmd_args.append("-r%d" % (revision, ))
self.__error_url = "%s -r%s" % (svn_url, revision)
cmd_args.append(unicode(svn_url))
self.__cmd_args = cmd_args
self.__ignore_bad_externals = ignore_bad_externals
self.__sandbox_dir = sandbox_dir
self.__debug = debug
self.__dry_run = dry_run
self.__verbose = verbose
def __handle_stderr(self, cmdname, line, verbose=False):
if verbose:
print("%s!! %s" % (cmdname, line))
if line.startswith("svn: warning: "):
print("SWITCH WARNING: %s" % (line, ), file=sys.stderr)
return
# E160013: File not found
if line.startswith("svn: E160013: ") or \
(line.startswith("svn: Target path ") and
line.endswith(" does not exist")):
if self.__ignore_bad_externals:
return
raise SVNNonexistentException(self.__error_url)
# E195012: Use --ignore-ancestry
if line.startswith("svn: E195012: "):
raise SVNBadAncestryException(self.__error_url)
if line.startswith("svn: E155027: ") or \
line.find("Tree conflict on ") >= 0:
raise SVNMergeConflictException(cmdname)
handle_connect_stderr(cmdname, line, verbose=False)
def run(self):
cmdname = " ".join(self.__cmd_args[:2]).upper()
for line in run_generator(self.__cmd_args, cmdname,
stderr_handler=self.__handle_stderr,
working_directory=self.__sandbox_dir,
debug=self.__debug, dry_run=self.__dry_run,
verbose=self.__verbose):
yield line
def svn_switch(svn_url=None, revision=None, accept_type=None,
ignore_ancestry=False, ignore_bad_externals=False,