-
Notifications
You must be signed in to change notification settings - Fork 4
/
pwcli
executable file
·3668 lines (2711 loc) · 118 KB
/
pwcli
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 python3
#
# Copyright (c) 2015-2019, The Linux Foundation.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
import logging
import sys
import subprocess
import argparse
import os
import configparser
import email
import email.mime.text
import email.header
import email.utils
import smtplib
import pprint
import re
import timeit
import textwrap
import collections
import string
import datetime
import platform
import socket
import functools
import traceback
import mailbox
import requests
import shutil
import queue
import threading
import readline
assert readline # to shut up pyflakes
PWCLI_VERSION = '0.1.1-git'
PWCLI_PROJECT_URL = 'https://github.com/kvalo/pwcli/'
PWCLI_USER_AGENT = 'pwcli/%s (%s) Python/%s' % (PWCLI_VERSION,
PWCLI_PROJECT_URL,
platform.python_version())
PWCLI_EDIT_FILE = '.pwcli-edit'
DEFAULT_EDITOR = 'nano'
PATCHWORK_API_DIRECTORY = 'api/1.2'
# global variables
logger = logging.getLogger('pwcli')
LOG_SEPARATOR = '\n---\n'
MAIL_BODY_WIDTH = 72
PATCH_STATE_NEW = 'new'
PATCH_STATE_UNDER_REVIEW = 'under-review'
PATCH_STATE_ACCEPTED = 'accepted'
PATCH_STATE_REJECTED = 'rejected'
PATCH_STATE_RFC = 'rfc'
PATCH_STATE_NOT_APPLICABLE = 'not-applicable'
PATCH_STATE_CHANGES_REQUESTED = 'changes-requested'
PATCH_STATE_AWAITING_UPSTREAM = 'awaiting-upstream'
PATCH_STATE_SUPERSEDED = 'superseded'
PATCH_STATE_DEFERRED = 'deferred'
# special state to print patches in pending branch
PATCH_STATE_PENDING = 'pending'
PATCH_ACTIVE_STATES = [PATCH_STATE_NEW,
PATCH_STATE_UNDER_REVIEW,
PATCH_STATE_AWAITING_UPSTREAM,
PATCH_STATE_DEFERRED]
PATCH_ALLOWED_STATES = [PATCH_STATE_NEW,
PATCH_STATE_UNDER_REVIEW,
PATCH_STATE_ACCEPTED,
PATCH_STATE_REJECTED,
PATCH_STATE_RFC,
PATCH_STATE_NOT_APPLICABLE,
PATCH_STATE_AWAITING_UPSTREAM,
PATCH_STATE_DEFERRED,
PATCH_STATE_PENDING]
OLD_PATCH_STATE_MAP = {
PATCH_STATE_NEW: 'New',
PATCH_STATE_UNDER_REVIEW: 'Under Review',
PATCH_STATE_ACCEPTED: 'Accepted',
PATCH_STATE_REJECTED: 'Rejected',
PATCH_STATE_RFC: 'RFC',
PATCH_STATE_NOT_APPLICABLE: 'Not Applicable',
PATCH_STATE_CHANGES_REQUESTED: 'Changes Requested',
PATCH_STATE_AWAITING_UPSTREAM: 'Awaiting Upstream',
PATCH_STATE_SUPERSEDED: 'Superseded',
PATCH_STATE_DEFERRED: 'Deferred',
}
STATE_ABORTED = 'Aborted'
PATCHINDEX_ALL = 'all'
ACKED_BY = r'^Acked-by:'
REVIEWED_BY = r'^Reviewed-by:'
TESTED_BY = r'^Tested-by:'
def clean(buf):
# FIXME: is this translate call really needed, for example in
# emails? And is the whole clean() function useless?
# buf = buf.translate(None, '\n\t')
buf = buf.strip()
return buf
def pretty(obj):
return pprint.pformat(obj, indent=4)
def get_patches_plural(count, capitalize=True):
if count > 1:
return '%d patches' % (count)
single = 'patch'
if capitalize:
single = single.capitalize()
return single
# parses a string like '1-3,5' and returns the indexes in a list [1, 2, 3, 5]
def parse_list(arg):
ids = []
if arg.find(' ') != -1:
raise PwcliError('Spaces are not allowed in an index list: %s' % (arg))
if len(arg) == 0:
return []
entries = arg.split(',')
for entry in entries:
(start_str, sep, end_str) = entry.partition('-')
if not start_str.isdigit():
raise PwcliError('Not a digit: %s' % (start_str))
start = int(start_str)
if sep != '-':
# entry is just one value
ids.append(start)
continue
# entry is a region
if not end_str.isdigit():
raise PwcliError('Not a digit: %s' % (end_str))
end = int(end_str)
# when we say 0-5 we also want the index 5, not just 0-4
end += 1
ids += list(range(start, end))
ids = sorted(ids)
# remove duplicate entries (didn't find any clever way to do this)
#
# remember to copy the list as you cannot modify the list you are
# currently iterating!
prev = None
for val in list(ids):
if val == prev:
ids.remove(val)
continue
prev = val
return ids
# Note: cannot use textwrap.shorten() as it drops entire words, this
# works per character to maximise the use of space
def shrink(s, width, ellipsis=True):
ELLIPSIS = '...'
if width <= 0:
return ''
if len(s) <= width:
return s
if not ellipsis:
return s[:width]
if width <= len(ELLIPSIS):
return ''
s = s[:width - len(ELLIPSIS)]
# if the last character is a space for readability replace it with
# a dot
if s[-1] == ' ':
s = s[:-1]
s += '.'
s += ELLIPSIS
return s
def utcnow():
if 'PWCLI_HARDCODE_DATE' in os.environ:
return datetime.datetime.strptime(os.environ['PWCLI_HARDCODE_DATE'],
'%Y-%m-%dT%H:%M:%S')
return datetime.datetime.utcnow()
def get_age(date):
delta = utcnow() - date
if delta.days >= 2 * 12 * 30:
# over 2 years
return '%dy' % (delta.days // 365)
elif delta.days >= 30:
return '%dm' % (delta.days // 30)
elif delta.days > 0:
return '%dd' % (delta.days)
elif delta.seconds >= 3600:
return '%dh' % (delta.seconds // 3600)
else:
return '0h'
class Timer():
def start(self):
self.start_time = timeit.default_timer()
def stop(self):
self.end_time = timeit.default_timer()
def get_seconds(self):
return '{:.3f}s'.format(self.end_time - self.start_time)
class PwcliError(Exception):
pass
class RunProcess():
# subprocess.Popen() throws OSError if the command is not found
def __init__(self, args, stdout_cb=None, input=None):
self.args = args
self.stdout_cb = stdout_cb
self.input = input
self.returncode = None
self.stdoutdata = ''
self.stderrdata = ''
self.timer = Timer()
self.timer.start()
# universal_newlines=True switches to unicode
self.p = subprocess.Popen(args,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True)
if input:
self.p.stdin.write(input)
# need to close stdin after writing everything, otherwise
# reading output will block
self.p.stdin.close()
lines = iter(self.p.stdout.readline, '')
for line in lines:
self.stdoutdata += line
if stdout_cb:
stdout_cb(line)
self.stderrdata = self.p.stderr.read()
self.p.stdout.close()
self.p.stderr.close()
self.returncode = self.p.wait()
self.timer.stop()
logger.info('%s took %s: %s' %
(self, self.timer.get_seconds(), self.returncode))
logger.debug('stdout: %r' % self.stdoutdata)
logger.debug('stderr: %r' % self.stderrdata)
def __str__(self):
if self.input:
input_len = '%d B' % (len(self.input))
else:
input_len = 'None'
return 'RunProcess(\'%s\', %s, %s)' % (' '.join(self.args),
self.stdout_cb,
input_len)
def __repr__(self):
return 'RunProcess(%r, %r, %r)' % (self.args,
self.stdout_cb,
self.input)
class GitError(Exception):
def __str__(self):
return self.msg
def __init__(self, msg, log=''):
self.msg = msg
self.log = log
class GitCommit(object):
# stg-show doesn't support --format so have to have separate
# parser for it, cannot use parse_simple_format(). But a problem
# might be if user has enabled custom output formats in git, this
# function might easily fail on that.
@staticmethod
def parse_stg_show(text):
commit = GitCommit()
match = re.search(r'^commit ([0-9a-f]{40})', text.splitlines()[0],
re.MULTILINE)
if match is None:
raise GitError('commit id not found')
commit.commit_id = match.group(1)
match = re.search(r'^\s*Patchwork-Id:\s*(\d+)$', text, re.MULTILINE)
if match is not None:
try:
commit.patchwork_id = int(match.group(1))
except Exception as e:
raise GitError('failed to parse patchwork id: %s' % (e))
# '*?' is non-greedy
match = re.search(r'\n\n\s\s\s\s(.*?)\n\s\s\s\s\n(\s\s\s\s.*\n)\n[^\s]', text,
re.MULTILINE | re.DOTALL)
# TODO: make title and log parsing optionally because tests
# fail, most likely because stubs return the patch in wrong
# format (or something). But that should be fixed and we
# should throw GitError() if the patch is not in correct
# format.
if match is not None:
commit.title = match.group(1)
commit.log = re.sub(r'\s\s\s\s(.*?)\n', r'\1\n', match.group(2))
return commit
# the simple format is:
#
# commit <full commitid>
# <title>
# <empty line>
# <rest is commit log>
#
@staticmethod
def parse_simple_format(text):
commit = GitCommit()
match = re.search(r'^commit ([0-9a-f]{40})$', text.splitlines()[0])
if match is None:
raise GitError('commit id not found')
commit.commit_id = match.group(1)
commit.title = text.splitlines()[1]
commit.log = '\n'.join(text.splitlines()[3:])
match = re.search(r'^\s*Patchwork-Id:\s*(\d+)$', commit.log, re.MULTILINE)
if match is not None:
try:
commit.patchwork_id = int(match.group(1))
except Exception as e:
raise GitError('failed to parse patchwork id: %s' % (e))
return commit
def __str__(self):
return 'GitCommit(title=\'%s\', id=\'%s\', patchwork_id=\'%d\')' % \
(self.title, self.commit_id, self.patchwork_id)
def __init__(self):
self.commit_id = None
self.patchwork_id = None
self.title = None
self.log = None
class Stg():
def rollback(self):
cmd = ['stg', 'delete', '--top']
logger.debug('stg.rollback():')
p = RunProcess(cmd)
ret = p.returncode
logger.debug('%s returned: %s' % (cmd, ret))
if ret != 0:
raise GitError('%s failed: %s' % (cmd, ret), log=p.stderrdata)
def get_name_for_patch(self, patch_id):
for p in self.get_series():
commit = self.get_commit(p)
if patch_id == commit.patchwork_id:
return p
return None
def delete_patch(self, patch_id):
pname = self.get_name_for_patch(patch_id)
if pname is None:
logger.debug('stg.delete(): %s not found', patch_id)
return
cmd = ['stg', 'delete', pname]
p = RunProcess(cmd)
ret = p.returncode
logger.debug('%s returned: %s' % (cmd, ret))
if ret != 0:
raise GitError('%s failed: %s' % (cmd, ret), log=p.stderrdata)
def import_patch(self, mbox):
cmd = ['stg', 'import', '--mbox', '--sign']
logger.debug('stg.import_patch(): %s' % (mbox))
p = RunProcess(cmd, input=mbox)
ret = p.returncode
logger.debug('%s returned: %s' % (cmd, ret))
if ret != 0:
raise GitError('%s failed: %s' % (cmd, ret), log=p.stderrdata)
def get_series(self):
cmd = ['stg', 'series', '--noprefix', '--all']
p = RunProcess(cmd)
if p.returncode != 0:
raise GitError('stg series failed: %d' % (p.returncode),
log=p.stderrdata)
output = p.stdoutdata.strip()
result = output.splitlines()
logger.debug('stg.get_series(): %s', result)
return result
def get_commit(self, patchname):
cmd = ['stg', 'show', patchname]
p = RunProcess(cmd)
if p.returncode != 0:
raise GitError('stg show failed: %d' % (p.returncode),
log=p.stderrdata)
try:
return GitCommit.parse_stg_show(p.stdoutdata)
except Exception as e:
raise GitError('Failed to parse patch %s: %s' % (patchname, e))
def __init__(self, output):
self.output = output
class Git():
def rollback(self):
cmd = ['git', 'reset', '--hard', 'HEAD^']
logger.debug('git.rollback():')
p = RunProcess(cmd)
ret = p.returncode
logger.debug('%s returned: %s' % (cmd, ret))
if ret != 0:
raise GitError('%s failed: %s' % (cmd, ret), log=p.stderrdata)
def get_commit(self, commitid):
cmd = ['git', 'show', '--format=commit %H%n%s%n%n%b',
'--no-patch', commitid]
p = RunProcess(cmd)
if p.returncode != 0:
raise GitError('git show failed: %d' % (p.returncode),
log=p.stderrdata)
try:
return GitCommit.parse_simple_format(p.stdoutdata)
except Exception as e:
raise GitError('Failed to parse commit %s: %s' % (commitid, e))
def show_signature(self, commitid):
cmd = ['git', 'show', '--format=', '--no-patch', '--show-signature',
commitid]
p = RunProcess(cmd)
if p.returncode != 0:
raise GitError('git show --show-signature failed: %d' % (p.returncode),
log=p.stderrdata)
return p.stdoutdata.strip()
def log_oneline(self, max_count):
# should try to disable all possible customisations but didn't
# figure out yet, so just disable decoration for now
cmd = ['git', 'log', '--oneline', '--reverse', '--no-decorate',
'--max-count', str(max_count)]
p = RunProcess(cmd)
if p.returncode != 0:
raise GitError('git log --oneline failed: %d' % (p.returncode),
log=p.stderrdata)
return p.stdoutdata.strip()
def get_config(self, config):
cmd = ['git', 'config', '--get', config]
p = RunProcess(cmd)
if p.returncode != 0:
# if the command fails, assume that it's not set and return None
logger.debug('Failed to get git config for %r: %d' % (config,
p.returncode))
return None
return p.stdoutdata.strip()
def get_branch(self):
cmd = ['git', 'branch']
p = RunProcess(cmd)
if p.returncode != 0:
raise GitError('git branch failed: %d' % (p.returncode),
log=p.stderrdata)
output = p.stdoutdata
# the current branch is prefixed with '*'
for line in output.splitlines():
tokens = line.split()
if tokens[0] == '*' and len(tokens) > 1:
return tokens[1]
return None
def update_commit_log(self, title, log):
full_log = '%s\n\n%s' % (title, log)
cmd = ['git', 'commit', '--amend', '--file=-']
p = RunProcess(cmd, input=full_log)
if p.returncode != 0:
raise GitError('Commit log update failed: %d' % (p.returncode),
log=p.stderrdata)
def remove_tag(self, tag):
commit = self.get_commit('HEAD')
pattern = r'^%s.*\n' % (tag)
log = re.sub(pattern, '', commit.log, flags=re.MULTILINE)
self.update_commit_log(commit.title, log)
def add_tag(self, tag):
commit = self.get_commit('HEAD')
# Newline in the end is important, a commit log should end
# with a newline.
log = '%s%s\n' % (commit.log, tag)
self.update_commit_log(commit.title, log)
def cherry_pick(self, commit_id):
cmd = ['git', 'cherry-pick', commit_id]
p = RunProcess(cmd)
if p.returncode != 0:
# FIXME: if the cherry-pick fails (conflicts or whatnot) we
# should run git cherry-pick --abort to cleanup
raise GitError('git cherry-pick failed: %d' % (p.returncode),
log=p.stderrdata)
def checkout(self, branch):
cmd = ['git', 'checkout', branch]
p = RunProcess(cmd)
if p.returncode != 0:
raise GitError('git checkout failed: %d' % (p.returncode),
log=p.stderrdata)
def pull(self, url):
cmd = ['git', 'pull', '--no-edit', '--no-ff', '--stat', '--cleanup=strip'] + \
url.split(' ')
p = RunProcess(cmd)
if p.returncode != 0:
raise GitError('git pull failed: %d' % (p.returncode),
log=p.stderrdata)
return p.stdoutdata.strip()
def am(self, mbox):
cmd = ['git', 'am', '-s', '-3']
p = RunProcess(cmd, input=mbox)
ret = p.returncode
logger.debug('%s returned: %s' % (cmd, ret))
if ret != 0:
abort_cmd = ['git', 'am', '--abort']
logger.debug('Aborting git am: %s' % abort_cmd)
RunProcess(abort_cmd)
clean_cmd = ['git', 'checkout', '-f']
logger.debug('Cleaning working tree: %s' % clean_cmd)
RunProcess(clean_cmd)
log = p.stderrdata
# At least with 1.7.9.5 all errors are output just to stdout
# so add that to the log. Just remove the help messages from
# the end, they don't provide any real value in this case:
#
# When you have resolved this problem run "git am --resolved".
# If you would prefer to skip this patch, instead run "git am --skip".
# To restore the original branch and stop patching run "git am --abort".
#
log += re.sub(r'When you have resolved.*$', '', p.stdoutdata,
flags=re.MULTILINE | re.DOTALL)
raise GitError('%s failed: %s' % (cmd, ret), log=log)
def __init__(self, output):
self.output = output
@functools.total_ordering
class Patch():
def get_name_original(self):
return self._name
def get_name(self):
if self.pending_commit is not None:
name = ''
# get tags (eg. "[RFC,7/9]" from the original title
if self.get_tags() is not None:
name += '%s ' % (self.get_tags())
name += self.pending_commit.title
return name
elif self._name_new is not None:
return self._name_new
else:
return self.get_name_original()
def get_tags(self):
match = re.match(r'^\s*(\[.*?\])', self.get_name_original())
if match is None:
return None
return match.group(1)
def get_id(self):
return self._id
def get_delegate(self):
return self._delegate_username
def set_delegate(self, delegate_name):
self.pw.update_patch(self.get_id(), delegate=delegate_name)
self._delegate_username = delegate_name
logger.debug('%s delegated to %s' % (self.get_id(), delegate_name))
def get_submitter(self):
return '%s <%s>' % (self._submitter_name, self._submitter_email)
def get_submitter_name(self):
# sometimes there might not be a name and only email, return
# only empty string in that case
if self._submitter_name is None:
return ''
return self._submitter_name
def get_date(self):
return self._date
def get_date_pretty(self):
# patchwork uses T to separate date and time, convert that to space
return self.get_date().replace('T', ' ')
def get_datetime(self):
return datetime.datetime.strptime(self.get_date(), '%Y-%m-%dT%H:%M:%S')
def get_age(self):
return get_age(self.get_datetime())
def get_state_name(self):
return self._state
# returns legacy state names, for avoiding major changes in
# automatic test output
def get_state_name_old(self):
return OLD_PATCH_STATE_MAP[self.get_state_name()]
def set_state_name(self, state_name):
self.pw.update_patch(self.get_id(), state=state_name)
self._state = state_name
logger.debug('%s state changed to %s' % (self.get_id(), state_name))
def get_commit_ref(self):
return self._commit_ref
def set_commit_ref(self, commit_ref):
self.pw.update_patch(self.get_id(), commit_ref=commit_ref)
self._commit_ref = commit_ref
logger.debug('%s: commit_ref change to %s' % (self, commit_ref))
def get_pull_url(self):
return self._pull_url
def get_url(self):
return self._web_url
def get_message_id(self):
# remove '<' and '>' chars, we don't want to use them
return self._msgid[1:-1]
def get_mbox(self):
if self.mbox is None:
logger.debug('patch_get_mbox(%s)' % self.get_id())
self.mbox = self.pw.get_mbox(self._mbox_url)
logger.debug(repr(self.mbox))
# Note: the returned type is unicode
return self.mbox
# removes all extra '[ ]' tags _before_ the actual title
def clean_subject(self, subject):
# Note: '.*?' is a non-greedy version of '.*'
return re.sub(r'^\s*(\[.*?\]\s*)*', '', subject)
def get_mbox_for_stgit(self):
msg = self.get_email()
payload = msg.get_payload()
# add Patchwork-Id with s/^---\n/Patchwork-Id: 1001\n---\n
id_line = '\nPatchwork-Id: %s\n---\n' % (self.get_id())
payload = re.sub(r'\n---\n', id_line, payload)
msg.set_payload(payload)
subject = self.clean_subject(msg['Subject'])
msg.replace_header('Subject', subject)
# Add a From header with unixfrom so that this is valid mbox
# format, strangely patchwork doesn't add it.
mbox = msg.as_string(unixfrom=True)
return mbox
def set_mbox(self, mbox):
logger.debug('%s: set_mbox(): %s' % (self, repr(mbox)))
self.mbox = mbox
# need to also update the name from mbox
msg = self.get_email()
# if Subject is long email.message.Message splits it into
# multiple lines, fix that by removing newlines
self._name_new = msg['Subject'].replace('\n', '')
def get_diffstat(self):
p = RunProcess(['diffstat', '-p1'], input=self.get_mbox())
diffstat = p.stdoutdata
diffstat = diffstat.rstrip()
return diffstat
# Note: this returns email.Message object, NOT email address
#
# TODO: rename the function to avoid confusion
def get_email(self):
return email.message_from_string(self.get_mbox())
def get_reply_msg(self, from_name, from_email, text='', signature=None):
msg = self.get_email()
# create body
quote = []
from_entries = email.header.decode_header(msg['From'])
logger.debug('from_entries %r' % (from_entries))
who = str(email.header.make_header(from_entries))
if who:
quote.append('%s wrote:' % (who))
quote.append('')
for line in self.get_log().splitlines():
quote.append('> %s' % line)
quote.append('')
body = '\n'.join(quote)
# empty line after the quote
body += '\n'
body += text
if signature:
t = string.Template(signature)
s = t.substitute(URL=self.get_url())
body += '-- \n%s\n' % (s)
logger.debug('body=%s', repr(body))
# avoid base64 encoding, a tip from http://bugs.python.org/issue12552
email.charset.add_charset('utf-8', email.charset.SHORTEST)
reply = email.mime.text.MIMEText(body, _charset='utf-8')
# create cc list
persons = []
if 'To' in msg:
persons += msg['To'].split(',')
if 'Cc' in msg:
persons += msg['Cc'].split(',')
cc = []
for person in persons:
person = clean(person)
# don't add my email in cc field
if person.count(from_email) > 0:
continue
cc.append(person)
from_hdr = '%s <%s>' % (from_name, from_email)
subject_hdr = 'Re: %s' % clean(msg['Subject'])
to_hdr = clean(msg['From'])
cc_hdr = ', '.join(cc)
reply['Subject'] = subject_hdr
reply['From'] = from_hdr
reply['In-Reply-To'] = msg['Message-Id']
reply['References'] = msg['Message-Id']
reply['To'] = to_hdr
if len(cc_hdr) > 0:
reply['Cc'] = cc_hdr
user_agent = PWCLI_USER_AGENT
if 'PWCLI_CENSOR_USER_AGENT' in os.environ:
# censor the string from all changing version numbers (pwcli
# _and_ python) so that it doesn't change the test output
user_agent = re.sub(r'(pwcli/)[0-9\.\-git]+', r'\1<censored>',
user_agent)
user_agent = re.sub(r'(Python/)[0-9\.]+', r'\1<censored>',
user_agent)
reply['User-Agent'] = user_agent
logger.debug('%s().get_reply_msg(): %s', self, repr(quote))
return reply
def get_log(self):
if self.pending_commit is not None:
log = self.pending_commit.log
# remove Patchwork-Id
log = re.sub(r'\n\s*Patchwork-Id:\s*\d+\s*\n', '\n', log)
else:
msg = self.get_email()
payload = msg.get_payload()
(log, sep, patch) = payload.partition(LOG_SEPARATOR)
return log.strip()
# Tries to guess the patch number (eg 5 from 5/10) from the name
# and returns that as int. If no index found returns None.
def get_patch_index(self):
# Note: '.*?' is a non-greedy version of '.*'
match = re.search(r'^\s*\[.*?(\d+)/\d+.*?]', self.get_name_original())
if match is None:
return None
return int(match.group(1))
def get_series_id(self):
return self._series_id
def set_series(self, series):
self._series = series
def get_series(self):
return self._series
def set_comments(self, comments):
self._comments = comments
def get_comments(self):
return self._comments
def get_comment_count(self):
if self._comments is None:
return 0
return self._comments.get_count()
def get_acked_by_count(self):
if self._comments is None:
return 0
return self._comments.get_acked_by_count()
def get_reviewed_by_count(self):
if self._comments is None:
return 0
return self._comments.get_reviewed_by_count()