summaryrefslogtreecommitdiff
path: root/dim
blob: ee958be231abb5330837269b580cb9c4a8a4e4b1 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
#!/bin/bash

# Copyright © 2012-2016 Intel Corporation
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice (including the next
# paragraph) shall be included in all copies or substantial portions of the
# Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
# Authors:
#    Daniel Vetter <daniel.vetter@ffwll.ch>
#    Jani Nikula <jani.nikula@intel.com>

# drm-intel-next maintainer script

# fail on any goof-up
set -e

#
# User configuration. Set in environment or configuration file. See
# dimrc.sample for an example.
#

# dim configuration file
DIM_CONFIG=${DIM_CONFIG:-$HOME/.dimrc}
if [ -r $DIM_CONFIG ]; then
	# shellcheck source=/dev/null
	. $DIM_CONFIG
fi

# prefix for repo directories
DIM_PREFIX=${DIM_PREFIX:-$HOME/linux}

# main maintainer repo under $DIM_PREFIX
DIM_REPO=${DIM_REPO:-${DIM_DRM_INTEL:-src}}

# mail user agent. must support a subset of mutt(1) command line options:
# usage: $DIM_MUA [-s subject] [-i file] [-c cc-addr] to-addr [...]
DIM_MUA=${DIM_MUA:-mutt}

# make options (not used for C=1)
DIM_MAKE_OPTIONS=${DIM_MAKE_OPTIONS:--j20}

# command to run after dim apply
DIM_POST_APPLY_ACTION=${DIM_POST_APPLY_ACTION:-}

# greetings pull request template
DIM_TEMPLATE_HELLO=${DIM_TEMPLATE_HELLO:-$HOME/.dim.template.hello}

# signature pull request template
DIM_TEMPLATE_SIGNATURE=${DIM_TEMPLATE_SIGNATURE:-$HOME/.dim.template.signature}

# dim pull-request tag summary template
DIM_TEMPLATE_TAG_SUMMARY=${DIM_TEMPLATE_TAG_SUMMARY:-$HOME/.dim.template.tagsummary}

# GPG key id for signing tags. If unset, don't sign.
DIM_GPG_KEYID=${DIM_GPG_KEYID:+-u $DIM_GPG_KEYID}

#
# Internal configuration.
#

dim=$(basename $0)

dim_today=$(date +%Y-%m-%d)
dim_timestamp="$(date --utc +%Yy-%mm-%dd-%Hh-%Mm-%Ss) UTC"

# Recipients for all dim based pull requests.
# Add To: lines to the end, Cc: lines in the beginning with -c.
pull_request_recipients=(
	-c "Daniel Vetter <daniel.vetter@ffwll.ch>"
	-c "Jani Nikula <jani.nikula@linux.intel.com>"
	-c "Joonas Lahtinen <joonas.lahtinen@linux.intel.com>"
	-c "Rodrigo Vivi <rodrigo.vivi@intel.com>"
	-c "Sean Paul <seanpaul@chromium.org>"
	-c "dri-devel@lists.freedesktop.org"
	-c "intel-gfx@lists.freedesktop.org"
	"Dave Airlie <airlied@gmail.com>"
)

# Recipients for drm-intel-testing updates.
test_request_recipients=(
	-c "Jani Nikula <jani.nikula@linux.intel.com>"
	-c "Joonas Lahtinen <joonas.lahtinen@linux.intel.com>"
	-c "Rodrigo Vivi <rodrigo.vivi@intel.com>"
	-c "intel-gfx@lists.freedesktop.org"
	"Jari Tahvanainen <jari.tahvanainen@intel.com>"
)

# integration configuration
integration_config=nightly.conf

function read_integration_config
{
	# clear everything first to allow configuration reload
	unset drm_tip_repos drm_tip_config
	declare -g -A drm_tip_repos
	declare -g -a drm_tip_config

	if [ -r $DIM_PREFIX/drm-rerere/$integration_config ]; then
		# shellcheck source=/dev/null
		source $DIM_PREFIX/drm-rerere/$integration_config

		if [[ "${#drm_tip_repos[@]}" = "0" ]] || [[ "${#drm_tip_config[@]}" = "0" ]]; then
			echoerr "$integration_config not set up correctly, please fix manually"
			exit 1
		fi
	else
		echoerr "$integration_config is missing, please check your configuration and/or run dim setup"
		exit 1
	fi

	dim_branches=
	for conf in "${drm_tip_config[@]}"; do
		local repo branch override
		read -r repo branch override <<< $conf
		if [[ "$repo" = "drm-intel" || "$repo" = "drm-misc" ]]; then
			dim_branches="$dim_branches $branch"
		fi
	done
}

function echoerr
{
	echo "$dim: $*" >&2
}

function warn_or_fail
{
	if [[ $FORCE ]] ; then
		echoerr "WARNING: $1, but continuing"
	elif [[ $DRY ]] ; then
		echoerr "WARNING: $1, but continuing dry-run"
	else
		echoerr "ERROR: $1, aborting"
		exit 1
	fi
}

function pause
{
	read -rsp "Press any key to continue..." -n1 key2
	echo
}

#
# Command line options.
#

DRY_RUN=
INTERACTIVE=
DRY=
FORCE=
HELP=

while getopts hdfis opt; do
	case "$opt" in
		d)
			DRY_RUN=--dry-run
			DRY=echo
			;;
		f)
			FORCE=1
			;;
		i)
			INTERACTIVE=pause
			;;
		h)
			HELP=1
			;;
		s)
			# FIXME: transitional, do unconditionally at the top
			# when there are no more errors about unbound variables
			set -u
			;;
		*)
			echoerr "See '$dim help' for more information."
			exit
	esac
done
shift $((OPTIND - 1))

# first positional argument is the subcommand
if [ -n "$HELP" ] || [ "$#" = "0" ]; then
    subcommand="usage"
else
    subcommand="$1"
    shift
fi

# generic usage to be used for ${1:?$usage} style argument references
usage="Missing arguments(s) for '$dim $subcommand'. See '$dim help' for usage."

#
# Sanity checks.
#

# Make sure we use 'dim_foo' within dim instead of 'dim foo'.
if [[ -n "${__dim_running:-}" ]]; then
	echoerr "INTERNAL ERROR: do not recurse back to dim"
	exit 1
fi
export __dim_running=1

if [ "$subcommand" != "setup" ] && [ "$subcommand" != "help" ] && [ "$subcommand" != "usage" ]; then
	for d in $DIM_PREFIX $DIM_PREFIX/$DIM_REPO $DIM_PREFIX/drm-rerere $DIM_PREFIX/drm-tip; do
		if [ ! -d $d ]; then
			echoerr "$d is missing, please check your configuration and/or run dim setup"
			exit 1
		fi
	done

	read_integration_config
fi

#
# Only function and alias definitions until the subcommand handling at the end.
#

#
# Variable naming convetion:
#
# repo:
#	symbolic git repository name from $integration_config
# remote:
#	local remote name in the git repository for the current path
# branch:
#	git branch name - dim assumes that the remote and local name match
# url:
#	url to a repo, using ssh:// protocol
# git_url:
#	url to a repo, but using anonymous git:// protocol
#
# The below functions map between these.
#

function url_to_remote # url [url ...]
{
	local url remote

	if [[ "$#" = "0" ]]; then
		echoerr "url_to_remote without URLs"
		return 1
	fi

	for url; do
		remote=$(git remote -v | grep -m 1 "$url" | cut -f 1)
		if [[ -n "$remote" ]]; then
			echo "$remote"
			return 0
		fi
	done

	echoerr "No git remote for any of the URLs $* found in $(pwd)"

	url=$1
	remote=${url%.git}
	remote=${remote##*/}
	read -r -i "$remote" -e -p "Enter a name to auto-add this remote, leave blank to abort: " remote
	if [[ -z "$remote" ]]; then
		echoerr "Please set it up yourself using:"
		echoerr "    $ git remote add <name> $url"
		echoerr "with a name of your choice."
		return 1
	fi

	git remote add $remote $url

	echo $remote

	return 0
}

function pick_protocol_url # (git|ssh|https|whatever) url [url ...]
{
	local url protocol protocol_url

	if [[ "$#" -lt "2" ]]; then
		echoerr "pick_protocol_url without protocol or URLs"
		return 1
	fi

	protocol=$1
	shift

	# Find the URL that has given protocol
	for url; do
		case $url in
			${protocol}://*)
				protocol_url=$url
				break
				;;
		esac
	done

	if [[ -z "$protocol_url" ]]; then
		echoerr "No $protocol URL in any of the URLs: $*"
		return 1
	fi

	echo $protocol_url
}

function branch_to_remote # branch
{
	local branch remote

	branch=$1
	remote=$(git rev-parse --abbrev-ref --symbolic-full-name "$branch@{upstream}")
	remote=${remote%%/*}

	echo $remote
}

function repo_to_remote # repo
{
	local repo url_list

	repo=$1
	url_list=${drm_tip_repos[$repo]}

	if [[ -z "$url_list" ]]; then
		echoerr "unknown repo $repo"
		return 1
	fi

	url_to_remote $url_list
}

function branch_to_repo # branch
{
	for conf in "${drm_tip_config[@]}"; do
		local repo branch override
		read -r repo branch override <<< $conf

		if [[ "$branch" == "$1" ]] ; then
			echo $repo
		fi
	done

	echo ""
}

function dim_uptodate
{
	local using

	using="${BASH_SOURCE[0]}"

	if [[ ! -e "$using" ]]; then
		echoerr "could not figure out the version being used ($using)."
		return 1
	fi

	if [[ ! -e "$DIM_PREFIX/maintainer-tools/.git" ]]; then
		echoerr "could not find the upstream repo for $dim."
		return 1
	fi

	if ! git --git-dir=$DIM_PREFIX/maintainer-tools/.git show "@{upstream}:dim" |\
			diff "$using" - >& /dev/null; then
		echoerr "not running upstream version of the script."
		return 1
	fi
}

function check_for_updates
{
	local stamp stampfile

	stampfile=$HOME/.dim-update-check-timestamp

	# daily check for updates based on file timestamp
	stamp=$(stat --printf=%Y $stampfile 2>/dev/null || echo -n 0)
	if [[ $((stamp + 24*60*60)) -lt $(date +%s) ]]; then
		dim_uptodate || true
		touch $stampfile
	fi
}

function git_fetch_helper # remote
{
	local remote

	remote=$1

	if ! git fetch --prune -q $remote ; then
		# old git versions returned 128 if there was nothing to fetch
		if [[ $? -ne "128" ]] ; then
			echoerr "Failed to fetch $remote"
			return 1
		fi
	fi
}

function git_current_branch
{
	git symbolic-ref -q --short HEAD
}

function git_is_current_branch # branch
{
	test "$(git_current_branch)" = "$1"
}

function git_branch_exists # branch
{
	if [[ "$(git branch --list $1)" == "" ]] ; then
		false
	else
		true
	fi
}

function git_committer_email
{
	if ! committer_email=$(git config --get user.email) ; then
		committer_email=${EMAIL-}
	fi

	echo $committer_email
}

# get message id from file
# $1 = file
message_get_id ()
{
	python <<EOF
from email.parser import Parser
headers = Parser().parse(open('$1', 'r'))
message_id = headers['message-id']
if message_id is not None:
    print(message_id.strip('<>'))
EOF
}

message_print_body ()
{
	python2 <<EOF
import email

def print_part(part):
    mtype = part.get_content_maintype()
    if mtype == 'text':
        print(part.get_payload(decode=True))

def print_msg(file):
    msg = email.message_from_file(file)
    if msg.is_multipart():
        for part in msg.get_payload():
            print_part(part)
    else:
        print_part(msg)

print_msg(open('$1', 'r'))
EOF
}

# append all arguments as tags at the end of the commit message of HEAD
function dim_commit_add_tag
{
	for arg; do
		# the first sed deletes all trailing blank lines at the end
		git log -1 --pretty=%B | \
			sed -e :a -e '/^\n*$/{$d;N;ba' -e '}' | \
			sed "\$a${arg}" | \
			git commit --amend -F-
	done
}

# $1: branch [optional]
function git_find_tip
{
	git log $1 -1 --format=%H --grep="^drm-tip: .* integration manifest$"
}

# $1: branch [optional]
function dim_retip
{
	local branch upstream remote

	branch="$1"

	if [ -n "$branch" ] ; then
		shift
	else
		branch=$(git symbolic-ref --short HEAD)
	fi

	remote=$(repo_to_remote drm-tip)
	upstream=$(git_find_tip "$branch")

	if [[ -z "$upstream" ]]; then
		echoerr "$branch is not based on drm-tip"
		return 1
	fi

	git rebase --onto $remote/drm-tip $upstream $branch "$@"
}

# update for-linux-next and for-linux-next-fixes branches
function update_linux_next # branch next next-fixes fixes
{
	local branch linux_next linux_next_fixes linux_fixes repo remote

	cd $DIM_PREFIX/drm-tip
	branch=$1
	linux_next=$2
	linux_next_fixes=$3
	linux_fixes=$4

	repo=$(branch_to_repo $branch)

	if [[ $repo != $(branch_to_repo $linux_next) ]] ; then
		return
	fi

	remote=$(repo_to_remote $repo)

	git_fetch_helper $remote

	# always update drm-intel-fixes
	echo -n "Pushing $linux_fixes to for-linux-next-fixes... "
	git push $DRY_RUN $remote +$remote/$linux_fixes:for-linux-next-fixes # >& /dev/null
	echo "Done."

	if git merge-base --is-ancestor $remote/$linux_next_fixes $remote/$linux_fixes ; then
		# -fixes has caught up to dinf, i.e. we're out of the merge
		# window. Push the next queue.
		echo -n "Out of merge window. Pushing $linux_next to for-linux-next... "
		git push $DRY_RUN $remote +$remote/$linux_next:for-linux-next >& /dev/null
		echo "Done."
	else
		# dinf is ahead of -fixes, i.e. drm-next has already closed for
		# the next merge window and we've started to gather new fixes
		# for the current -next cycle. Push dinf

		echo -n "Pushing $linux_next_fixes to for-linux-next... "
		git push $DRY_RUN $remote +$remote/$linux_next_fixes:for-linux-next >& /dev/null
		echo "Done."
	fi
}

function check_conflicts # tree
{
	if git diff | grep -q '\(<<<<<<<\|=======\|>>>>>>>\||||||||\)' ; then
		# we need an empty line to make it look pretty
		echoerr ""
		echoerr "FAILURE: Could not merge $1"
		echoerr "See the section \"Resolving Conflicts when Rebuilding drm-tip\""
		echoerr "in the drm-intel.rst documentation for how to handle this situation."
		exit 1
	fi
	true
}

function rr_cache_dir
{
	if [ -d $DIM_PREFIX/drm-tip/.git/ ] ; then
		echo $DIM_PREFIX/drm-tip/.git/rr-cache
	else
		echo $DIM_PREFIX/$DIM_REPO/.git/rr-cache
	fi
}

function update_rerere_cache
{
	echo -n "Updating rerere cache... "

	cd $DIM_PREFIX/drm-rerere/
	if ! git pull -q ; then
		echoerr "Failed to update the rerere cache."
		echoerr "Please manually run"
		echoerr "	$ cd $DIM_PREFIX/drm-rerere ; git pull"
		echoerr "and fixup any issues."

		return 1
	fi
	if [ ! -L $(rr_cache_dir) ] ; then
		if [ -d $(rr_cache_dir) ] ; then
			rm -Rf $(rr_cache_dir)
		fi
		ln -s "$DIM_PREFIX/drm-rerere/rr-cache" $(dirname $(rr_cache_dir))
	fi

	cd - > /dev/null

	echo "Done."
}

function commit_rerere_cache
{
	local remote file commit_message

	echo -n "Updating rerere cache... "

	cd $DIM_PREFIX/drm-rerere/
	if ! git_is_current_branch rerere-cache; then
		echo "Fail: Branch setup for the rerere-cache is borked."
		exit 1
	fi

	remote=$(branch_to_remote rerere-cache)

	if ! git pull -q; then
		echoerr "Failed to update the rerere cache."
		echoerr "Please manually run"
		echoerr "	$ cd $DIM_PREFIX/drm-rerere; git pull"
		echoerr "and fixup any issues."

		return 1
	fi
	git add ./*.patch >& /dev/null || true
	for file  in $(git ls-files -- rr-cache); do
		if ! git log --since="60 days ago" --name-only -- $file | grep $file &> /dev/null; then
			git rm $file &> /dev/null || true
		fi
	done
	find rr-cache/ -mtime -1 -type f -not -name "thisimage*" -print0 | xargs -0 git add > /dev/null || true
	git rm rr-cache/rr-cache &> /dev/null || true

	commit_message=$(mktemp)
	cat > $commit_message <<-EOF
		$dim_timestamp: $integration_branch rerere cache update

		$(git --version)
		EOF

	if git commit -F $commit_message >& /dev/null; then
		echo -n "New commit. "
	else
		echo -n "Nothing changed. "
	fi
	rm $commit_message

	echo -n "Pushing rerere cache... "
	git push $DRY_RUN $remote HEAD >& /dev/null && echo "Done."
}

function dim_rebuild_tip
{
	local integration_branch specfile first rerere repo remote

	integration_branch=drm-tip
	specfile=$(mktemp)
	first=1

	rerere=$DIM_PREFIX/drm-rerere

	cd $rerere
	if git status --porcelain | grep -q -v "^[ ?][ ?]"; then
		warn_or_fail "integration configuration file $integration_config not commited"
	fi

	update_rerere_cache

	echo -n "Reloading $integration_config... "
	read_integration_config
	echo "Done."

	cd $DIM_PREFIX/$integration_branch
	if ! git_is_current_branch $integration_branch ; then
		echo "Branch setup for the integration repo is borked"
		exit 1
	fi

	# rerere uses sha1 of the diff to identify conflicts, we must ensure
	# that they look the same for everyone
	git config merge.conflictstyle merge

	for repo in "${!drm_tip_repos[@]}"; do
		remote=$(repo_to_remote $repo)
		echo -n "Fetching $repo (local remote $remote)... "
		git_fetch_helper $remote
		echo "Done."
	done

	# merge -fixes
	for conf in "${drm_tip_config[@]}"; do
		local branch override sha1 fixup_file

		read -r repo branch override <<< $conf
		remote=$(repo_to_remote $repo)
		sha1=$remote/$branch

		echo -n "Merging $repo (local remote $remote) $branch... "

		if [[ -n "$override" ]]; then
			sha1=$override
			echo -n "Using override sha1: $sha1... "
		fi

		if [ $first == 1 ] ; then
			git reset --hard $sha1 &> /dev/null
			echo "Reset. Done."
			first=0
		elif git merge --rerere-autoupdate --ff-only $sha1 >& /dev/null ; then
			# nothing to do if just fast-forward
			echo "Fast-forward. Done."
			true
		else
			fixup_file=$rerere/$repo-${branch//\//-}-fixup.patch
			echo $fixup_file > .fixup_file_path

			git merge --rerere-autoupdate --no-commit $sha1 >& /dev/null || true
			# normalize conflict markers
			if git grep -l '^>>>>>>> ' &> /dev/null ; then
				git grep -l '^>>>>>>> ' | xargs sed -e "s|^>>>>>>> .*$|>>>>>>> $repo\/$branch|" -i
			fi

			if [ -f $fixup_file ] ; then
				echo -n "Applying manual fixup patch for $integration_branch merge... "
				patch -p1 -i $fixup_file
			fi
			check_conflicts "$repo/$branch"
			git add -u

			# because we filter out fast-forward merges there will
			# always be something to commit
			git commit --no-edit --quiet
			echo "Done."
		fi

		echo -e "$repo $branch $(git rev-parse $sha1)\n\t$(git log -1 $sha1 --pretty=format:%s)" >> $specfile

		$INTERACTIVE
	done

	echo -n "Adding integration manifest $integration_branch: $dim_timestamp... "
	mv $specfile integration-manifest
	git add integration-manifest
	git commit --quiet -m "$integration_branch: $dim_timestamp integration manifest"
	echo "Done."

	remote=$(repo_to_remote drm-tip)

	echo -n "Pushing $integration_branch... "
	git push $DRY_RUN $remote +HEAD >& /dev/null && echo "Done."

	commit_rerere_cache
}

# additional patch checks before pushing, e.g. for r-b tags
function checkpatch_commit_push
{
	local sha1

	sha1=$1

	# use real names for people with many different email addresses
	author=$(git show -s $sha1 --format="format:%an")
	committer=$(git show -s $sha1 --format="format:%cn")
	# outlook mangles mails into "Last, First"
	author_outlook=$(git show -s $sha1 --format="format:%an" | sed -e 's/\([^ ]*\) \(.*\)/\2, \1/')

	# check for author sign-off
	if ! git show -s $sha1 | grep -qi "S.*-by:.*\\($author\\|$author_outlook\\)" ; then
		warn_or_fail "$sha1 is lacking author of sign-off"
	fi

	# check for committer sign-off
	if ! git show -s $sha1 | grep -qi "S.*-by:.*$committer"  ; then
		warn_or_fail "$sha1 is lacking committer of sign-off"
	fi

	# check for Link tag
	if ! git show -s $sha1 | grep -qi 'Link:'  ; then
		warn_or_fail "$sha1 is lacking of link tag"
	fi

	# check for a-b/r-b tag
	if git show -s $sha1 | grep -qi '\(reviewed\|acked\)\S*-by:'  ; then
		return
	fi

	# check for committer != author
	if [[ "$committer" != "$author" ]]; then
		return
	fi

	warn_or_fail "$sha1 is lacking mandatory review"
}

# push branch $1, rebuild drm-tip. the rest of the arguments are passed to git
# push.
function dim_push_branch
{
	local branch remote committer_email

	branch=${1:?$usage}
	shift

	assert_branch $branch

	remote=$(branch_to_remote $branch)

	committer_email=$(git_committer_email)

	for sha1 in $(git rev-list "$branch@{u}..$branch" --committer="$committer_email" --no-merges) ; do
		checkpatch_commit_push $sha1
	done

	git push $DRY_RUN $remote $branch "$@"

	update_linux_next $branch drm-intel-next-queued drm-intel-next-fixes drm-intel-fixes
	update_linux_next $branch drm-misc-next drm-misc-next-fixes drm-misc-fixes
	update_linux_next $branch drm-amd-next drm-amd-next-fixes drm-amd-fixes

	dim_rebuild_tip
}

dim_alias_pq=push-queued
function dim_push_queued
{
	dim_push_branch drm-intel-next-queued "$@"
}

dim_alias_pnf=push-next-fixes
function dim_push_next_fixes
{
	dim_push_branch drm-intel-next-fixes "$@"
}

dim_alias_pf=push-fixes
function dim_push_fixes
{
	dim_push_branch drm-intel-fixes "$@"
}

function dim_push
{
	dim_push_branch $(git_current_branch) "$@"
}

function apply_patch #patch_file
{
	local patch message_id committer_email patch_from sob rv

	patch="$1"
	shift
	message_id=$(message_get_id $patch)
	committer_email=$(git_committer_email)

	patch_from=$(grep "From:" "$patch" | head -1)
	if [[ "$patch_from" != *"$committer_email"* ]] ; then
		sob=-s
	fi

	git am --scissors -3 $sob "$@" $patch

	if [ -n "$message_id" ]; then
		dim_commit_add_tag "Link: https://patchwork.freedesktop.org/patch/msgid/$message_id"
	else
		echoerr "WARNING: No message-id found in the patch file."
		rv=1
	fi

	if ! checkpatch_commit HEAD; then
		rv=1
	fi
	if ! check_maintainer $branch HEAD; then
		rv=1
	fi

	eval $DRY $DIM_POST_APPLY_ACTION
	return $rv
}

# ensure we're on branch $1, and apply patches. the rest of the arguments are
# passed to git am.
dim_alias_ab=apply-branch
dim_alias_sob=apply-branch
function dim_apply_branch
{
	local branch file rv

	branch=${1:?$usage}
	shift
	file=$(mktemp)
	dir=$(mktemp -d)

	assert_branch $branch
	assert_repo_clean

	cat > $file
	git mailsplit -b -o$dir $file > /dev/null

	for patch in $dir/*; do
		if ! apply_patch $patch "$@"; then
			rv=1
		fi
	done
	rm -rf $file $dir

	return $rv
}

function dim_apply_pull
{
	local branch file message_id pull_branch rv

	branch=${1:?$usage}
	file=$(mktemp)

	assert_branch $branch
	assert_repo_clean

	cat > $file

	pull_branch=$(sed -e '0,/[gG]it repository at:$/d' $file | head -n 2 | tail -n 1)

	echo $pull_branch

	git pull $pull_branch

	message_id=$(message_get_id $file)

	git commit --amend -s --no-edit
	if [ -n "$message_id" ]; then
		dim_commit_add_tag "Link: https://patchwork.freedesktop.org/patch/msgid/$message_id"
	else
		echoerr "WARNING: No message-id found in the patch file."
		rv=1
	fi


	eval $DRY $DIM_POST_APPLY_ACTION

	return $rv
}

function dim_backmerge
{
	local branch upstream patch_file

	branch=${1:?$usage}
	upstream=${2:?$usage}

	cd $DIM_PREFIX/drm-tip
	tip_remote=$(repo_to_remote drm-tip)
	git fetch -q $tip_remote || true

	if ! git merge-base --is-ancestor $upstream $tip_remote/drm-tip ; then
		echoerr "Upstream $upstream not merged into drm-tip, aborting."
		echoerr "Please make sure any backmerge is tested in drm-tip,"
		echoerr "to give all the CI bots some time to find bugs."
		exit 1
	fi

	assert_branch $branch
	assert_repo_clean

	git merge --rerere-autoupdate --no-commit $upstream >& /dev/null || true

	if [[ -d .git ]]; then
		patch_file=".git"
	else
		patch_file=$(cut -d ' ' -f 2 .git)
	fi
	patch_file=$patch_file/MERGE_MSG


	cat > $patch_file <<-HERE
		Merge $upstream into $branch

		*** DETAILED BACKMERGE RATIONALE HERE ***

		HERE

	if git diff | grep -q '\(<<<<<<<\|=======\|>>>>>>>\||||||||\)' ; then
		echoerr "Conflicts found while merging $upstream into $branch."
		echoerr "This should only happen when git rerere gets confused"
		echoerr "or if there's a manual fixup patch in drm-rerere."
		echoerr "Please proceed with extreme caution."
		echoerr "Once the conflict is resolved, commit it with"
		echoerr "   git commit -a"
	fi

	git add -u
	git commit -s
}

function dim_add_link
{
	local branch file message_id

	branch=${1:?$usage}
	shift
	file=$(mktemp)

	assert_branch $branch
	assert_repo_clean

	cat > $file

	message_id=$(message_get_id $file)

	rm -f $file

	if [[ -n "$message_id" ]]; then
		dim_commit_add_tag "Link: https://patchwork.freedesktop.org/patch/msgid/$message_id"
	else
		echoerr "No message-id found in the patch file."
	fi
}

function dim_add_link_queued
{
	dim_add_link drm-intel-next-queued "$@"
}

function dim_add_link_fixes
{
	dim_add_link drm-intel-fixes "$@"
}

function dim_add_link_next_fixes
{
	dim_add_link drm-intel-next-fixes "$@"
}

dim_alias_aq=apply-queued
function dim_apply_queued
{
	dim_apply_branch drm-intel-next-queued "$@"
}

function dim_apply_fixes
{
	dim_apply_branch drm-intel-fixes "$@"
}

function dim_apply_next_fixes
{
	dim_apply_branch drm-intel-next-fixes "$@"
}

# apply patch to current branch, the rest of the arguments are passed to
# git am
dim_alias_am=apply
function dim_apply
{
	dim_apply_branch $(git_current_branch) "$@"
}

function commit_list_references
{
	local commit remote log

	cd $DIM_PREFIX/drm-tip
	remote=$(repo_to_remote drm-tip)
	git fetch -q $remote || true

	commit="$1"
	log=$(mktemp)

	git log --regexp-ignore-case --grep="${commit:0:8}" --oneline \
	    $commit..$remote/drm-tip > $log

	if [ "$(cat $log)" != "" ]; then
		echo "Commit ${commit:0:8} is referenced by later commits:"
		sed 's/^/\t/' < $log
	fi

	rm -f $log

	cd - >/dev/null
}

function dim_cherry_pick
{
	local commit

	commit=$(git rev-parse ${1:?$usage})

	git_fetch_helper $remote

	commit_list_references $commit

	$DRY git cherry-pick -s -x -e $commit
}

function git_list_fixes
{
	git log --reverse --format=format:%H --regexp-ignore-case \
	    --grep="^Cc:.*stable@vger\.kernel\.org" \
	    --grep="^Fixes: " \
	    "$@"
}

function cherry_pick_branch
{
	local branch log fail_log intel_remote needed have_fixes

	branch=${1:?$usage}
	log=$(mktemp)
	fail_log=$(mktemp)

	intel_remote=$(repo_to_remote drm-intel)

	# Look for commits in dinq tagged as fixes.
	for commit in $(git_list_fixes $intel_remote/$branch..$intel_remote/drm-intel-next-queued -- drivers/gpu/drm/i915); do
		echo -n "Considering $(dim_cite $commit)... "

		# Look at history for already cherry-picked fixes.
		# Note: use *local* branches to account for unpushed commits.
		git log drm-intel-fixes --format=format:%h --after=6months \
		    --grep="cherry picked .* $commit" > $log
		if [ "$(cat $log)" = "" ]; then
			git log drm-intel-next-fixes --format=format:%h --after=6months \
			    --grep="cherry picked .* $commit" > $log
		fi

		if [ "$(cat $log)" != "" ]; then
			echo "Already backported as $(tr "\n" " " < $log). OK."
			continue
		fi

		have_fixes=
		needed=
		for fixes in $(git show -s $commit | grep -i "^    Fixes: *[0-9a-fA-F]" | sed 's/^ *[Ff]ixes: *\([0-9a-fA-F]\+\).*/\1/'); do
			have_fixes=1
			fixes=$(git log -1 --format=format:%H $fixes 2>/dev/null || true)
			if [[ -z "$fixes" ]]; then
				continue
			fi

			# FIXME: see if the commit to be fixed has been
			# backported!
			echo -n "Fixes: $(dim_cite $fixes). "
			if [[ "$(git merge-base $branch $fixes)" = "$fixes" ]]; then
				needed=1
			fi
		done

		# Note: Cc: stable will overrule Fixes:
		if [[ -n "$have_fixes" && -z "$needed" ]]; then
			echo "Fixes a commit not in $branch. OK."
			continue
		fi

		echo "Try to cherry-pick."
		commit_list_references $commit
		if ! git cherry-pick -x -s $commit; then
			echo "FAILED: $(dim_cite $commit)"
			(dim_cite $commit) >> $fail_log
			git cherry-pick --abort
		fi
	done

	# FIXME: evolve this into an email report to commit authors etc.
	if [ "$(cat $fail_log)" != "" ]; then
		echo "Failed to cherry-pick:"
		cat $fail_log
	fi

	rm -f $log $fail_log
}

function dim_cherry_pick_fixes
{
	assert_branch drm-intel-fixes
	cherry_pick_branch drm-intel-fixes "$@"
}

function dim_cherry_pick_next_fixes
{
	assert_branch drm-intel-next-fixes
	cherry_pick_branch drm-intel-next-fixes "$@"
}

dim_alias_ar=apply-resolved
function dim_apply_resolved
{
	make $DIM_MAKE_OPTIONS && git add -u && git am --resolved
	checkpatch_commit HEAD || true

	eval $DRY $DIM_POST_APPLY_ACTION
}

dim_alias_mrr=magic-rebase-resolve
function dim_magic_rebase_resolve
{
	git diff HEAD | patch -p1 -R
	dim_magic_patch < .git/rebase-merge/patch
	make $DIM_MAKE_OPTIONS
	git add -u
	git rebase --continue
}

dim_alias_mp=magic-patch
function dim_magic_patch
{
	local conflict_files

	if [[ "$1" = "-a" ]]; then
		cd $(cat ~/.dim-last-path)
	fi

	conflict_files=$(patch -p1 | grep "saving rejects" | sed -e "s/.*saving rejects to file \(.*\)/\1/")

	if [[ $conflict_files != "" ]] ; then
		echo conflicts found!
	fi

	for file in $conflict_files ; do
		echo wiggling in ${file%.rej}:
		#cat $file
		rm -f ${file%.rej}.porig
		wiggle -r ${file%.rej} $file || true
	done
}

function dim_create_branch
{
	local branch repo remote

	branch=${1:?$usage}
	start=${2:-HEAD}
	repo="drm-intel"

	cd $DIM_PREFIX/$DIM_REPO

	repo=${branch%%/*}
	branch=${branch#*/}
	if [[ "$repo" = "$branch" ]]; then
		echoerr "give branch in format repo/branch"
		return 1
	fi

	remote=$(repo_to_remote $repo)

	$DRY git branch $branch $start
	git push $DRY_RUN $remote +$branch --set-upstream

	cd $DIM_PREFIX/drm-rerere
	$DRY sed -i "s/^\() # DO NOT CHANGE THIS LINE\)$/\t\"$repo\t\t${branch//\//\\\/}\"\n\1/" $integration_config

	$DRY git add $integration_config
	$DRY git commit --quiet -m "Add $repo $branch to $integration_config"
}

function dim_remove_branch
{
	local branch repo remote

	branch=${1:?$usage}

	cd $DIM_PREFIX/$DIM_REPO

	if [[ -d $DIM_PREFIX/$branch ]] ; then
		rm -R $DIM_PREFIX/$branch
		git worktree prune &> /dev/null || true
	fi

	if git_branch_exists $branch &&
	   ! $DRY git branch -d $branch  ; then
			warn_or_fail "Can't remove $branch in working repo"
	fi

	cd $DIM_PREFIX/drm-tip

	repo=$(branch_to_repo $branch)

	if [[ $repo == "" ]] ; then
		echoerr "$branch not found in $integration_config"
		exit 1
	fi

	remote=$(repo_to_remote $repo)

	git push $DRY_RUN $remote --delete $branch
	$DRY git fetch $remote --prune
	cd $DIM_PREFIX/drm-rerere
	$DRY sed -i "/^[[:space:]]*\"${repo}[[:space:]]\+${branch//\//\\\/}.*$/d" $integration_config

	$DRY git add $integration_config
	$DRY git commit --quiet -m "Remove $repo $branch from $integration_config"

	dim_rebuild_tip
}

function dim_cd
{
	local path

	if [[ -d $DIM_PREFIX/$1 ]] ; then
		path=$DIM_PREFIX/$1
	else
		path=$DIM_PREFIX/$DIM_REPO
	fi

	echo $path > ~/.dim-last-path
	cd $path
}

dim_alias_co=checkout
function dim_checkout
{
	local branch repo remote

	branch=${1:?$usage}

	dim_cd $branch
	if ! git_branch_exists $branch ; then
		repo=$(branch_to_repo $branch)

		if [[ $branch == "drm-intel-next" ]] ; then
			repo="drm-intel"
		fi

		if [[ $repo == "" ]] ; then
			echoerr "$branch not found in $integration_config"
			exit 1
		fi

		remote=$(repo_to_remote $repo)

		if [ "$remote" == "" ] ; then
			exit 1
		fi
		git_fetch_helper $remote
		git checkout -t $remote/$branch
	else
		git checkout $branch
	fi
}

function dim_conq
{
	dim_checkout drm-intel-next-queued "$@"
}

function dim_cof
{
	dim_checkout drm-intel-fixes "$@"
}

function dim_conf
{
	dim_checkout drm-intel-next-fixes "$@"
}

# $1 branch
# $2 commit
function check_maintainer
{
	local branch commit rv

	branch=$1
	commit=$2

        if [ "$branch" = "drm-intel-next-queued" ]; then
		if non_i915_files=$(git diff-tree --no-commit-id --name-only -r $commit | \
			grep -v "^\(drivers/gpu/drm/i915/\|include/drm/i915\|include/uapi/drm/i915\)") && [[ -n "$non_i915_files" ]]; then
			echo -e "The following files are outside of i915 maintenance scope:\n"
			echo "$non_i915_files"
			echo -e "\nConfirm you have appropriate Acked-by and Reviewed-by for above files."
			rv=1
		fi
	fi

	return $rv
}

# $1 is the git sha1 to check
function checkpatch_commit
{
	local commit cmd bug_lines non_i915_files rv

	commit=$1
	cmd="git show --pretty=email $commit"

	git --no-pager log --oneline -1 $commit
	if ! $cmd | scripts/checkpatch.pl -q --emacs --strict -; then
		rv=1
	fi

	if bug_lines=$($cmd | grep -m 1 -B 1 '^\+.*\WBUG' | grep -c '^[+-].*\WBUG') && [[ "$bug_lines" = "1" ]]; then
		echoerr "WARNING: New BUG macro added"
		rv=1
	fi

	return $rv
}

# turn $1 in to a git commit range
function rangeish()
{
	if [ -z "$1" ]; then
		echo "HEAD^..HEAD"
	elif [ -n "$(echo $1 | grep '\.\.')" ]; then
		echo "$1"
	else
		echo "$1..HEAD"
	fi
}

function dim_extract_tags
{
	local branch range file tags

	branch=${1:?$usage}
	range=$(rangeish "${2:-}")
	file=$(mktemp)

	assert_branch $branch
	assert_repo_clean

	cat > $file

	tags=$(message_print_body "$file" | grep -ai '^[^>]*[A-Za-z-]\+: [^ ]')

	rm -f $file

	if [[ -z "$tags" ]]; then
		return 0
	fi

	tags=$(printf -- "# *** extracted tags ***\n%s" "$tags")

	git filter-branch -f --msg-filter "cat ; echo \"$tags\"" $range
}

function dim_extract_queued
{
	dim_extract_tags drm-intel-next-queued "$@"
}

function dim_extract_fixes
{
	dim_extract_tags drm-intel-fixes "$@"
}

function dim_extract_next_fixes
{
	dim_extract_tags drm-intel-next-fixes "$@"
}

dim_alias_check_patch=checkpatch
dim_alias_cp=checkpatch
function dim_checkpatch
{
	local range rv

	range=$(rangeish "${1:-}")

	for commit in $(git rev-list --reverse $range); do
		if ! checkpatch_commit $commit; then
			rv=1
		fi
	done

	return $rv
}

function dim_sparse
{
	local range

	range=$(rangeish "${1:-}")

	make $DIM_MAKE_OPTIONS
	touch --no-create $(git diff --name-only $range) $(git diff --name-only)
	make C=1
}

function dim_checker
{
	rm -f drivers/gpu/drm/i915/*.o drivers/gpu/drm/i915/*.ko
	make C=1 drivers/gpu/drm/i915/i915.ko
}

function prep_pull_mail_greetings
{
	if [ -r $DIM_TEMPLATE_HELLO ]; then
		cat $DIM_TEMPLATE_HELLO
	fi
}

function prep_pull_mail_signature
{
	if [ -r $DIM_TEMPLATE_SIGNATURE ]; then
		cat $DIM_TEMPLATE_SIGNATURE
	fi
}

# print pull mail overview based on tags in $@, if any
# without tags, print a reminder
function prep_pull_mail_overview
{
	local obj

	if [ "$#" = "0" ]; then
		echo "*** PULL REQUEST OVERVIEW HERE ***"
	else
		for tag in "$@"; do
			obj=$(git rev-parse $tag)
			if [[ "$(git cat-file -t $obj)" == "tag" ]] ; then
				echo $tag:
				git cat-file -p $obj | tail -n+6 | sed -n '/^-----BEGIN PGP SIGNATURE-----$/q;p'
			fi
		done
	fi
}

# prepare a pull request mail
# $@: tags, if any, to extract into the pull request overview
function prep_pull_mail
{
	local file
	file=$1
	shift
	prep_pull_mail_greetings > $file
	prep_pull_mail_overview "$@" >> $file
	prep_pull_mail_signature >> $file
}

function dim_create_workdir
{
	local branches

	cd $DIM_PREFIX

	if [[ "x$1" = "x" ]]; then
		echo "usage: $dim $subcommand branch|all"
		exit 1
	elif [[ "$1" = "all" ]] ; then
		branches=$dim_branches
	else
		branches=$1
	fi

	for branch in $branches ; do
		if [[ -d $branch ]] ; then
			continue;
		fi

		echo Creating separate workdir for $branch

		if git help worktree &> /dev/null; then
			# native worktree support was added in git 2.5
			cd $DIM_REPO
			$DRY git worktree prune
			$DRY git worktree add $DIM_PREFIX/$branch $branch
			cd $DIM_PREFIX
		else
			$DRY git-new-workdir $DIM_REPO $branch $branch
		fi
	done
}

dim_alias_fw=for-each-workdir
function dim_for_each_workdir
{
	cd $DIM_PREFIX/$DIM_REPO
	"$@"
	for branch in $dim_branches ; do
		if [[ -d $DIM_PREFIX/$branch ]] ; then
			cd $DIM_PREFIX/$branch
			"$@"
		fi
	done
}

function dim_update_next
{
	local remote

	assert_branch drm-intel-next-queued

	remote=$(repo_to_remote drm-tip)

	git pull --ff-only
	git fetch drm-tip

	if ! git branch --merged $remote/drm-tip | grep -q drm-intel-fixes ; then
		echo "drm-intel-fixes not merged into drm-tip, please update!"
		exit 2
	fi
	if ! git branch --merged $remote/drm-tip | grep -q drm-intel-next-queued ; then
		echo "drm-intel-next-queued not merged into drm-tip, please update!"
		exit 2
	fi

	driver_date=$(date +%Y%m%d)
	driver_timestamp=$(date +%s)
	$DRY sed -i -e "s/^#define DRIVER_DATE.*\"[0-9]*\"$/#define DRIVER_DATE\t\t\"$driver_date\"/; s/^#define DRIVER_TIMESTAMP.*/#define DRIVER_TIMESTAMP\t$driver_timestamp/" \
	     drivers/gpu/drm/i915/i915_drv.h
	$DRY git add drivers/gpu/drm/i915/i915_drv.h
	git commit $DRY_RUN -sm "drm/i915: Update DRIVER_DATE to $driver_date"

	gitk drm-intel-next-queued ^$(repo_to_remote drm-upstream)/drm-next &

	# try to push dinq first in case someone raced
	FORCE=1 dim_push_queued

	dim_update_next_continue
}

function dim_update_next_continue
{
	local remote intel_remote req_file suffix tag tag_testing

	assert_branch drm-intel-next-queued

	intel_remote=$(repo_to_remote drm-intel)
	remote=$(repo_to_remote drm-tip)

	git push $DRY_RUN -f $intel_remote drm-intel-next-queued:drm-intel-next
	tag=drm-intel-next-$dim_today
	tag_testing=drm-intel-testing-$dim_today

	while git tag -l $tag | grep -q $tag ; do
		tag="drm-intel-next-$dim_today-$((++suffix))"
		tag_testing="drm-intel-testing-$dim_today-$((++suffix))"
	done

	$DRY git tag -a $DIM_GPG_KEYID $tag $intel_remote/drm-intel-next
	git push $DRY_RUN $intel_remote $tag

	echo "Updating drm-intel-testing to latest drm-tip"
	git push $DRY_RUN $intel_remote +$remote/drm-tip:drm-intel-testing
	$DRY git tag $tag_testing $intel_remote/drm-intel-testing
	$DRY git push $intel_remote $tag_testing

	req_file=$(mktemp)
	cat > $req_file <<-HERE
		Hi all,

		The following changes tagged $tag_testing:

		HERE

	prep_pull_mail_overview "$tag" >> $req_file
	prep_pull_mail_signature >> $req_file

	$DRY $DIM_MUA -s "Updated drm-intel-testing" \
	     -i $req_file "${test_request_recipients[@]}"
}

function dim_tag_next
{
	local intel_remote tag suffix

	cd $DIM_PREFIX/$DIM_REPO

	intel_remote=$(repo_to_remote drm-intel)
	git fetch $intel_remote

	if [ $(git rev-parse drm-intel-next) == $(git rev-parse "drm-intel-next@{u}") ] ; then
		echo "Tagging current drm-intel-next"

		tag=drm-intel-next-$dim_today
		while git tag -l $tag | grep -q $tag ; do
			tag="drm-intel-next-$dim_today-$((++suffix))"
		done

		$DRY git tag -a $DIM_GPG_KEYID $tag $intel_remote/drm-intel-next
		git push $DRY_RUN $intel_remote $tag
	else
		echo "drm-intel-next not up-to-date, aborting"
		exit
	fi

}

function prep_pull_tag_summary
{
	if [ -r $DIM_TEMPLATE_TAG_SUMMARY ]; then
		cat $DIM_TEMPLATE_TAG_SUMMARY
	else
		cat <<-EOF
		UAPI Changes:

		Cross-subsystem Changes:

		Core Changes:

		Driver Changes:

		EOF
	fi
}

# dim_pull_request branch upstream
function dim_pull_request
{
	local branch upstream remote repo req_file url_list git_url suffix tag

	branch=${1:?$usage}
	upstream=${2:?$usage}
	remote=$(branch_to_remote $branch)
	req_file=$(mktemp)

	if [ "$branch" != "drm-intel-next" ]; then
		assert_branch $branch
	else
		cd $DIM_PREFIX/$DIM_REPO
	fi

	git_fetch_helper ${upstream%%/*}
	echo "Using $upstream as the upstream"

	if [ "$branch" = "drm-intel-next" ]; then
		# drm-intel-next pulls have been tagged using dim update-next
		drm_intel_next_tags=$(git log "$branch@{upstream}" ^$upstream --decorate | grep "(.*tag: drm-intel-next-" | sed -e "s/^.*(.*tag: \(drm-intel-next-[^ ,]*\).*)$/\1/")
		prep_pull_mail $req_file $drm_intel_next_tags
		tag=$(git describe --all --exact "$branch@{upstream}")

		repo="drm-intel"
	else
		tag=$branch-$dim_today

		while git tag -l $tag | grep -q $tag ; do
			tag="$branch-$dim_today-$((++suffix))"
		done
		gitk "$branch@{upstream}" ^$upstream &
		prep_pull_tag_summary | $DRY git tag -F- $tag "$branch@{upstream}"
		$DRY git tag -a $DIM_GPG_KEYID -f $tag
		$DRY git push $remote $tag
		prep_pull_mail $req_file $tag

		repo=$(branch_to_repo $branch)
	fi

	url_list=${drm_tip_repos[$repo]}
	git_url=$(pick_protocol_url git $url_list)

	git request-pull $upstream $git_url $tag >> $req_file
	$DRY $DIM_MUA -s "[PULL] $branch" \
	     -i $req_file "${pull_request_recipients[@]}"
}

function dim_pull_request_next
{
	upstream=${1:-$(repo_to_remote drm-upstream)/drm-next}
	dim_pull_request drm-intel-next $upstream
}

function dim_pull_request_fixes
{
	upstream=${1:-origin/master}
	dim_pull_request drm-intel-fixes $upstream
}

function dim_pull_request_next_fixes
{
	upstream=${1:-$(repo_to_remote drm-upstream)/drm-next}
	dim_pull_request drm-intel-next-fixes $upstream
}

# Note: used by bash completion
function dim_list_upstreams
{
	local dim_drm_upstream_remote

	cd $DIM_PREFIX/$DIM_REPO

	dim_drm_upstream_remote=$(repo_to_remote drm-upstream)

	echo origin/master
	echo $dim_drm_upstream_remote/drm-next
	echo $dim_drm_upstream_remote/drm-fixes
}

# Note: used by bash completion
function dim_list_branches
{
	echo $dim_branches | sed 's/ /\n/g'
}

dim_alias_ub=update-branches
function dim_update_branches
{
	local repo remote intel_remote

	cd $DIM_PREFIX/$DIM_REPO

	for repo in "${!drm_tip_repos[@]}"; do
		remote=$(repo_to_remote $repo)
		echo -n "Fetching $repo (local remote $remote)... "
		git_fetch_helper $remote
		echo "Done."
	done

	assert_repo_clean

	for branch in $dim_branches ; do
		if ! git_branch_exists $branch ; then
			continue
		fi
		dim_checkout $branch
		repo=$(branch_to_repo $branch)
		remote=$(repo_to_remote $repo)

		if ! $DRY git merge --ff-only $remote/$branch; then
			$DRY git rebase -i
		fi
	done
	if git_branch_exists drm-intel-next ; then
		intel_remote=$(repo_to_remote drm-intel)

		dim_checkout drm-intel-next
		$DRY git reset --hard $intel_remote/drm-intel-next
	fi

	cd $DIM_PREFIX/maintainer-tools
	if git_is_current_branch maintainer-tools ; then
		echo "Updating maintainer-tools ..."
		git pull --rebase
	fi

	update_rerere_cache
}

function dim_status
{
	local repo remote drm_remote patches

	cd $DIM_PREFIX/$DIM_REPO

	drm_remote=$(repo_to_remote drm-upstream)

	for branch in $dim_branches ; do
		repo=$(branch_to_repo $branch)
		remote=$(repo_to_remote $repo)

		patches=$(git log --oneline $remote/$branch ^origin/master ^$drm_remote/drm-next ^$drm_remote/drm-fixes | wc -l)

		if [[ $patches -ne 0 ]] ; then
			echo $repo/$branch: $patches unmerged patches
		fi
	done
}

function setup_aux_checkout # name url directory
{
	local name url dir remote

	name=$1
	url=$2
	dir=$3

	echo "Setting up $dir ..."

	if [ ! -d $dir ]; then
		if git help worktree &> /dev/null ; then
			cd $DIM_PREFIX/$DIM_REPO
			remote=$(url_to_remote $url)
			if ! git_branch_exists $name ; then
				git_fetch_helper $remote
				git branch --track $name $remote/$name
			fi
			git worktree add $DIM_PREFIX/$dir $name
		else
			git clone --reference=$DIM_PREFIX/$DIM_REPO/.git $url $dir
			cd $dir
			git config remote.origin.url $url
			echo "$DIM_PREFIX/$DIM_REPO/.git/objects" > .git/objects/info/alternates
			git repack -a -d -l
			remote=origin
		fi
	else
		cd $dir
		remote=$(url_to_remote $url)
	fi
	if ! git_branch_exists $name ; then
		git checkout -t $remote/$name
	fi
	cd - > /dev/null
}

function dim_setup
{
	local remote drm_intel_ssh drm_tip_ssh drm_upstream_git linux_upstream_git

	drm_intel_ssh=ssh://git.freedesktop.org/git/drm-intel
	drm_tip_ssh=ssh://git.freedesktop.org/git/drm-tip
	drm_upstream_git=git://people.freedesktop.org/~airlied/linux
	linux_upstream_git=git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git

	if [ ! -d $DIM_PREFIX ]; then
		echoerr "Directory $DIM_PREFIX doesn't exist."
		echoerr "Please set up your repository directory with"
		echoerr "    mkdir -p $DIM_PREFIX"
		echoerr "or update your configuration (see dimrc.sample)."
		exit 1
	fi
	cd $DIM_PREFIX

	if [ ! -d $DIM_PREFIX/$DIM_REPO/.git ]; then
		echoerr "No git checkout found in $DIM_PREFIX/$DIM_REPO."
		echoerr "Please set up your maintainer linux repository at $DIM_PREFIX/$DIM_REPO with"
		echoerr "    cd $DIM_PREFIX"
		echoerr "    git clone $linux_upstream_git $DIM_REPO"
		echoerr "or update your configuration (see dimrc.sample)."
		exit 1
	fi

	cd $DIM_PREFIX

	setup_aux_checkout maintainer-tools $drm_intel_ssh maintainer-tools

	setup_aux_checkout rerere-cache $drm_tip_ssh drm-rerere

	setup_aux_checkout drm-tip $drm_tip_ssh drm-tip
	cd drm-tip
	if git remote | grep -q drm-upstream ; then
		git config remote.drm-upstream.url $drm_upstream_git
	else
		remote=$(url_to_remote $drm_tip_ssh)
		remote=$(url_to_remote $drm_upstream_git)
	fi

	echo "dim setup successfully completed!"
}

function assert_branch
{
	local branch

	branch=$1

	dim_cd $branch

	if git_is_current_branch $branch ; then
		return 0
	else
		echo "You're on the wrong branch, expected $branch in $PWD"
		return 1
	fi
}

function assert_repo_clean
{
	if [[ -n "$(git status --porcelain --untracked-files=no)" ]]; then
		echo "Repository not clean, aborting."
		exit 1
	fi
}

# Note: used by bash completion
function dim_list_commands
{
	declare -F | grep -o " dim_[a-zA-Z_]*" | sed 's/^ dim_//;s/_/-/g'
}

# Note: used by bash completion
function dim_list_aliases
{
	# use posix mode to omit functions in set output
	( set -o posix; set ) | grep "^dim_alias_[a-zA-Z0-9_]*=" |\
		sed 's/^dim_alias_//;s/=/\t/;s/_/-/g'
}

function dim_cat_to_fixup
{
	cd $DIM_PREFIX/drm-tip
	cat > $(cat .fixup_file_path)
}

function dim_tc
{
	local sha1 tag conf remote_branches

	sha1=${1:?$usage}

	cd $DIM_PREFIX/$DIM_REPO
	tag=$(git tag --contains $sha1 | grep ^v | sort -V | head -n 1)
	if [[ -n "$tag" ]]; then
		echo "$tag"
		return 0
	fi

	# not in a tagged release, show upstream branches
	remote_branches="origin/master"
	for conf in "${drm_tip_config[@]}"; do
		local repo branch override remote

		read -r repo branch override <<< $conf
		remote=$(repo_to_remote $repo)

		remote_branches="$remote_branches $remote/$branch"
	done

	git branch -r --contains $sha1 $remote_branches | sed 's/^ *//' | sort
}

function dim_cite
{
	local sha1

	sha1=${1:?$usage}

	cd $DIM_PREFIX/$DIM_REPO

	git log -1 $sha1 "--pretty=format:%H (\"%s\")%n" | \
		sed -e 's/\([0-f]\{12\}\)[0-f]*/\1/'
}

function dim_fixes
{
	local sha1 tag

	sha1=${1:?$usage}

	cd $DIM_PREFIX/$DIM_REPO
	echo "Fixes: $(dim_cite $sha1)"

	(
		git show --no-patch $sha1 | \
			sed -e 's/\(Reviewed\|Acked\|Reported\|Signed\)[a-zA-Z-]*-by:/Cc:/' | \
			sed -e 's/^    C[Cc]: */Cc: /' | grep '^Cc: '
		git show $sha1 | scripts/get_maintainer.pl  --email --norolestats --pattern-depth 1 | sed -e "s/^/Cc: /"
	) | awk '!x[$0]++'

	tag=$(git tag --contains $sha1 | grep ^v | sort -V | head -n 1)
	if [[ -n "$tag" ]]; then
		if ! echo "$tag" | grep -q -e "-rc"; then
			echo "Cc: <stable@vger.kernel.org> # ${tag}+"
		fi
	fi
}

function dim_add_missing_cc
{
	local email name matches

	git show | scripts/get_maintainer.pl --email --norolestats --pattern-depth 1 | while read -r cc; do
		email="$(echo "$cc" | sed -e 's/.*<//' -e 's/>.*//')"
		name=''

		if echo "$cc" | grep -q '<'; then
			name="$(echo ${cc/<*/} | sed -e 's/[[:space:]]*\$//')";
		fi

		# Don't add main mailing lists
		if [[ "$email" = "dri-devel@lists.freedesktop.org" || \
		      "$email" = "linux-kernel@vger.kernel.org}" ]]; then
			continue
		fi

		# Variables from the while loop don't propagate,
		# print out a 1 on success
		matches=$(
			git show -s | grep -i "^    Cc:" | sed 's/^ *[Cc][Cc]: *//' | while read -r testcc; do
				testemail="$(echo "$testcc" | sed -e 's/.*<//' -e 's/>.*//')"

				if [ "$testemail" != "$email" ]; then
					if [ -z "$name" ]; then continue; fi

					testname="$(echo ${testcc/<*/} | sed -e 's/[[:space:]]*\$//' -e 's/^[[:space:]]*//')"

					if [ "$testname" != "$name" ]; then continue; fi
				fi

				echo 1
				break
			done
		)

		if [ -z "$matches" ]; then
			$DRY dim_commit_add_tag "Cc: ${cc}"
		fi
	done
}

function dim_help
{
	manpage=$DIM_PREFIX/maintainer-tools/dim.rst
	if [ ! -e "$manpage" ]; then
		manpage=$(dirname $(readlink -f $0))/dim.rst
		if [ ! -e "$manpage" ]; then
			echo "Can't find the man page. See http://cgit.freedesktop.org/drm-intel/tree/dim.rst?h=maintainer-tools"
			exit 1
		fi
	fi

	if hash rst2man 2>/dev/null; then
		renderer=rst2man
		pager="man -l -"
	else
		renderer=cat
		pager=${PAGER:-cat}
	fi

	$renderer < $manpage | $pager
}

function dim_usage
{
	echo "usage: $dim [OPTIONS] SUBCOMMAND [ARGUMENTS]"
	echo
	echo "The available subcommands are:"
	if hash column 2>/dev/null; then
		dim_list_commands | column -c 72 | sed 's/^/\t/'
	else
		dim_list_commands | sed 's/^/\t/'
	fi
	echo
	echo "See '$dim help' for more information."
}

# occasional check for dim updates
check_for_updates

# dim subcommand aliases (with bash 4.3+)
if ! declare -n subcmd=dim_alias_${subcommand//-/_} &> /dev/null || \
		test -z "${subcmd:-}"; then
	subcmd="$subcommand"
fi

# look up the function by the subcommand name
subcmd_func=dim_${subcmd//-/_}
if ! declare -f $subcmd_func >/dev/null; then
	echoerr "'$subcommand' is not a dim command."
	dim_usage
	exit 1
fi

# throw away to not confuse list-aliases
unset subcmd

$subcmd_func "$@"