-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathviews.py
More file actions
1784 lines (1570 loc) · 64.2 KB
/
Copy pathviews.py
File metadata and controls
1784 lines (1570 loc) · 64.2 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
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.db import connection, transaction
from django.db.models import Count, Q
from django.http import (
Http404,
HttpResponse,
HttpResponseForbidden,
HttpResponseRedirect,
)
from django.shortcuts import get_object_or_404, render
from django.utils import timezone
from django.views.decorators.csrf import csrf_exempt
import collections
import hmac
import json
import urllib
from datetime import datetime, timedelta
from email.mime.text import MIMEText
from email.utils import formatdate, make_msgid
from pgcommitfest.mailqueue.util import send_mail, send_simple_mail
from pgcommitfest.userprofile.models import UserProfile
from pgcommitfest.userprofile.util import UserWrapper
from .ajax import _archivesAPI, doAttachThread, refresh_single_thread
from .feeds import ActivityFeed
from .forms import (
BulkEmailForm,
CommentForm,
CommitFestFilterForm,
NewPatchForm,
PatchForm,
)
from .models import (
CfbotBranch,
CfbotTask,
CommitFest,
Committer,
MailThread,
Patch,
PatchHistory,
PatchOnCommitFest,
Tag,
UserInputError,
)
def get_tags_data():
"""Generate JSON data for enhanced selectize dropdown with tag colors and descriptions."""
return json.dumps(
[
{
"id": tag.id,
"name": tag.name,
"color": tag.color,
"description": tag.description,
}
for tag in Tag.objects.all().order_by("name")
]
)
@transaction.atomic
def home(request):
curs = connection.cursor()
# Make sure the that all the queries work on the same snapshot. Needs to be
# first in the transaction.atomic decorator.
curs.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ")
cfs = CommitFest.relevant_commitfests()
context = {
"cfs": cfs,
"header_activity": "Activity log",
"header_activity_link": "/activity/",
}
# Add dashboard content for logged-in users
if request.user.is_authenticated:
# Check if user is experienced (has been active for a while)
# Consider user experienced if they joined more than 30 days ago
is_experienced_user = request.user.date_joined < timezone.now() - timedelta(
days=30
)
curs = connection.cursor()
curs.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ")
# Use existing cfs data instead of querying again
cf = cfs.get("in_progress") or cfs.get("open")
form = CommitFestFilterForm(request.GET, commitfest=cf)
patch_list = patchlist(request, cf, personalized=True)
if patch_list.redirect:
return patch_list.redirect
# Get stats related to user for current commitfest (same as me() view)
curs.execute(
"""SELECT
ps.status, ps.statusstring, count(*)
FROM commitfest_patchoncommitfest poc
INNER JOIN commitfest_patch p ON p.id = poc.patch_id
INNER JOIN commitfest_patchstatus ps ON ps.status=poc.status
WHERE
ps.status = ANY(%(openstatuses)s)
AND (
EXISTS (
SELECT 1 FROM commitfest_patch_reviewers cpr WHERE cpr.patch_id=p.id AND cpr.user_id=%(user_id)s
)
OR EXISTS (
SELECT 1 FROM commitfest_patch_authors cpa WHERE cpa.patch_id=p.id AND cpa.user_id=%(user_id)s
)
OR p.committer_id=%(user_id)s
)
GROUP BY ps.status ORDER BY ps.sortkey""",
{
"user_id": request.user.id,
"openstatuses": PatchOnCommitFest.OPEN_STATUSES,
},
)
statussummary = curs.fetchall()
context.update(
{
"show_dashboard": True,
"form": form,
"patches": patch_list.patches,
"statussummary": statussummary,
"tags_data": get_tags_data(),
"all_tags": {t.id: t for t in Tag.objects.all()},
"has_filter": patch_list.has_filter,
"grouping": patch_list.sortkey == 0,
"sortkey": patch_list.sortkey,
"openpatchids": [p["id"] for p in patch_list.patches if p["is_open"]],
"userprofile": getattr(request.user, "userprofile", UserProfile()),
"is_experienced_user": is_experienced_user,
}
)
return render(request, "home.html", context)
@login_required
def me_legacy_redirect(request):
# Previously we would have a dedicated dashboard page, now this
# is on the homepage.
return HttpResponseRedirect("/#dashboard")
def commitfest_history(request):
cfs = list(CommitFest.objects.order_by("-enddate"))
return render(
request,
"all_commitfests.html",
{
"commitfests": cfs,
"title": "Commitfest history",
"header_activity": "Activity log",
"header_activity_link": "/activity/",
},
)
def help(request):
return render(
request,
"help.html",
{
"title": "What is the Commitfest app?",
"auto_move_email_activity_days": settings.AUTO_MOVE_EMAIL_ACTIVITY_DAYS,
"auto_move_max_failing_days": settings.AUTO_MOVE_MAX_FAILING_DAYS,
},
)
def archive(request):
commitfests = list(CommitFest.objects.all())
return render(
request,
"archive.html",
{
"commitfests": commitfests,
"title": "Commitfests",
"header_activity": "Activity log",
"header_activity_link": "activity/",
},
)
def activity(request, cfid=None, rss=None):
# Number of notes to fetch
if rss:
num = 50
else:
num = 100
if cfid:
cf = get_object_or_404(CommitFest, pk=cfid)
# Yes, we do string concatenation of the were clause. Because
# we're evil. And also because the number has been verified
# when looking up the cf itself, so nothing can be injected
# there.
where = "WHERE EXISTS (SELECT 1 FROM commitfest_patchoncommitfest poc2 WHERE poc2.patch_id=p.id AND poc2.commitfest_id={0})".format(
cf.id
)
else:
cf = None
where = ""
sql = "SELECT ph.date, auth_user.username AS by, ph.what, p.id AS patchid, p.name, (SELECT max(commitfest_id) FROM commitfest_patchoncommitfest poc WHERE poc.patch_id=p.id) AS cfid FROM commitfest_patchhistory ph INNER JOIN commitfest_patch p ON ph.patch_id=p.id INNER JOIN auth_user on auth_user.id=ph.by_id {0} ORDER BY ph.date DESC LIMIT {1}".format(
where, num
)
curs = connection.cursor()
curs.execute(sql)
activity = [dict(zip([c[0] for c in curs.description], r)) for r in curs.fetchall()]
if rss:
# Return RSS feed with these objects
return ActivityFeed(activity, cf)(request)
else:
# Return regular webpage
return render(
request,
"activity.html",
{
"commitfest": cf,
"activity": activity,
"title": cf and "Commitfest activity" or "Global Commitfest activity",
"rss_alternate": cf
and "/{0}/activity.rss/".format(cf.id)
or "/activity.rss/",
"rss_alternate_title": "PostgreSQL Commitfest Activity Log",
"breadcrumbs": cf
and [
{"title": cf.title, "href": "/%s/" % cf.pk},
]
or None,
},
)
def redir(request, what, end):
if what == "open":
cfs = list(
CommitFest.objects.filter(status=CommitFest.STATUS_OPEN, draft=False)
)
elif what == "inprogress":
cfs = list(CommitFest.objects.filter(status=CommitFest.STATUS_INPROGRESS))
elif what == "current":
cfs = list(CommitFest.objects.filter(status=CommitFest.STATUS_INPROGRESS))
if len(cfs) == 0:
cfs = list(
CommitFest.objects.filter(status=CommitFest.STATUS_OPEN, draft=False)
)
elif what == "draft":
cfs = list(CommitFest.objects.filter(status=CommitFest.STATUS_OPEN, draft=True))
else:
raise Http404()
if len(cfs) == 0:
messages.warning(
request, "No {0} commitfests exist, redirecting to startpage.".format(what)
)
return HttpResponseRedirect("/")
if len(cfs) != 1:
messages.warning(
request,
"More than one {0} commitfest exists, redirecting to startpage instead.".format(
what
),
)
return HttpResponseRedirect("/")
query_string = request.GET.urlencode()
if query_string:
query_string = "?" + query_string
return HttpResponseRedirect(f"/{cfs[0].id}/{end}{query_string}")
PatchList = collections.namedtuple(
"PatchList", ["patches", "has_filter", "sortkey", "redirect"]
)
def patchlist(request, cf, personalized=False):
# Build a dynamic filter based on the filtering options entered
whereclauses = []
whereparams = {}
if request.GET.get("status", "-1") != "-1":
try:
whereparams["status"] = int(request.GET["status"])
whereclauses.append("poc.status=%(status)s")
except ValueError:
# int() failed -- so just ignore this filter
pass
if request.GET.get("targetversion", "-1") != "-1":
if request.GET["targetversion"] == "-2":
whereclauses.append("targetversion_id IS NULL")
else:
try:
whereparams["verid"] = int(request.GET["targetversion"])
whereclauses.append("targetversion_id=%(verid)s")
except ValueError:
# int() failed, ignore
pass
if request.GET.getlist("tag") != []:
try:
tag_ids = [int(t) for t in request.GET.getlist("tag")]
for tag_id in tag_ids:
# Instead of using parameters, we just inline the tag_id. This
# is easier because we have can have multiple tags, and since
# tag_id is always an int it's safe with respect to SQL
# injection.
whereclauses.append(
f"EXISTS (SELECT 1 FROM commitfest_patch_tags tags WHERE tags.patch_id=p.id AND tags.tag_id={tag_id})"
)
except ValueError:
# int() failed -- so just ignore this filter
pass
if request.GET.get("author", "-1") != "-1":
if request.GET["author"] == "-2":
whereclauses.append(
"NOT EXISTS (SELECT 1 FROM commitfest_patch_authors cpa WHERE cpa.patch_id=p.id)"
)
elif request.GET["author"] == "-3":
# Checking for "yourself" requires the user to be logged in!
if not request.user.is_authenticated:
return PatchList(
patches=[],
has_filter=False,
sortkey=0,
redirect=HttpResponseRedirect(
"%s?next=%s" % (settings.LOGIN_URL, request.path)
),
)
whereclauses.append(
"EXISTS (SELECT 1 FROM commitfest_patch_authors cpa WHERE cpa.patch_id=p.id AND cpa.user_id=%(self)s)"
)
whereparams["self"] = request.user.id
else:
try:
whereparams["author"] = int(request.GET["author"])
whereclauses.append(
"EXISTS (SELECT 1 FROM commitfest_patch_authors cpa WHERE cpa.patch_id=p.id AND cpa.user_id=%(author)s)"
)
except ValueError:
# int() failed -- so just ignore this filter
pass
if request.GET.get("reviewer", "-1") != "-1":
if request.GET["reviewer"] == "-2":
whereclauses.append(
"NOT EXISTS (SELECT 1 FROM commitfest_patch_reviewers cpr WHERE cpr.patch_id=p.id)"
)
elif request.GET["reviewer"] == "-3":
# Checking for "yourself" requires the user to be logged in!
if not request.user.is_authenticated:
return PatchList(
patches=[],
has_filter=False,
sortkey=0,
redirect=HttpResponseRedirect(
"%s?next=%s" % (settings.LOGIN_URL, request.path)
),
)
whereclauses.append(
"EXISTS (SELECT 1 FROM commitfest_patch_reviewers cpr WHERE cpr.patch_id=p.id AND cpr.user_id=%(self)s)"
)
whereparams["self"] = request.user.id
else:
try:
whereparams["reviewer"] = int(request.GET["reviewer"])
whereclauses.append(
"EXISTS (SELECT 1 FROM commitfest_patch_reviewers cpr WHERE cpr.patch_id=p.id AND cpr.user_id=%(reviewer)s)"
)
except ValueError:
# int() failed -- so just ignore this filter
pass
if request.GET.get("text", "") != "":
whereclauses.append("p.name ILIKE '%%' || %(txt)s || '%%'")
whereparams["txt"] = request.GET["text"]
has_filter = len(whereclauses) > 0
if personalized:
whereclauses.append("""
EXISTS (
SELECT 1 FROM commitfest_patch_reviewers cpr WHERE cpr.patch_id=p.id AND cpr.user_id=%(self)s
) OR EXISTS (
SELECT 1 FROM commitfest_patch_authors cpa WHERE cpa.patch_id=p.id AND cpa.user_id=%(self)s
) OR p.committer_id=%(self)s""")
whereparams["self"] = request.user.id
whereclauses.append("poc.status=ANY(%(openstatuses)s)")
else:
whereclauses.append("poc.commitfest_id=%(cid)s")
# Exclude "Moved to other CF" patches from draft commitfests
if cf.draft:
whereclauses.append("poc.status != %(status_moved)s")
whereparams["status_moved"] = PatchOnCommitFest.STATUS_MOVED
if personalized:
# For now we can just order by these names in descending order, because
# they are crafted such that they alphabetically sort in the intended
# order.
columns_str = """
CASE WHEN
EXISTS (
SELECT 1 FROM commitfest_patch_authors cpa WHERE cpa.patch_id=p.id AND cpa.user_id=%(self)s
) AND (
cf.status = %(closed_status)s
)
THEN 'Your still open patches in a closed commitfest (you should move or close these)'
WHEN
EXISTS (
SELECT 1 FROM commitfest_patch_authors cpa WHERE cpa.patch_id=p.id AND cpa.user_id=%(self)s
) AND (
poc.status=%(needs_author)s
OR branch.needs_rebase_since IS NOT NULL
OR branch.failing_since + interval '4 days' < now()
OR (%(is_committer)s AND poc.status=%(needs_committer)s)
)
THEN 'Your patches that need changes from you'
WHEN
NOT EXISTS (
SELECT 1 FROM commitfest_patch_authors cpa WHERE cpa.patch_id=p.id AND cpa.user_id=%(self)s
) AND (
poc.status=ANY(%(review_statuses)s)
)
THEN 'Patches that are ready for your review'
ELSE 'Blocked on others'
END AS group_name,
cf.id AS cf_id,
cf.name AS cf_name,
cf.status AS cf_status,
"""
whereparams["needs_author"] = PatchOnCommitFest.STATUS_AUTHOR
whereparams["needs_committer"] = PatchOnCommitFest.STATUS_COMMITTER
whereparams["closed_status"] = CommitFest.STATUS_CLOSED
is_committer = bool(Committer.objects.filter(user=request.user, active=True))
whereparams["is_committer"] = is_committer
if is_committer:
whereparams["review_statuses"] = [
PatchOnCommitFest.STATUS_REVIEW,
PatchOnCommitFest.STATUS_COMMITTER,
]
else:
whereparams["review_statuses"] = [
PatchOnCommitFest.STATUS_REVIEW,
]
joins_str = "INNER JOIN commitfest_commitfest cf ON poc.commitfest_id=cf.id"
groupby_str = "cf.id,"
else:
columns_str = ""
joins_str = ""
groupby_str = ""
# Figure out custom ordering
try:
sortkey = int(request.GET.get("sortkey", "0"))
except ValueError:
sortkey = 0
if sortkey == 2:
orderby_str = "lastmail, created"
elif sortkey == -2:
orderby_str = "lastmail DESC, created DESC"
elif sortkey == 3:
orderby_str = "num_cfs DESC, modified, created"
elif sortkey == -3:
orderby_str = "num_cfs ASC, modified DESC, created DESC"
elif sortkey == 4:
orderby_str = "p.id"
elif sortkey == -4:
orderby_str = "p.id DESC"
elif sortkey == 5:
orderby_str = "p.name, created"
elif sortkey == -5:
orderby_str = "p.name DESC, created DESC"
elif sortkey == 6:
orderby_str = "branch.all_additions + branch.all_deletions NULLS LAST, created"
elif sortkey == -6:
orderby_str = (
"branch.all_additions + branch.all_deletions DESC NULLS LAST, created DESC"
)
elif sortkey == 7:
orderby_str = "branch.failing_since DESC NULLS FIRST, branch.created DESC"
elif sortkey == -7:
orderby_str = "branch.failing_since NULLS LAST, branch.created"
elif sortkey == 8:
orderby_str = "poc.commitfest_id, lastmail DESC"
elif sortkey == -8:
orderby_str = "poc.commitfest_id DESC, lastmail"
else:
if personalized:
# First we sort by group_name, to have the grouping work.
# Then we show non-failing patches first, and the ones that are
# shortest failing we show first. We consider patches in a closed
# commitfest, as if they are failing since that commitfest was
# closed.
# Then we sort by start date of the CF, to show entries in the "In
# progress" commitfest before ones in the "Open" commitfest.
# And then to break ties, we put ones with the most recent email at
# the top.
orderby_str = """group_name DESC,
COALESCE(
branch.failing_since,
CASE WHEN cf.status = %(cf_closed_status)s
THEN enddate ELSE NULL END
) DESC NULLS FIRST,
cf.startdate,
lastmail DESC"""
whereparams["cf_closed_status"] = CommitFest.STATUS_CLOSED
else:
orderby_str = "created"
sortkey = 0
if not has_filter and sortkey == 0 and request.GET:
# Redirect to get rid of the ugly url
return PatchList(
patches=[],
has_filter=False,
sortkey=0,
redirect=HttpResponseRedirect(request.path),
)
if whereclauses:
where_str = "({0})".format(") AND (".join(whereclauses))
else:
where_str = "true"
params = {
"openstatuses": PatchOnCommitFest.OPEN_STATUSES,
"cid": cf.id,
}
params.update(whereparams)
# Let's not overload the poor django ORM
curs = connection.cursor()
curs.execute(
f"""SELECT p.id, p.name, poc.status, v.version AS targetversion, p.created, p.modified, p.lastmail, committer.first_name || ' ' || committer.last_name || ' (' || committer.username || ')' AS committer,
{columns_str}
(poc.status=ANY(%(openstatuses)s)) AS is_open,
(SELECT string_agg(first_name || ' ' || last_name || ' (' || username || ')', ', ') FROM auth_user INNER JOIN commitfest_patch_authors cpa ON cpa.user_id=auth_user.id WHERE cpa.patch_id=p.id) AS author_names,
(SELECT string_agg(first_name || ' ' || last_name || ' (' || username || ')', ', ') FROM auth_user INNER JOIN commitfest_patch_reviewers cpr ON cpr.user_id=auth_user.id WHERE cpr.patch_id=p.id) AS reviewer_names,
(SELECT count(1) FROM commitfest_patchoncommitfest pcf WHERE pcf.patch_id=p.id) AS num_cfs,
(SELECT array_agg(tag_id) FROM commitfest_patch_tags t WHERE t.patch_id=p.id) AS tag_ids,
branch.needs_rebase_since,
branch.failing_since,
(
SELECT row_to_json(t) as cfbot_results
from (
SELECT
count(*) FILTER (WHERE task.status in ('COMPLETED', 'PAUSED')) as completed,
count(*) FILTER (WHERE task.status in ('CREATED', 'SCHEDULED', 'EXECUTING')) running,
count(*) FILTER (WHERE task.status in ('ABORTED', 'ERRORED', 'FAILED')) failed,
count(*) FILTER (WHERE task.status in ('ABORTED', 'ERRORED', 'FAILED') AND task.task_name != 'FormattingCheck') as failed_non_formatting,
count(*) total,
string_agg(task.task_name, ', ') FILTER (WHERE task.status in ('ABORTED', 'ERRORED', 'FAILED')) as failed_task_names,
branch.status as branch_status,
branch.apply_url,
branch.build_url,
branch.patch_count,
branch.all_additions,
branch.all_deletions
FROM commitfest_cfbotbranch branch
LEFT JOIN commitfest_cfbottask task ON task.branch_id = branch.branch_id
WHERE branch.patch_id=p.id
GROUP BY branch.patch_id
) t
)
FROM commitfest_patch p
INNER JOIN commitfest_patchoncommitfest poc ON poc.patch_id=p.id
{joins_str}
LEFT JOIN auth_user committer ON committer.id=p.committer_id
LEFT JOIN commitfest_targetversion v ON p.targetversion_id=v.id
LEFT JOIN commitfest_cfbotbranch branch ON branch.patch_id=p.id
WHERE {where_str}
GROUP BY p.id, poc.id, {groupby_str} committer.id, v.version, branch.patch_id
ORDER BY is_open DESC, {orderby_str}""",
params,
)
patches = [
dict(zip([col[0] for col in curs.description], row)) for row in curs.fetchall()
]
return PatchList(
patches=patches,
sortkey=sortkey,
has_filter=has_filter,
redirect=False,
)
@transaction.atomic
def commitfest(request, cfid):
curs = connection.cursor()
# Make sure the patchlist() query, the stats query and, Tag.objects.all()
# all work on the same snapshot. Needs to be first in the
# transaction.atomic decorator.
curs.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ")
# Find ourselves
cf = get_object_or_404(CommitFest, pk=cfid)
patch_list = patchlist(request, cf)
if patch_list.redirect:
return patch_list.redirect
# Generate patch status summary.
# Exclude "Moved to other CF" status from draft commitfests
status_filter = "AND poc.status != %(status_moved)s" if cf.draft else ""
curs.execute(
f"SELECT ps.status, ps.statusstring, count(*) FROM commitfest_patchoncommitfest poc INNER JOIN commitfest_patchstatus ps ON ps.status=poc.status WHERE commitfest_id=%(id)s {status_filter} GROUP BY ps.status ORDER BY ps.sortkey",
{
"id": cf.id,
"status_moved": PatchOnCommitFest.STATUS_MOVED,
},
)
statussummary = curs.fetchall()
statussummary.append([-1, "Total", sum((r[2] for r in statussummary))])
# Generates a fairly expensive query, which we shouldn't do unless
# the user is logged in. XXX: Figure out how to avoid doing that..
form = CommitFestFilterForm(request.GET, commitfest=cf)
return render(
request,
"commitfest.html",
{
"cf": cf,
"form": form,
"patches": patch_list.patches,
"statussummary": statussummary,
"tags_data": get_tags_data(),
"all_tags": {t.id: t for t in Tag.objects.all()},
"has_filter": patch_list.has_filter,
"title": f"{cf.title} ({cf.periodstring})",
"sortkey": patch_list.sortkey,
"openpatchids": [p["id"] for p in patch_list.patches if p["is_open"]],
"header_activity": "Activity log",
"header_activity_link": "activity/",
"userprofile": getattr(request.user, "userprofile", UserProfile()),
},
)
def patches_by_messageid(messageid):
# First try to find the messageid in our database
patches = (
Patch.objects.select_related()
.filter(mailthread_set__messageid=messageid)
.order_by(
"created",
)
.all()
)
if patches:
return patches
urlsafe_messageid = urllib.parse.quote(messageid)
# If it's not there, try to find it in the archives
try:
thread = _archivesAPI(f"/message-id.json/{urlsafe_messageid}")
except Http404:
return []
if len(thread) == 0:
return []
first_email = min(thread, key=lambda x: x["date"])
return (
Patch.objects.select_related()
.filter(mailthread_set__messageid=first_email["msgid"])
.order_by(
"created",
)
.all()
)
# We require login for this page primarily so that the author/reviewer filter
# boxes can always be searched. Since searching for users outside of a
# commitfest requires users to be logged in to not make the data too easy to
# scrape.
@login_required
def global_search(request):
if "searchterm" not in request.GET:
return HttpResponseRedirect("/")
searchterm = request.GET["searchterm"].strip()
patches = []
if "@" in searchterm:
# This is probably a messageid, so let's try to look up patches related
# to it. Let's first remove any < and > around it though.
cleaned_id = searchterm.removeprefix("<").removesuffix(">")
patches = patches_by_messageid(cleaned_id)
if not patches:
patches_query = (
Patch.objects.select_related("targetversion", "committer")
.prefetch_related(
"authors",
"reviewers",
"tags",
"patchoncommitfest_set__commitfest",
"mailthread_set",
)
.select_related("cfbot_branch")
.filter(name__icontains=searchterm)
)
# Apply filters using the same logic as patchlist
if request.GET.get("status", "-1") != "-1":
try:
status = int(request.GET["status"])
patches_query = patches_query.filter(
patchoncommitfest__status=status
).distinct()
except ValueError:
pass
if request.GET.get("targetversion", "-1") != "-1":
if request.GET["targetversion"] == "-2":
patches_query = patches_query.filter(targetversion_id__isnull=True)
else:
try:
ver_id = int(request.GET["targetversion"])
patches_query = patches_query.filter(targetversion_id=ver_id)
except ValueError:
pass
if request.GET.getlist("tag"):
try:
tag_ids = [int(t) for t in request.GET.getlist("tag")]
for tag_id in tag_ids:
patches_query = patches_query.filter(tags__id=tag_id)
patches_query = patches_query.distinct()
except ValueError:
pass
# Apply author filter
if request.GET.get("author", "-1") != "-1":
if request.GET["author"] == "-2":
patches_query = patches_query.filter(authors__isnull=True)
elif request.GET["author"] == "-3":
# Filter for current user's patches
if not request.user.is_authenticated:
return HttpResponseRedirect(
f"{settings.LOGIN_URL}?next={request.path}?searchterm={searchterm}"
)
patches_query = patches_query.filter(authors=request.user)
else:
try:
author_id = int(request.GET["author"])
patches_query = patches_query.filter(authors__id=author_id)
except ValueError:
pass
# Apply reviewer filter
if request.GET.get("reviewer", "-1") != "-1":
if request.GET["reviewer"] == "-2":
patches_query = patches_query.filter(reviewers__isnull=True)
elif request.GET["reviewer"] == "-3":
# Filter for current user's reviews
if not request.user.is_authenticated:
return HttpResponseRedirect(
f"{settings.LOGIN_URL}?next={request.path}?searchterm={searchterm}"
)
patches_query = patches_query.filter(reviewers=request.user)
else:
try:
reviewer_id = int(request.GET["reviewer"])
patches_query = patches_query.filter(reviewers__id=reviewer_id)
except ValueError:
pass
# Ensure distinct results after filtering on many-to-many relationships
patches_query = patches_query.distinct()
# Apply sorting based on sortkey parameter (adapted for Django ORM)
sortkey = request.GET.get("sortkey", "1")
if sortkey == "2": # Latest mail
patches_query = patches_query.order_by("-modified") # Use modified as proxy
elif sortkey == "-2":
patches_query = patches_query.order_by("modified")
elif sortkey == "3": # Num cfs
patches_query = patches_query.annotate(
num_cfs=Count("patchoncommitfest")
).order_by("-num_cfs")
elif sortkey == "-3":
patches_query = patches_query.annotate(
num_cfs=Count("patchoncommitfest")
).order_by("num_cfs")
elif sortkey == "4": # ID
patches_query = patches_query.order_by("id")
elif sortkey == "-4":
patches_query = patches_query.order_by("-id")
elif sortkey == "5": # Patch name
patches_query = patches_query.order_by("name")
elif sortkey == "-5":
patches_query = patches_query.order_by("-name")
elif sortkey == "8": # CF
patches_query = patches_query.order_by("patchoncommitfest__commitfest__id")
elif sortkey == "-8":
patches_query = patches_query.order_by("-patchoncommitfest__commitfest__id")
else: # Default: Created (sortkey 1)
patches_query = patches_query.order_by("created")
patches = patches_query.all()
if len(patches) == 1:
patch = patches[0]
return HttpResponseRedirect(f"/patch/{patch.id}/")
# Use the existing filter form (no cf parameter, will require login for user lookups)
form = CommitFestFilterForm(request.GET)
# Get user profile for timestamp preferences
userprofile = None
if request.user.is_authenticated:
try:
from pgcommitfest.userprofile.models import UserProfile
userprofile = UserProfile.objects.get(user=request.user)
except UserProfile.DoesNotExist:
pass
return render(
request,
"patchsearch.html",
{
"patches": patches,
"title": "Patch search results",
"searchterm": searchterm,
"form": form,
"cf": None, # No specific commitfest context
"sortkey": int(request.GET.get("sortkey") or "1"),
"tags_data": get_tags_data(),
"all_tags": {t.id: t for t in Tag.objects.all()},
"userprofile": userprofile,
},
)
def patch_legacy_redirect(request, cfid, patchid):
# Previously we would include the commitfest id in the URL. This is no
# longer the case.
return HttpResponseRedirect(f"/patch/{patchid}/")
def patch(request, patchid):
patch = get_object_or_404(Patch.objects.select_related(), pk=patchid)
patch_commitfests = (
PatchOnCommitFest.objects.select_related("commitfest")
.filter(patch=patch)
.order_by("-enterdate")
.all()
)
cf = patch_commitfests[0].commitfest
committers = Committer.objects.filter(active=True).order_by(
"user__first_name", "user__last_name"
)
cfbot_branch = getattr(patch, "cfbot_branch", None)
cfbot_tasks = patch.cfbot_tasks.order_by("position") if cfbot_branch else []
# XXX: this creates a session, so find a smarter way. Probably handle
# it in the callback and just ask the user then?
if request.user.is_authenticated:
committer = [c for c in committers if c.user == request.user]
if len(committer) > 0:
is_committer = True
is_this_committer = committer[0] == patch.committer
else:
is_committer = is_this_committer = False
is_reviewer = request.user in patch.reviewers.all()
is_subscribed = patch.subscribers.filter(id=request.user.id).exists()
else:
is_committer = False
is_this_committer = False
is_reviewer = False
is_subscribed = False
return render(
request,
"patch.html",
{
"cf": cf,
"patch": patch,
"patch_commitfests": patch_commitfests,
"cfbot_branch": cfbot_branch,
"cfbot_tasks": cfbot_tasks,
"is_committer": is_committer,
"is_this_committer": is_this_committer,
"is_reviewer": is_reviewer,
"is_subscribed": is_subscribed,
"committers": committers,
"attachnow": "attachthreadnow" in request.GET,
"title": patch.name,
"description": (
"PostgreSQL patch by %s in the %s commitfest."
% (patch.authors_string or "unknown author", cf.title)
),
"breadcrumbs": [
{"title": cf.title, "href": "/%s/" % cf.pk},
],
"userprofile": getattr(request.user, "userprofile", UserProfile()),
"cfs": CommitFest.relevant_commitfests(),
},
)
@login_required
@transaction.atomic
def patchform(request, patchid):
patch = get_object_or_404(Patch, pk=patchid)
cf = patch.current_commitfest()
prevreviewers = list(patch.reviewers.all())
prevauthors = list(patch.authors.all())
prevcommitter = patch.committer
if request.method == "POST":
form = PatchForm(data=request.POST, instance=patch)
if form.is_valid():
# Some fields need to be set when creating a new one
r = form.save(commit=False)
# Fill out any locked fields here
form.save_m2m()
# Track all changes
for field, values in r.diff.items():
if field == "tags":
value = ", ".join(v.name for v in values[1])
else:
value = values[1]
PatchHistory(
patch=patch,
by=request.user,
what="Changed %s to %s" % (field, value),
).save_and_notify(
prevcommitter=prevcommitter,
prevreviewers=prevreviewers,
prevauthors=prevauthors,
)
r.set_modified()
r.save()
return HttpResponseRedirect("../../%s/" % r.pk)
# Else fall through and render the page again
else:
form = PatchForm(instance=patch)
return render(
request,
"base_form.html",
{
"cf": cf,
"form": form,
"patch": patch,
"title": "Edit patch",
"tags_data": get_tags_data(),
"breadcrumbs": [
{"title": cf.title, "href": "/%s/" % cf.pk},
{"title": "View patch", "href": "/%s/%s/" % (cf.pk, patch.pk)},
],
},
)
@login_required
@transaction.atomic
def newpatch(request, cfid):
cf = get_object_or_404(CommitFest, pk=cfid)
if not cf.status == CommitFest.STATUS_OPEN and not request.user.is_staff:
raise Http404("This commitfest is not open!")
if request.method == "POST":
form = NewPatchForm(data=request.POST)
if form.is_valid():