-
Notifications
You must be signed in to change notification settings - Fork 196
Expand file tree
/
Copy pathmailer.py
More file actions
executable file
·1621 lines (1336 loc) · 53.4 KB
/
Copy pathmailer.py
File metadata and controls
executable file
·1621 lines (1336 loc) · 53.4 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
# -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
#
# mailer.py: send email describing a commit
#
# $HeadURL$
# $LastChangedDate$
# $LastChangedBy$
# $LastChangedRevision$
#
# USAGE: mailer.py commit REPOS REVISION [CONFIG-FILE]
# mailer.py propchange REPOS REVISION AUTHOR REVPROPNAME [CONFIG-FILE]
# mailer.py propchange2 REPOS REVISION AUTHOR REVPROPNAME ACTION \
# [CONFIG-FILE]
# mailer.py lock REPOS AUTHOR [CONFIG-FILE]
# mailer.py unlock REPOS AUTHOR [CONFIG-FILE]
#
# Using CONFIG-FILE, deliver an email describing the changes between
# REV and REV-1 for the repository REPOS.
#
# ACTION was added as a fifth argument to the post-revprop-change hook
# in Subversion 1.2.0. Its value is one of 'A', 'M' or 'D' to indicate
# if the property was added, modified or deleted, respectively.
#
# See _MIN_SVN_VERSION below for which version of Subversion's Python
# bindings are required by this version of mailer.py.
import os
import sys
if sys.hexversion >= 0x3000000:
PY3 = True
import configparser
from urllib.parse import quote as _url_quote
else:
PY3 = False
import ConfigParser as configparser
from urllib import quote as _url_quote
import time
import subprocess
from io import BytesIO
import smtplib
import re
import tempfile
import codecs
# Minimal version of Subversion's bindings required
_MIN_SVN_VERSION = [1, 5, 0]
# Import the Subversion Python bindings, making sure they meet our
# minimum version requirements.
import svn.fs
import svn.delta
import svn.repos
import svn.core
if _MIN_SVN_VERSION > [svn.core.SVN_VER_MAJOR,
svn.core.SVN_VER_MINOR,
svn.core.SVN_VER_PATCH]:
sys.stderr.write(
"You need version %s or better of the Subversion Python bindings.\n" \
% ".".join([str(x) for x in _MIN_SVN_VERSION]))
sys.exit(1)
# Absorb difference between Python 2 and Python >= 3
if PY3:
def to_bytes(x):
return x.encode('utf-8')
def to_str(x):
return x.decode('utf-8')
# We never use sys.stdin nor sys.stdout TextIOwrapper.
_stdin = sys.stdin.buffer
_stdout = sys.stdout.buffer
else:
# Python 2
def to_bytes(x):
return x
def to_str(x):
return x
_stdin = sys.stdin
_stdout = sys.stdout
SEPARATOR = '=' * 78
def main(pool, cmd, config_fname, repos_dir, cmd_args):
### TODO: Sanity check the incoming args
if cmd == 'commit':
revision = int(cmd_args[0])
repos = Repository(repos_dir, revision, pool)
cfg = Config(config_fname, repos_dir,
{'author': repos.author,
'repos_basename': os.path.basename(repos.repos_dir)
})
messenger = Commit(pool, cfg, repos)
elif cmd == 'propchange' or cmd == 'propchange2':
revision = int(cmd_args[0])
author = cmd_args[1]
propname = cmd_args[2]
if cmd == 'propchange2' and cmd_args[3]:
action = cmd_args[3]
else:
action = 'A'
repos = Repository(repos_dir, revision, pool)
# Override the repos revision author with the author of the propchange
repos.author = author
cfg = Config(config_fname, repos_dir,
{'author': author,
'repos_basename': os.path.basename(repos.repos_dir)
})
messenger = PropChange(cfg, repos, author, propname, action)
elif cmd == 'lock' or cmd == 'unlock':
author = cmd_args[0]
repos = Repository(repos_dir, 0, pool) ### any old revision will do
# Override the repos revision author with the author of the lock/unlock
repos.author = author
cfg = Config(config_fname, repos_dir,
{'author': author,
'repos_basename': os.path.basename(repos.repos_dir)
})
messenger = Lock(pool, cfg, repos, author, cmd == 'lock')
else:
raise UnknownSubcommand(cmd)
output = create_output(cfg, repos)
return messenger.generate(output, pool)
def create_output(cfg, repos):
if cfg.is_set('general.mail_command'):
cls = PipeOutput
elif cfg.is_set('general.smtp_hostname'):
cls = SMTPOutput
else:
cls = StandardOutput
return cls(cfg, repos)
def remove_leading_slashes(path):
while path and path[0:1] == b'/':
path = path[1:]
return path
class Writer:
"Simple class for writing strings/binary, with optional encoding."
def __init__(self, maxbytes, encoding):
self.maxbytes = maxbytes
self.buffer = BytesIO()
# Attach a couple functions to SELF, rather than methods.
self.write_binary = self.buffer.write
if codecs.lookup(encoding) != codecs.lookup('utf-8'):
def _write(s):
"Write text string S using the given encoding."
return self.buffer.write(s.encode(encoding, 'backslashreplace'))
else:
def _write(s):
"Write text string S using the *default* encoding (utf-8)."
return self.buffer.write(to_bytes(s))
def write_limited(s):
# If it looks like this write() will surpass the maximum length,
# then bail out.
if len(self.buffer.getbuffer()) + len(s) > self.maxbytes:
raise MessageTooLarge
return _write(s)
self.write = write_limited
class OutputBase:
"Abstract base class to formalize the interface of output methods"
def __init__(self, cfg, repos):
self.cfg = cfg
self.repos = repos
self._CHUNKSIZE = 128 * 1024
def send(self, subject_line, group, params, long_func, short_func):
### get the MAXBYTEs from the configuration
writer = Writer(90000, self.get_encoding())
try:
try:
long_func(writer)
except MessageTooLarge:
writer.buffer.truncate(0)
writer.buffer.seek(0)
try:
short_func(writer)
except MessageTooLarge:
# NOTE: don't use the Writer() API, or it will check the
# length again. Reach inside.
writer.buffer.write(b'\n\n\n... message too long. Truncated.\n')
# FALLTHRU
except MessageSendFailure:
return True # failed
self.deliver(subject_line, group, params, writer.buffer.getvalue())
return False # succeeded
def get_encoding(self):
"""Get the encoding for text-to-bytes in the output.
This will default to UTF-8. If the output mechanism needs a different
encoding, then override this method to provide the custom encoding.
"""
return 'utf-8'
def deliver(self, subject_line, group, params, body):
"""Override this method.
### FIX THIS DOCSTRING
Begin writing an output representation. SUBJECT_LINE is a subject line
describing the action (commit, properties, lock), which may be tweaked
given other conditions. GROUP is the name of the configuration file
group which is causing this output to be produced. PARAMS is a
dictionary of any named subexpressions of regular expressions defined
in the configuration file, plus the key 'author' contains the author
of the action being reported.
Return bytes() for the prefix of the content to deliver.
"""
raise NotImplementedError
class MailedOutput(OutputBase):
def get_prefix(self, subject_line, group, params):
# whitespace (or another character) separated list of addresses
# which must be split into a clean list
to_addr_in = self.cfg.get('to_addr', group, params)
# if list of addresses starts with '[.]'
# use the character between the square brackets as split char
# else use whitespaces
if len(to_addr_in) >= 3 and to_addr_in[0] == '[' \
and to_addr_in[2] == ']':
self.to_addrs = \
[_f for _f in to_addr_in[3:].split(to_addr_in[1]) if _f]
else:
self.to_addrs = [_f for _f in to_addr_in.split() if _f]
self.from_addr = self.cfg.get('from_addr', group, params) \
or self.repos.author or 'no_author'
# if the from_addr (also) starts with '[.]' (may happen if one
# map is used for both to_addr and from_addr) remove '[.]'
if len(self.from_addr) >= 3 and self.from_addr[0] == '[' \
and self.from_addr[2] == ']':
self.from_addr = self.from_addr[3:]
self.reply_to = self.cfg.get('reply_to', group, params)
# if the reply_to (also) starts with '[.]' (may happen if one
# map is used for both to_addr and reply_to) remove '[.]'
if len(self.reply_to) >= 3 and self.reply_to[0] == '[' \
and self.reply_to[2] == ']':
self.reply_to = self.reply_to[3:]
# Return the prefix for the mail message.
return self.mail_headers(subject_line, group)
def _rfc2047_encode(self, hdr):
# Return the result of splitting HDR into tokens (on space
# characters), encoding (per RFC2047) each token as necessary, and
# slapping 'em back to together again.
from email.header import Header
def _maybe_encode_header(hdr_token):
try:
hdr_token.encode('ascii')
return hdr_token
except UnicodeError:
return Header(hdr_token, 'utf-8').encode()
return ' '.join(map(_maybe_encode_header, hdr.split()))
def mail_headers(self, subject_line, group):
from email import utils
subject = self._rfc2047_encode(subject_line)
from_hdr = self._rfc2047_encode(self.from_addr)
to_hdr = self._rfc2047_encode(', '.join(self.to_addrs))
hdrs = 'From: %s\n' \
'To: %s\n' \
'Subject: %s\n' \
'Date: %s\n' \
'Message-ID: %s\n' \
'MIME-Version: 1.0\n' \
'Content-Type: text/plain; charset=UTF-8\n' \
'Content-Transfer-Encoding: 8bit\n' \
'X-Svn-Commit-Project: %s\n' \
'X-Svn-Commit-Author: %s\n' \
'X-Svn-Commit-Revision: %d\n' \
'X-Svn-Commit-Repository: %s\n' \
% (from_hdr, to_hdr, subject,
utils.formatdate(), utils.make_msgid(), group,
self.repos.author or 'no_author', self.repos.rev,
os.path.basename(self.repos.repos_dir))
if self.reply_to:
hdrs = '%sReply-To: %s\n' % (hdrs, self.reply_to)
return (hdrs + '\n').encode()
class SMTPOutput(MailedOutput):
"Deliver a mail message to an MTA using SMTP."
def deliver(self, subject_line, group, params, body):
"""
Send email via SMTP or SMTP_SSL, logging in if username is
specified.
Errors such as invalid recipient, which affect a particular email,
are reported to stderr and raise MessageSendFailure. If the caller
has other emails to send, it may continue doing so.
Errors caused by bad configuration, such as login failures, for
which too many occurrences could lead to SMTP server lockout, are
reported to stderr and re-raised. These should be considered fatal
(to minimize the chances of said lockout).
"""
prefix = self.get_prefix(subject_line, group, params)
if self.cfg.is_set('general.smtp_port'):
smtp_port = self.cfg.general.smtp_port
else:
smtp_port = 0
try:
if self.cfg.is_set('general.smtp_ssl') and self.cfg.general.smtp_ssl == 'yes':
server = smtplib.SMTP_SSL(self.cfg.general.smtp_hostname, smtp_port)
else:
server = smtplib.SMTP(self.cfg.general.smtp_hostname, smtp_port)
except Exception as detail:
sys.stderr.write("mailer.py: Failed to instantiate SMTP object: %s\n" % (detail,))
# Any error to instantiate is fatal
raise
try:
if self.cfg.is_set('general.smtp_username'):
try:
server.login(self.cfg.general.smtp_username,
self.cfg.general.smtp_password)
except smtplib.SMTPException as detail:
sys.stderr.write("mailer.py: SMTP login failed with username %s and/or password: %s\n"
% (self.cfg.general.smtp_username, detail,))
# Any error at login is fatal
raise
server.sendmail(self.from_addr, self.to_addrs, prefix + body)
### TODO: 'raise .. from' is Python 3+. When we convert this
### script to Python 3, uncomment 'from detail' below
### (2 instances):
except smtplib.SMTPRecipientsRefused as detail:
sys.stderr.write("mailer.py: SMTP recipient(s) refused: %s: %s\n"
% (self.to_addrs, detail,))
raise MessageSendFailure ### from detail
except smtplib.SMTPSenderRefused as detail:
sys.stderr.write("mailer.py: SMTP sender refused: %s: %s\n"
% (self.from_addr, detail,))
raise MessageSendFailure ### from detail
except smtplib.SMTPException as detail:
# All other errors are fatal; this includes:
# SMTPHeloError, SMTPDataError, SMTPNotSupportedError
sys.stderr.write("mailer.py: SMTP error occurred: %s\n" % (detail,))
raise
finally:
try:
server.quit()
except smtplib.SMTPException as detail:
sys.stderr.write("mailer.py: Error occurred during SMTP session cleanup: %s\n"
% (detail,))
class StandardOutput(OutputBase):
"Print the commit message to stdout."
def get_encoding(self):
return sys.stdout.encoding if PY3 else 'utf-8'
def deliver(self, subject_line, group, params, body):
_stdout.write((
("Group: " + (group or "defaults") + "\n")
+ ("Subject: %s\n\n" % (subject_line,))
).encode() ### whoops. use the encoding
+ body)
class PipeOutput(MailedOutput):
"Deliver a mail message to an MTA via a pipe."
def __init__(self, cfg, repos):
MailedOutput.__init__(self, cfg, repos)
# figure out the command for delivery
self.cmd = cfg.general.mail_command.split()
def deliver(self, subject_line, group, params, body):
prefix = self.get_prefix(subject_line, group, params)
### gotta fix this. this is pretty specific to sendmail and qmail's
### mailwrapper program. should be able to use option param substitution
cmd = self.cmd + [ '-f', self.from_addr ] + self.to_addrs
# construct the pipe for talking to the mailer
pipe = subprocess.Popen(cmd, stdin=subprocess.PIPE,
close_fds=sys.platform != "win32")
# Send the content to the mailer, and wait for completion.
pipe.communicate(prefix + body)
class Messenger:
def __init__(self, cfg, repos, prefix_param):
self.cfg = cfg
self.repos = repos
self.prefix_param = prefix_param
# Subclasses should set this instance variable to describe the action
# being performed. See OutputBase.start() docstring.
self.basic_subject = ''
def make_subject(self, basic_subject, group, params):
prefix = self.cfg.get(self.prefix_param, group, params)
if prefix:
subject = prefix + ' ' + basic_subject
else:
subject = basic_subject
try:
truncate_subject = int(
self.cfg.get('truncate_subject', group, params))
except ValueError:
truncate_subject = 0
# truncate subject as UTF-8 string.
# Note: there still exists an issue on combining characters.
if truncate_subject:
bsubject = to_bytes(subject)
if len(bsubject) > truncate_subject:
idx = truncate_subject - 2
while b'\x80' <= bsubject[idx-1:idx] <= b'\xbf':
idx -= 1
subject = to_str(bsubject[:idx-1]) + "..."
return subject
class Commit(Messenger):
def __init__(self, pool, cfg, repos):
Messenger.__init__(self, cfg, repos, 'commit_subject_prefix')
# get all the changes and sort by path
editor = svn.repos.ChangeCollector(repos.fs_ptr, repos.root_this, pool)
e_ptr, e_baton = svn.delta.make_editor(editor, pool)
svn.repos.replay2(repos.root_this, "", svn.core.SVN_INVALID_REVNUM, 1, e_ptr, e_baton, None, pool)
self.changelist = sorted(editor.get_changes().items())
log = to_str(repos.get_rev_prop(svn.core.SVN_PROP_REVISION_LOG, pool) or b'')
# collect the set of groups and the unique sets of params for the options
self.groups = { }
for path, change in self.changelist:
for (group, params) in self.cfg.which_groups(to_str(path), log):
# turn the params into a hashable object and stash it away
param_list = sorted(params.items())
# collect the set of paths belonging to this group
if (group, tuple(param_list)) in self.groups:
old_param, paths = self.groups[group, tuple(param_list)]
else:
paths = { }
paths[path] = None
self.groups[group, tuple(param_list)] = (params, paths)
# figure out the changed directories
dirs = { }
for path, change in self.changelist:
path = to_str(path)
if change.item_kind == svn.core.svn_node_dir:
dirs[path] = None
else:
idx = path.rfind('/')
if idx == -1:
dirs[''] = None
else:
dirs[path[:idx]] = None
dirlist = list(dirs.keys())
commondir, dirlist = get_commondir(dirlist)
# compose the basic subject line. later, we can prefix it.
dirlist_s = ' '.join(sorted(dirlist))
if commondir:
self.basic_subject = 'r%d - in %s: %s' % (repos.rev, commondir, dirlist_s)
else:
self.basic_subject = 'r%d - %s' % (repos.rev, dirlist_s)
def generate(self, output, scratch_pool):
"Generate email for the various groups and option-params."
### the groups need to be further compressed. if the headers and
### body are the same across groups, then we can have multiple To:
### addresses. SMTPOutput holds the entire message body in memory,
### so if the body doesn't change, then it can be sent N times
### rather than rebuilding it each time.
iterpool = svn.core.svn_pool_create(scratch_pool)
failed = False
for (group, param_tuple), (params, paths) in sorted(self.groups.items()):
subject_line = self.make_subject(self.basic_subject, group, params)
def long_commit(writer):
# generate commit message (with diffs) for this group and params
generate_commit(writer, self.cfg, self.repos, self.changelist, False,
group, params, paths, iterpool)
def short_commit(writer):
# generate a shorter message, using URLs instead of diffs
generate_commit(writer, self.cfg, self.repos, self.changelist, True,
group, params, paths, iterpool)
failed |= output.send(subject_line, group, params,
long_commit, short_commit)
svn.core.svn_pool_clear(iterpool)
svn.core.svn_pool_destroy(iterpool)
return failed
class PropChange(Messenger):
def __init__(self, cfg, repos, author, propname, action):
Messenger.__init__(self, cfg, repos, 'propchange_subject_prefix')
self.author = author
self.propname = propname
self.action = action
# collect the set of groups and the unique sets of params for the options
self.groups = { }
for (group, params) in self.cfg.which_groups('', None):
# turn the params into a hashable object and stash it away
param_list = sorted(params.items())
self.groups[group, tuple(param_list)] = params
self.basic_subject = 'r%d - %s' % (repos.rev, propname)
def generate(self, output, scratch_pool):
actions = { 'A': 'added', 'M': 'modified', 'D': 'deleted' }
failed = False
### maybe create an iterpool?
for (group, param_tuple), params in self.groups.items():
subject_line = self.make_subject(self.basic_subject, group, params)
def long_propchange(writer):
writer.write('Author: %s\n'
'Revision: %s\n'
'Property Name: %s\n'
'Action: %s\n'
'\n'
% (self.author, self.repos.rev, self.propname,
actions.get(self.action, 'Unknown (\'%s\')' \
% self.action)))
if self.action == 'A' or self.action not in actions:
writer.write('Property value:\n')
propvalue = self.repos.get_rev_prop(self.propname, scratch_pool)
writer.write(propvalue)
elif self.action == 'M':
writer.write('Property diff:\n')
tempfile1 = tempfile.NamedTemporaryFile()
tempfile1.write(_stdin.read())
tempfile1.flush()
tempfile2 = tempfile.NamedTemporaryFile()
tempfile2.write(self.repos.get_rev_prop(self.propname, scratch_pool))
tempfile2.flush()
for diffs in generate_diff(self.cfg.get_diff_cmd(group, {
'label_from' : 'old property value',
'label_to' : 'new property value',
'from' : tempfile1.name,
'to' : tempfile2.name,
})):
writer.write(to_str(diffs.raw))
failed |= output.send(subject_line, group, params, long_propchange, None)
return failed
def get_commondir(dirlist):
"""Figure out the common portion/parent (commondir) of all the paths
in DIRLIST and return a tuple consisting of commondir, dirlist. If
a commondir is found, the dirlist returned is rooted in that
commondir. If no commondir is found, dirlist is returned unchanged,
and commondir is the empty string."""
if len(dirlist) < 2 or '/' in dirlist:
commondir = ''
newdirs = dirlist
else:
common = dirlist[0].split('/')
for j in range(1, len(dirlist)):
d = dirlist[j]
parts = d.split('/')
for i in range(len(common)):
if i == len(parts) or common[i] != parts[i]:
del common[i:]
break
commondir = '/'.join(common)
if commondir:
# strip the common portion from each directory
l = len(commondir) + 1
newdirs = [ ]
for d in dirlist:
if d == commondir:
newdirs.append('.')
else:
newdirs.append(d[l:])
else:
# nothing in common, so reset the list of directories
newdirs = dirlist
return commondir, newdirs
class Lock(Messenger):
def __init__(self, pool, cfg, repos, author, do_lock):
self.author = author
self.do_lock = do_lock
Messenger.__init__(self, cfg, repos,
(do_lock and 'lock_subject_prefix'
or 'unlock_subject_prefix'))
# read all the locked paths from STDIN and strip off the trailing newlines
self.dirlist = [to_str(x).rstrip() for x in _stdin.readlines()]
# collect the set of groups and the unique sets of params for the options
self.groups = { }
for path in self.dirlist:
for (group, params) in self.cfg.which_groups(path, None):
# turn the params into a hashable object and stash it away
param_list = sorted(params.items())
# collect the set of paths belonging to this group
if (group, tuple(param_list)) in self.groups:
old_param, paths = self.groups[group, tuple(param_list)]
else:
paths = { }
paths[path] = None
self.groups[group, tuple(param_list)] = (params, paths)
commondir, dirlist = get_commondir(self.dirlist)
# compose the basic subject line. later, we can prefix it.
dirlist_s = ' '.join(sorted(dirlist))
if commondir:
self.basic_subject = '%s: %s' % (commondir, dirlist_s)
else:
self.basic_subject = dirlist_s
# The lock comment is the same for all paths, so we can just pull
# the comment for the first path in the dirlist and cache it.
self.lock = svn.fs.svn_fs_get_lock(self.repos.fs_ptr,
to_bytes(self.dirlist[0]),
pool)
def generate(self, output, scratch_pool):
failed = False
for (group, param_tuple), (params, paths) in sorted(self.groups.items()):
subject_line = self.make_subject(self.basic_subject, group, params)
def long_lock(writer):
writer.write('Author: %s\n'
'%s paths:\n' %
(self.author, self.do_lock and 'Locked' or 'Unlocked'))
self.dirlist.sort()
for dir in self.dirlist:
writer.write(' %s\n\n' % dir)
if self.do_lock:
writer.write('Comment:\n%s\n' % (self.lock.comment or ''))
failed |= output.send(subject_line, group, params, long_lock, None)
return failed
class DiffSelections:
def __init__(self, cfg, group, params):
self.add = False
self.copy = False
self.delete = False
self.modify = False
gen_diffs = cfg.get('generate_diffs', group, params)
### Do a little dance for deprecated options. Note that even if you
### don't have an option anywhere in your configuration file, it
### still gets returned as non-None.
if len(gen_diffs):
list = gen_diffs.split(" ")
for item in list:
if item == 'add':
self.add = True
if item == 'copy':
self.copy = True
if item == 'delete':
self.delete = True
if item == 'modify':
self.modify = True
else:
self.add = True
self.copy = True
self.delete = True
self.modify = True
### These options are deprecated
suppress = cfg.get('suppress_deletes', group, params)
if suppress == 'yes':
self.delete = False
suppress = cfg.get('suppress_adds', group, params)
if suppress == 'yes':
self.add = False
class DiffURLSelections:
def __init__(self, cfg, group, params):
self.cfg = cfg
self.group = group
self.params = params
def _get_url(self, action, repos_rev, change):
# The parameters for the URLs generation need to be placed in the
# parameters for the configuration module, otherwise we may get
# KeyError exceptions.
params = self.params.copy()
params['path'] = _url_quote(change.path) if change.path else None
params['base_path'] = (_url_quote(change.base_path)
if change.base_path else None)
params['rev'] = repos_rev
params['base_rev'] = change.base_rev
return self.cfg.get("diff_%s_url" % action, self.group, params)
def get_add_url(self, repos_rev, change):
return self._get_url('add', repos_rev, change)
def get_copy_url(self, repos_rev, change):
return self._get_url('copy', repos_rev, change)
def get_delete_url(self, repos_rev, change):
return self._get_url('delete', repos_rev, change)
def get_modify_url(self, repos_rev, change):
return self._get_url('modify', repos_rev, change)
def generate_commit(writer, cfg, repos, changelist, no_diff_content,
group, params, paths, pool):
svndate = repos.get_rev_prop(svn.core.SVN_PROP_REVISION_DATE, pool)
### pick a different date format?
date = time.ctime(svn.core.secs_from_timestr(svndate, pool))
show_nonmatching_paths = cfg.get('show_nonmatching_paths', group, params) \
or 'yes'
params_with_rev = params.copy()
params_with_rev['rev'] = repos.rev
commit_url = cfg.get('commit_url', group, params_with_rev)
# figure out the lists of changes outside the selected path-space
if len(paths) != len(changelist) and show_nonmatching_paths != 'no':
other_summary = generate_summary(changelist, paths, False)
else:
other_summary = None
if len(paths) != len(changelist) and show_nonmatching_paths == 'yes':
other_diffs = generate_changelist_diffs(cfg, repos, changelist,
no_diff_content, False,
group, params, paths,
date, pool)
else:
other_diffs = None
summary = generate_summary(changelist, paths, True)
data = _data(
author=repos.author,
date=date,
rev=repos.rev,
log=to_str(repos.get_rev_prop(svn.core.SVN_PROP_REVISION_LOG, pool) or b''),
commit_url=commit_url,
summary=summary,
no_diff_content=no_diff_content,
show_nonmatching_paths=show_nonmatching_paths,
other_summary=other_summary,
diffs=generate_changelist_diffs(cfg, repos, changelist,
no_diff_content, True,
group, params, paths, date, pool),
other_diffs=other_diffs,
)
### clean this up in future rev. Just use wb
w = writer.write
wb = writer.write_binary
render_commit(w, wb, data)
def generate_summary(changelist, paths, in_paths):
def gather_info(action):
return _gather_paths(action, changelist, paths, in_paths)
return _data(
added=gather_info(svn.repos.CHANGE_ACTION_ADD),
replaced=gather_info(svn.repos.CHANGE_ACTION_REPLACE),
deleted=gather_info(svn.repos.CHANGE_ACTION_DELETE),
modified=gather_info(svn.repos.CHANGE_ACTION_MODIFY),
)
def _gather_paths(action, changelist, paths, in_paths):
items = [ ]
for path, change in changelist:
if change.action == action and (path in paths) == in_paths:
item = _data(
path=path,
is_dir=change.item_kind == svn.core.svn_node_dir,
props_changed=change.prop_changes,
text_changed=change.text_changed,
copied=(change.action == svn.repos.CHANGE_ACTION_ADD \
or change.action == svn.repos.CHANGE_ACTION_REPLACE) \
and change.base_path,
base_path=remove_leading_slashes(change.base_path),
base_rev=change.base_rev,
)
items.append(item)
return items
def generate_changelist_diffs(cfg, repos, changelist,
no_diff_content, in_paths,
group, params, paths, date, pool):
"This is a generator returning diffs for each change."
diffsels = DiffSelections(cfg, group, params)
diffurls = DiffURLSelections(cfg, group, params)
for path, change in changelist:
diff = diff_url = None
kind = None
label1 = None
label2 = None
src_fname = None
dst_fname = None
binary = None
singular = None
content = None
# just skip directories. they have no diffs.
if change.item_kind == svn.core.svn_node_dir:
continue
# is this change in (or out of) the set of matched paths?
if (path in paths) != in_paths:
continue
if change.base_rev != -1:
svndate = repos.get_rev_prop(svn.core.SVN_PROP_REVISION_DATE,
pool, change.base_rev)
### pick a different date format?
base_date = time.ctime(svn.core.secs_from_timestr(svndate, pool))
else:
base_date = ''
# figure out if/how to generate a diff
base_path_bytes = remove_leading_slashes(change.base_path)
base_path = (to_str(base_path_bytes)
if base_path_bytes is not None else None)
if change.action == svn.repos.CHANGE_ACTION_DELETE:
# it was delete.
kind = 'D'
# get the diff url, if any is specified
diff_url = diffurls.get_delete_url(repos.rev, change)
# show the diff?
if diffsels.delete:
diff = svn.fs.FileDiff(repos.get_root(change.base_rev),
base_path_bytes, None, None, pool)
label1 = '%s\t%s\t(r%s)' % (base_path, date, change.base_rev)
label2 = '/dev/null\t00:00:00 1970\t(deleted)'
singular = True
elif change.action == svn.repos.CHANGE_ACTION_ADD \
or change.action == svn.repos.CHANGE_ACTION_REPLACE:
if base_path and (change.base_rev != -1):
# any diff of interest?
if change.text_changed:
# this file was copied and modified.
kind = 'W'
# get the diff url, if any is specified
diff_url = diffurls.get_copy_url(repos.rev, change)
# show the diff?
if diffsels.modify:
diff = svn.fs.FileDiff(repos.get_root(change.base_rev),
base_path_bytes,
repos.root_this, change.path,
pool)
label1 = ('%s\t%s\t(r%s, copy source)'
% (base_path, base_date, change.base_rev))
label2 = ('%s\t%s\t(r%s)'
% (to_str(change.path), date, repos.rev))
singular = False
else:
# this file was copied.
kind = 'C'
if diffsels.copy:
diff = svn.fs.FileDiff(None, None, repos.root_this,
change.path, pool)
label1 = ('/dev/null\t00:00:00 1970\t'
'(empty, because file is newly added)')
label2 = ('%s\t%s\t(r%s, copy of r%s, %s)'
% (to_str(change.path),
date, repos.rev, change.base_rev,
base_path))
singular = False
else:
# the file was added.
kind = 'A'
# get the diff url, if any is specified
diff_url = diffurls.get_add_url(repos.rev, change)
# show the diff?
if diffsels.add:
diff = svn.fs.FileDiff(None, None, repos.root_this,
change.path, pool)
label1 = '/dev/null\t00:00:00 1970\t' \
'(empty, because file is newly added)'
label2 = '%s\t%s\t(r%s)' \
% (to_str(change.path), date, repos.rev)
singular = True
elif not change.text_changed:
# the text didn't change, so nothing to show.
continue
else:
# a simple modification.
kind = 'M'
# get the diff url, if any is specified
diff_url = diffurls.get_modify_url(repos.rev, change)
# show the diff?
if diffsels.modify:
diff = svn.fs.FileDiff(repos.get_root(change.base_rev),
base_path,
repos.root_this, change.path,
pool)
label1 = '%s\t%s\t(r%s)' \
% (base_path, base_date, change.base_rev)
label2 = '%s\t%s\t(r%s)' \
% (to_str(change.path), date, repos.rev)
singular = False