summaryrefslogtreecommitdiff
path: root/bin/git_gpush.pm
blob: f5972914e9eb7f65734c24881d65511780e5f27a (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
# Copyright (C) 2017 The Qt Company Ltd.
# Copyright (C) 2019 Oswald Buddenhagen
# Contact: http://www.qt.io/licensing/
#
# You may use this file under the terms of the 3-clause BSD license.
# See the file LICENSE from this package for details.
#

package git_gpush;

use v5.14;
use strict;
use warnings;
no warnings qw(io);

use Carp;
$SIG{__WARN__} = \&Carp::cluck;
$SIG{__DIE__} = \&Carp::confess;

use List::Util qw(min max);
use File::Spec;
use File::Temp qw(mktemp);
use IPC::Open3 qw(open3);
use Symbol qw(gensym);
use Term::ReadKey;
use Text::Wrap;
use JSON;

our @_imported;
BEGIN {
    no strict 'refs';
    @_imported = keys %{__PACKAGE__.'::'};
}

##################
# shared options #
##################

our $debug = 0;
our $verbose = 0;
our $quiet = 0;
our $dry_run = 0;

##################
# message output #
##################

$| = 1;  # OUTPUT_AUTOFLUSH; in case we're redirecting debug output.

my ($tty_width, undef, undef, undef) = (-t STDOUT) ? GetTerminalSize() : (80);

# This is for messages which even after wrapping will rarely/barely
# exceed a single line, so it does not matter that the output possibly
# violates the "no more than 80 columns for flowed text" guideline.
sub _wrap_wide($)
{
    $Text::Wrap::columns = $tty_width + 1;
    return wrap("", "", $_[0]);
}

sub wout($)
{
    print _wrap_wide($_[0]);
}

sub werr($)
{
    print STDERR _wrap_wide($_[0]);
}

sub wfail($)
{
    werr($_[0]);
    exit(1);
}

# This is for bigger amounts of text.
sub _wrap_narrow($)
{
    $Text::Wrap::columns = min($tty_width, 80) + 1;
    return wrap("", "", $_[0]);
}

sub nwout($)
{
    print _wrap_narrow($_[0]);
}

sub nwerr($)
{
    print STDERR _wrap_narrow($_[0]);
}

sub nwfail($)
{
    nwerr($_[0]);
    exit(1);
}

sub fail($)
{
    print STDERR $_[0];
    exit(1);
}

#######################
# subprocess handling #
#######################

use constant {
    NUL_STDIN => 0,
    USE_STDIN => 1,
    FWD_STDIN => 2,
    NUL_STDOUT => 0,
    USE_STDOUT => 4,
    FWD_STDOUT => 8,
    NUL_STDERR => 0,
    USE_STDERR => 16,
    FWD_STDERR => 32,
    FWD_OUTPUT => 40,
    SILENT_STDIN => 64,  # Suppress debug output for stdin
    SOFT_FAIL => 256,    # A non-zero exit from the process is not fatal
    DRY_RUN => 512       # Don't actually run the command if $dry_run is true
};

sub _format_cmd(@)
{
    return join(' ', map { /\s/ ? '"' . $_ . '"' : $_ } @_);
}

sub open_process($@)
{
    my ($flags, @cmd) = @_;
    my %process;

    $flags &= ~DRY_RUN if (!$dry_run);
    $process{flags} = $flags;
    if ($flags & DRY_RUN) {
        print "+ "._format_cmd(@cmd)." [DRY]\n" if ($debug);
        return \%process;
    }
    my $cmd = _format_cmd(@cmd);
    $process{cmd} = $cmd;
    my ($in, $out, $err);
    if ($flags & USE_STDIN) {
        $in = \$process{stdin};
    } elsif ($flags & FWD_STDIN) {
        # open3() closes the handle input is redirected from, which is
        # most definitely not what we want to happen to stdin.
        no warnings 'once';  # The parser doesn't see the string reference.
        open INPUT, '<&STDIN' or wfail("Failed to dup() stdin: $!\n");
        $in = \'<&INPUT';
    } else {
        $in = \'<&NUL';
    }
    if ($flags & USE_STDOUT) {
        $out = \$process{stdout};
    } elsif ($flags & FWD_STDOUT) {
        $out = \'>&STDOUT';
    } else {
        $out = \'>&NUL';
    }
    if ($flags & USE_STDERR) {
        $err = \$process{stderr};
        $$err = gensym();
    } elsif ($flags & FWD_STDERR) {
        $err = \'>&STDERR';
    } else {
        $err = \'>&NUL';
    }
    print "+ $cmd\n" if ($debug);
    open(NUL, '>'.File::Spec->devnull()) or wfail("Failed to open bitbucket: $!\n");
    eval { $process{pid} = open3($$in, $$out, $$err, @cmd); };
    wfail("Failed to run \"$cmd[0]\": $!\n") if ($@);
    close(NUL);
    return \%process;
}

sub close_process($)
{
    my ($process) = @_;

    if ($$process{flags} & DRY_RUN) {
        $? = 0;
        return 0;
    }
    my $cmd = $$process{cmd};
    if ($$process{stdout}) {
        close($$process{stdout}) or wfail("Failed to close read pipe of '$cmd': $!\n");
    }
    if ($$process{stderr}) {
        close($$process{stderr}) or wfail("Failed to close error read pipe of '$cmd': $!\n");
    }
    waitpid($$process{pid}, 0) or wfail("Failed to wait for '$cmd': $!\n");
    if ($? & 128) {
        wfail("'$cmd' crashed with signal ".($? & 127).".\n") if ($? != 141); # allow SIGPIPE
        $? = 0;
    } elsif ($? && !($$process{flags} & SOFT_FAIL)) {
        exit($? >> 8);
    }
    return 0;
}

# Write any number of lines to the process' stdin.
# The input is expected to already contain trailing newlines.
# This function must be called exactly once iff USE_STDIN is used.
# Note that this will deadlock with USE_STDOUT if the process outputs
# too much before all input is written.
sub write_process($@)
{
    my ($process, @input) = @_;

    my $stdin = $$process{stdin};
    my $silent = ($$process{flags} & SILENT_STDIN);
    my $dry = ($$process{flags} & DRY_RUN);
    local $SIG{PIPE} = "IGNORE";
    foreach (@input) {
        print "> $_" if ($debug && !$silent);
        print $stdin $_ if (!$dry);
    }
    $dry or close($stdin) or wfail("Failed to close write pipe of '$$process{cmd}': $!\n");
}

# Read a line from the process' stdout.
sub read_process($)
{
    my ($process) = @_;

    my $fh = $$process{stdout};
    $_ = <$fh>;
    if (defined($_)) {
        chomp;
        print "- $_\n" if ($debug);
    }
    return $_;
}

# Read all lines from the process' stdout.
sub read_process_all($)
{
    my ($process) = @_;

    my $fh = $$process{stdout};
    my @lines = <$fh>;
    chomp @lines;
    printf("Read %d lines.\n", int(@lines)) if ($debug);
    return \@lines;
}

# Read any number of null-terminated fields from the process' stdout.
sub read_fields($@)
{
    my $process = shift;
    my $fh = $$process{stdout};
    return 0 if (eof($fh));
    local $/ = "\0";
    for (@_) { chop($_ = <$fh>); }
    return 1;
}

# Read all of a process' output channel as a single string.
sub get_process_output($$)
{
    my ($process, $which) = @_;

    local $/;
    my $fh = $$process{$which};
    return <$fh>;
}

# The equivalent of system().
sub run_process($@)
{
    my ($flags, @cmd) = @_;

    close_process(open_process($flags, @cmd));
}

# The equivalent of popen("r").
sub open_cmd_pipe($@)
{
    my ($flags, @cmd) = @_;

    return open_process(USE_STDOUT | FWD_STDERR | $flags, @cmd);
}

# Run the specified command and try to read exactly one line from its stdout.
sub read_cmd_line($@)
{
    my ($flags, @cmd) = @_;

    my $proc = open_cmd_pipe($flags, @cmd);
    read_process($proc);
    close_process($proc);
    return $_;
}

##############
# git basics #
##############

our $gitdir;  # $GIT_DIR
our $gitcommondir;  # $GIT_COMMON_DIR

sub goto_gitdir()
{
    my $cdup = read_cmd_line(0, 'git', 'rev-parse', '--show-cdup');
    fail("fatal: This operation must be run in a work tree\n") if (!defined($cdup));
    chdir($cdup) unless ($cdup eq "");
    $gitdir = read_cmd_line(0, 'git', 'rev-parse', '--git-dir');
    $gitcommondir = read_cmd_line(0, 'git', 'rev-parse', '--no-flags', '--git-common-dir');
}

# `git config --list` output, plus contents of .git-gpush-aliases' [config]
our %gitconfig;  # { key => [ value, ... ] }

sub _load_git_config()
{
    # Read all git configuration at once, as that's faster than repeated
    # git invocations, especially under Windows.
    my $cfg = open_cmd_pipe(0, 'git', 'config', '-l', '-z');
    while (read_fields($cfg, my $entry)) {
        $entry =~ /^([^\n]+)\n(.*)$/;
        push @{$gitconfig{$1}}, $2;
    }
    close_process($cfg);
}

sub git_configs($)
{
    my ($key) = @_;
    my $ref = $gitconfig{$key};
    return defined($ref) ? @$ref : ();
}

sub git_config($;$)
{
    my ($key, $dflt) = @_;
    my @cfg = git_configs($key);
    return scalar(@cfg) ? $cfg[-1] : $dflt;
}

our $_indexfile;
END { unlink($_indexfile) if ($_indexfile); }

sub with_local_git_index($@)
{
    my ($callback, @args) = @_;

    $_indexfile = mktemp(($ENV{TMPDIR} or "/tmp") . "/git-gpush.XXXXXX");
    local $ENV{GIT_INDEX_FILE} = $_indexfile;

    local ($SIG{HUP}, $SIG{INT}, $SIG{QUIT}, $SIG{TERM});
    $SIG{HUP} = $SIG{INT} = $SIG{QUIT} = $SIG{TERM} = sub { exit; };

    my $ret = $callback->(@args);

    unlink($_indexfile);
    $_indexfile = undef;

    return $ret;
}

#################
# configuration #
#################

sub _file_contents($)
{
    my ($filename) = @_;

    my @contents = "";
    my $fh;
    if (-e $filename && open($fh, "< $filename")) {
        @contents = <$fh>;
        close $fh;
    }
    return @contents;
}

our %aliases;  # { alias => login }

sub load_config()
{
    # Read config from .git-gpush-aliases file
    my $in_aliases = 1;
    foreach my $line (_file_contents($::script_path."/.git-gpush-aliases")) {
        chomp $line;
        $line =~ s,(#|//).*$,,;  # Remove any comments
        if ($line =~ /^\[([^]]+)\]/) {
            if ($1 eq "aliases") {
                $in_aliases = 1;
            } elsif ($1 eq "config") {
                $in_aliases = 0;
            } else {
                fail("Unrecognized section '$1' in alias file.\n");
            }
        } elsif ($line =~ /^\s*([^ =]+)\s*=\s*(.*?)\s*$/) {  # Capture the value
            if ($in_aliases) {
                for my $alias (split(/,/, $1)) {
                    $aliases{$alias} = $2;
                }
            } else {
                push @{$gitconfig{"gpush.$1"}}, $2;
            }
        }
    }

    _load_git_config();

    foreach (keys %gitconfig) {
        if (/^gpush\.alias\.(.*)$/) {
            $aliases{$1} = git_config($_);
        }
    }
}

######################
# branches & remotes #
######################

# The name of the local branch we're working with (not necessarily the
# current branch). May be undef.
our $local_branch;
# The tips of the local and remote branches.
our %local_refs;  # { branch => sha1 }
our %remote_refs;  # { remote => { branch => sha1 } }

# The name of the local branch's upstream remote, or a configurable fallback.
our $upstream_remote;
# The name of the Gerrit remote, possibly identical to the upstream remote.
our $remote;

# The tips of the remote branches which are excluded from commit listings.
# The commits are already prepared for git-rev-list (prefixed with '^').
our @upstream_excludes;

sub update_excludes()
{
    my %heads;
    my $urefs = $remote_refs{$upstream_remote};
    if ($urefs) {
        $heads{$_} = 1 foreach (values %$urefs);
    }
    my $grefs = $remote_refs{$remote};
    if ($grefs) {
        $heads{$_} = 1 foreach (values %$grefs);
    }
    @upstream_excludes = map { "^$_" } keys %heads;
}

sub setup_remotes($)
{
    my ($source) = @_;

    my %remotes;
    for my $ky (keys %gitconfig) {
        if ($ky =~ /^remote\.(.*)\.url$/) {
            $remotes{$1} = 1;
        }
    }
    fail("No remotes configured.\n")
        if (!%remotes);
    if (defined($local_branch)) {
        $upstream_remote = git_config("branch.$local_branch.remote");
        fail("$source has invalid upstream remote '$upstream_remote'.\n")
            if (defined($upstream_remote) && !defined($remotes{$upstream_remote}));
    }
    if (!defined($upstream_remote)) {
        $upstream_remote = git_config('gpush.upstream');
        if (defined($upstream_remote)) {
            fail("Remote '$upstream_remote' configured in gpush.upstream is invalid.\n")
                if (!defined($remotes{$upstream_remote}));
        } else {
            $upstream_remote = 'origin';
            if (!defined($remotes{$upstream_remote})) {
                my @remotes_arr = keys %remotes;
                fail("$source has no upstream remote, and cannot guess one.\n")
                    if (@remotes_arr != 1);
                $upstream_remote = $remotes_arr[0];
            }
        }
        wout("Notice: $source has no upstream remote; defaulting to $upstream_remote.\n")
            if (!$quiet);
    }
    if (defined($remote)) {
        fail("Specified Gerrit remote '$remote' is invalid.\n")
            if (!defined($remotes{$remote}));
    } else {
        $remote = git_config('gpush.remote');
        # If a remote is configured, use exactly that one.
        if (defined($remote)) {
            fail("Remote '$remote' configured in gpush.remote is invalid.\n")
                if (!defined($remotes{$remote}));
        } else {
            # Otherwise try 'gerrit', and fall back to the upstream remote.
            $remote = 'gerrit';
            $remote = $upstream_remote if (!defined($remotes{$remote}));
        }
    }
    update_excludes();
}

###################
# commit metadata #
###################

our %commit_by_id;

sub init_commit($)
{
    my ($commit) = @_;

    my $id = $$commit{id};
    # Duplicating is bad, because it would discard members which are not
    # necessarily re-instantiated. Also, it's an indicator of inefficiency.
    die("Commit $id already instantiated")
        if ($commit_by_id{$id});
    $commit_by_id{$id} = $commit;
}

sub changes_from_commits($)
{
    my ($commits) = @_;

    return [ map { $$_{change} } @$commits ];
}

sub get_1st_commit($)
{
    my ($parents) = @_;

    return @$parents ? $$parents[0] : 'ROOT';
}

sub get_1st_parent($)
{
    my ($commit) = @_;

    my $parents = $$commit{parents};
    return @$parents ? $$parents[0] : 'ROOT';
}

sub get_1st_parent_tree($)
{
    my ($commit) = @_;

    # Upstream commits are not visited, so we get no tree id. However,
    # as this code aims at series which were not rebased, using the base
    # commit itself will work just as well for the series' first commit.
    my $parents = $$commit{parents};
    my $parent_id = @$parents ? $$parents[0] : 'ROOT';
    my $parent = $commit_by_id{$parent_id};
    return $parent ? $$parent{tree} : $parent_id;
}

sub get_more_parents($)
{
    my ($commit) = @_;

    my $parents = $$commit{parents};
    return @$parents > 1 ? "@$parents[1..$#$parents]" : "";
}

# Enumerate commits from the specified tip down to the merge base
# with upstream. Merges are handled in --first-parent mode.
sub get_commits_free($)
{
    my ($tip) = @_;

    my @commits;
    while (1) {
        my $commit = $commit_by_id{$tip};
        last if (!$commit);
        unshift @commits, $commit;
        $tip = get_1st_parent($commit);
    }
    return \@commits;
}

# Enumerate the specified number of commits from the specified tip.
# Merges are treated in --first-parent mode.
sub get_commits_count($$$)
{
    my ($tip, $count, $tip_raw) = @_;

    my @commits;
    for (1 .. $count) {
        my $commit = $commit_by_id{$tip};
        wfail("Range $tip_raw:$count extends beyond the local branch.\n")
            if (!$commit);
        unshift @commits, $commit;
        $tip = get_1st_parent($commit);
    }
    return \@commits;
}

# Enumerate commits from the specified tip down to the specified base.
# Merges are treated in --first-parent mode.
sub get_commits_base($$$$)
{
    my ($base, $tip, $base_raw, $tip_raw) = @_;

    # An empty base is understood to mean the merge base with upstream.
    # This avoids the need to figure out the actual commit, which is
    # particularly useful in the presence of multiple bases due to merges.
    return get_commits_free($tip) if (!length($base));

    my @commits;
    while ($tip ne $base) {
        my $commit = $commit_by_id{$tip};
        wfail("$base_raw is not an ancestor of $tip_raw within the local branch.\n")
            if (!$commit);
        unshift @commits, $commit;
        $tip = get_1st_parent($commit);
    }
    return \@commits;
}

########################
# gerrit query results #
########################

use constant {
    RVRTYPE_NONE => 0,
    RVRTYPE_REV => 1,
    RVRTYPE_CC => 1  # Because Gerrit won't tell.
};

our %gerrit_info_by_key;
our %gerrit_info_by_sha1;
our %gerrit_infos_by_id;

##################
# state handling #
##################

# This is built upon Change objects with these attributes:
# - key: Sequence number. This runs independently from Gerrit, so
#   we can enumerate Changes which were never pushed, and to make
#   it possible to re-associate local Changes with remote ones.
# - id: Gerrit Change-Id.
# - src: Local branch name, or "-" if Change is on a detached HEAD.
# - tgt: Target branch name.
# - topic: Gerrit topic. Persisted only as a cache.
# - pushed: SHA1 of the commit this Change was pushed as last time
#   from this repository.
# - base: SHA1 of commit on top of which the entire series which this
#   Change is part of was pushed.
# - orig: SHA1 of the _local_ commit 'pushed' was derived from.

my $next_key = 10000;
# All known Gerrit Changes for the current repository.
our %change_by_key;  # { sequence-number => change-object }
# Same, indexed by Gerrit Change-Id. A Change can exist on multiple branches.
our %changes_by_id;  # { gerrit-id => [ change-object, ... ] }

our $last_gc = 0;

my $state_lines;
my $state_updater = ($0 =~ s,^.*/,,r)." @ARGV";

# Perform a batch update of refs.
sub update_refs($$)
{
    my ($flags, $updates) = @_;

    if (!@$updates) {
        print "No refs to update.\n" if ($debug);
        return;
    }
    my $pipe = open_process(USE_STDIN | FWD_STDERR | $flags, "git", "update-ref", "--stdin");
    write_process($pipe, @$updates);
    close_process($pipe);
}

sub _commit_state($$)
{
    my ($blob, $new) = @_;

    run_process(0, 'git', 'update-index', '--add', '--cacheinfo', "100644,$blob,state");
    my $tree = read_cmd_line(0, 'git', 'write-tree');
    my $sha1 = read_cmd_line(0, 'git', 'commit-tree', '-m', 'Saving state', $tree);
    if ($new) {
        run_process(0, 'git', 'update-ref', 'refs/gpush/state-new', $sha1);
        return;
    }
    run_process(0, 'git', 'update-ref', '-m', $state_updater,
                   '--create-reflog', 'refs/gpush/state', $sha1);
}

sub save_state(;$$)
{
    my ($dry, $new) = @_;

    print "Saving ".($new ? "new " : "")."state".($dry ? " [DRY]" : "")." ...\n" if ($debug);
    my (@lines, @updates);
    my @fkeys = ('key', 'id', 'src', 'tgt', 'topic', 'base');
    my @rkeys = ('pushed', 'orig');
    if ($new) {
        push @lines, "verify $new", "updater $state_updater";
        push @fkeys, @rkeys;
        @rkeys = ();
    }
    push @lines,
        "next_key $next_key",
        "last_gc $last_gc",
        "";
    foreach my $key (sort keys %change_by_key) {
        my $change = $change_by_key{$key};
        my $garbage = $$change{garbage};
        foreach my $ky (@rkeys) {
            my ($val, $oval) = ($garbage ? undef : $$change{$ky}, $$change{'_'.$ky});
            if (!defined($val)) {
                push @updates, "delete refs/gpush/i${key}_$ky\n"
                    if (defined($oval));
            } else {
                push @updates, "update refs/gpush/i${key}_$ky $val\n"
                    if (!defined($oval) || ($oval ne $val));
            }
            $$change{'_'.$ky} = $val;
        }
        next if ($garbage);
        foreach my $ky (@fkeys) {
            my $val = $$change{$ky};
            if (defined($val)) {
                push @lines, "$ky $val";
            }
        }
        push @lines, "";
    }
    foreach my $ginfo (values %gerrit_info_by_key) {
        my $fetched = $$ginfo{fetched};
        next if (!defined($fetched));
        my $_fetched = \%{$$ginfo{_fetched}};
        for my $ky (keys %$fetched) {
            my ($val, $oval) = ($$fetched{$ky}, $$_fetched{$ky});
            if (!defined($val)) {
                push @updates, "delete refs/gpush/g$$ginfo{key}_$ky\n"
                    if (defined($oval));
            } else {
                push @updates, "update refs/gpush/g$$ginfo{key}_$ky $val\n"
                    if (!defined($oval) || ($oval ne $val));
            }
            $$_fetched{$ky} = $val;
        }
    }
    update_refs($dry ? DRY_RUN : 0, \@updates);

    # We save the state file in a git ref as well, so the entire state
    # can be synced between hosts with git operations.
    if ($new || ("@lines" ne "@$state_lines")) {
        my $sts = open_process(USE_STDIN | SILENT_STDIN | USE_STDOUT | FWD_STDERR,
                               'git', 'hash-object', '-w', '--stdin');
        write_process($sts, map { "$_\n" } @lines);
        my $blob = read_process($sts);
        close_process($sts);
        with_local_git_index(\&_commit_state, $blob, $new) if (!$dry);
        $state_lines = \@lines;
    } else {
        print "State file unmodified.\n" if ($debug);
    }
}

# Constructor for the Change object.
sub _init_change($$)
{
    my ($change, $changeid) = @_;

    print "Creating Change $next_key ($changeid).\n" if ($debug);
    $$change{key} = $next_key;
    $$change{id} = $changeid;
    push @{$changes_by_id{$changeid}}, $change;
    $change_by_key{$next_key} = $change;
    $next_key++;
}

use constant {
    CREATE => 1
};

# Get a Change object for a given Id on the _local_ branch. If no such
# object exists, create a new one if requested, otherwise return undef.
sub change_for_id($;$)
{
    my ($changeid, $create) = @_;

    my $br = $local_branch // "-";
    my $chgs = $changes_by_id{$changeid};
    if ($chgs) {
        foreach my $chg (@$chgs) {
            return $chg if ($$chg{src} eq $br);
        }
    }
    if ($create) {
        my %chg = (src => $br);
        _init_change(\%chg, $changeid);
        return \%chg;
    }
    return undef;
}

sub load_state_file(;$)
{
    my ($new) = @_;

    my $ref = $new ? "state-new" : "state";
    my $sts = open_process(SOFT_FAIL | USE_STDOUT | NUL_STDERR,
                           'git', 'cat-file', '-p', "refs/gpush/$ref:state");
    $state_lines = read_process_all($sts);
    close_process($sts);
    return if (!@$state_lines);

    my $state_verify;
    my $line = 0;
    my $inhdr = 1;
    my $change;
    my @changes;
    foreach (@$state_lines) {
        $line++;
        if (!length($_)) {
            $inhdr = 0;
            $change = undef;
        } elsif (!/^(\w+) (.*)/) {
            fail("Bad state file: Malformed entry at line $line.\n");
        } elsif ($inhdr) {
            if ($1 eq "next_key") {
                $next_key = int($2);
            } elsif ($1 eq "last_gc") {
                $last_gc = int($2);
            } elsif ($new && ($1 eq "verify")) {
                $state_verify = $2;
            } elsif ($new && ($1 eq "updater")) {
                $state_updater = $2;
            } else {
                fail("Bad state file: Unknown header keyword '$1' at line $line.\n");
            }
        } else {
            if (!$change) {
                $change = {};
                $$change{line} = $line;
                push @changes, $change;
            }
            $$change{$1} = $2;
        }
    }

    foreach my $change (@changes) {
        my $line = $$change{line};
        my ($key, $id) = ($$change{key}, $$change{id});
        fail("Bad state file: Change with no key at line $line.\n") if (!$key);
        fail("Bad state file: Change with no id at line $line.\n") if (!$id);
        fail("Bad state file: Change with duplicate id at line $line.\n")
            if (defined($change_by_key{$key}));
        $change_by_key{$key} = $change;
        push @{$changes_by_id{$id}}, $change;
    }

    return $state_verify;
}

sub load_refs(@)
{
    my (@refs) = @_;

    my @updates;
    my $info = open_cmd_pipe(0, 'git', 'for-each-ref', '--format=%(objectname) %(refname)', @refs);
    while (read_process($info)) {
        if (m,^(.{40}) refs/heads/(.*)$,) {
            $local_refs{$2} = $1;
        } elsif (m,^(.{40}) refs/remotes/([^/]+)/(.*)$,) {
            $remote_refs{$2}{$3} = $1;
        } elsif (m,^(.{40}) refs/gpush/i(\d+)_(.*)$,) {
            my $change = $change_by_key{$2};
            if (!$change) {
                my $ref = substr($_, 41);
                werr("Warning: Unrecognized Change key in state ref $ref - dropping.\n");
                # It would cause trouble once the key is re-used.
                push @updates, "delete $ref\n";
                next;
            }
            $$change{$3} //= $1;  # Don't overwrite value from new file.
            $$change{'_'.$3} = $1;
        } elsif (m,^(.{40}) refs/gpush/g(\d+)_(\d+)$,) {
            my $ginfo = \%{$gerrit_info_by_key{$2}};
            $$ginfo{key} = $2;
            $$ginfo{fetched}{$3} = $1;
            $$ginfo{_fetched}{$3} = $1;
        }
    }
    close_process($info);
    update_refs(0, \@updates);
}

sub load_state($)
{
    my ($all) = @_;

    print "Loading state ...\n" if ($debug);
    load_state_file();
    load_refs($all ? "refs/gpush/" : "refs/gpush/i*", "refs/heads/", "refs/remotes/");
}

##########################
# commit metadata output #
##########################

# Don't let lists get arbitrarily wide, as this makes them hard to follow.
use constant _LIST_WIDTH => 120;
# The _minimal_ width assumed for annotations, even if absent. This
# ensures that annotations always "stick out" on the right, even if only
# short subjects have annotations.
use constant _ANNOTATION_WIDTH => 6;
# Elide over-long Change subjects, as they add nothing but noise.
use constant _SUBJECT_WIDTH => 70;
# Truncation width for Change-Ids and SHA1s; empirically determined to be
# "sufficiently unambiguous".
use constant _ID_WIDTH => 10;

sub format_id($)
{
    my ($id) = @_;

    return substr($id, 0, _ID_WIDTH);
}

sub format_subject($$;$)
{
    my ($id, $subject, $max) = @_;

    $max = _SUBJECT_WIDTH if (!defined($max));
    $max += $tty_width if ($max < 0);
    $max -= _ID_WIDTH + 3 if (defined($id));
    $max = max(25, min(_SUBJECT_WIDTH, $max)) - 5;
    # Right-elide if subject is longer than $max + ellipsis:
    $subject =~ s/^(.{$max}).{6,}$/$1\[...]/;
    return $subject if (!defined($id));
    return format_id($id)." ($subject)";
}

sub format_commit($;$)
{
    my ($commit, $max) = @_;
    return format_subject($$commit{changeid}, $$commit{subject}, $max);
}

sub format_commits($;$)
{
    my ($commits, $prefix) = @_;

    $prefix = "  " if (!defined($prefix));
    my $output = "";
    foreach my $commit (@$commits) {
        $output .= $prefix.format_commit($commit, -length($prefix))."\n";
    }
    return $output;
}

sub _unpack_report($@)
{
    my $report = shift @_;
    my @a = ($$report{id}, $$report{subject},
             $$report{prefix} // "", $$report{suffix} // "", $$report{annotation} // "");
    push @a, length($a[2]) + length($a[3]) + max(length($a[4]), _ANNOTATION_WIDTH);
    for (@_) { $_ = shift @a; }
}

sub format_reports($)
{
    my ($reports) = @_;

    my $width = 0;
    foreach my $report (@$reports) {
        next if ($$report{type} ne "change");
        _unpack_report($report, my ($id, $subject, $pfx_, $sfx_, $ann_, $fixlen));
        my $w = length($subject);
        $w += _ID_WIDTH + 3 if (defined($id));
        $width = max($width, min($w, _SUBJECT_WIDTH) + $fixlen);
    }
    $width = min($width, $tty_width, _LIST_WIDTH);
    my $output = "";
    foreach my $report (@$reports) {
        my $type = $$report{type} // "";
        if ($type eq "flowed") {
            $output .= wrap("", "", $_)."\n" foreach (@{$$report{texts}});
        } elsif ($type eq "fixed") {
            $output .= join("", @{$$report{texts}});
        } elsif ($type eq "change") {
            _unpack_report($report, my ($id, $subject, $prefix, $suffix, $annot, $fixlen));
            my $w = $width - $fixlen;
            my $str = format_subject($id, $subject, min($w, _SUBJECT_WIDTH));
            my $spacing = length($annot) ? (" " x max($w - length($str), 0)) : "";
            $output .= $prefix.$str.$suffix.$spacing.$annot."\n";
        } else {
            die("Unknown report type '$type'.\n");
        }
    }
    return $output;
}

sub fail_formatted($)
{
    my ($reports) = @_;

    fail(format_reports($reports));
}

sub report_text($$@)
{
    my ($reports, $type, @texts) = @_;

    push @$reports, {
        type => $type,
        texts => \@texts
    };
}

sub report_flowed($@)
{
    my ($reports, @texts) = @_;

    push @$reports, {
        type => "flowed",
        texts => \@texts
    };
}

sub report_fixed($@)
{
    my ($reports, @texts) = @_;

    push @$reports, {
        type => "fixed",
        texts => \@texts
    };
}

sub set_change_error($$$)
{
    my ($change, $style, $error) = @_;

    ($$change{error_style}, $$change{error}) = ($style, $error);
}

sub report_local_changes($$)
{
    my ($reports, $changes) = @_;

    foreach my $change (@$changes) {
        my $commit = $$change{local};
        push @$reports, {
            type => "change",
            id => $$commit{changeid},
            subject => $$commit{subject},
            prefix => "  ",
            annotation => $$change{annotation}
        };
        my $error = $$change{error};
        if (defined($error)) {
            $error = (" " x (3 + _ID_WIDTH)).$error."\n"
                if (($$change{error_style} // 'oneline') eq 'oneline');
            report_fixed($reports, $error);
        }
    }
}

#############################
# commit metadata retrieval #
#############################

use constant _GIT_LOG_ARGS =>
        ('-z', '--pretty=%H%x00%P%x00%T%x00%B%x00%an%x00%ae%x00%ad%x00%cn%x00%ce%x00%cd');

# Retrieve metadata for commits reachable from the specified tips.
sub visit_commits_raw($$;$)
{
    my ($tips, $args, $cid_opt) = @_;

    return if (!@$tips);

    my @commits;
    my $log = open_process(USE_STDIN | USE_STDOUT | FWD_STDERR,
                           'git', 'log', _GIT_LOG_ARGS, @$args, '--stdin');
    write_process($log, map { "$_\n" } @$tips);
    my @author = (undef, undef, undef);
    my @committer = (undef, undef, undef);
    while (read_fields($log, my ($id, $parents, $tree, $message), @author, @committer)) {
        # We truncate the subject anyway, so using just the first line is OK.
        $message =~ /^(.*)$/m;
        my $subject = $1;

        my @cids = ($message =~ /^Change-Id: (.+)$/mg);
        my $changeid;
        if (!@cids) {
            fail(format_subject($id, $subject, -18)." has no Change-Id.\n")
                if (!$cid_opt);
        } else {
            # Gerrit uses the last Change-Id if multiple are present.
            $changeid = $cids[-1];
        }

        print "-- $id: ".format_subject($changeid, $subject, -45)."\n" if ($debug);

        unshift @commits, {
            id => $id,
            parents => [ split(/ /, $parents) ],
            changeid => $changeid,
            subject => $subject,
            message => $message,
            tree => $tree,
            author => [ @author ],  # Force copy, as these are ...
            committer => [ @committer ]  # ... not loop-local.
        };
    }
    close_process($log);
    return \@commits;
}

# Note: The return value is reliable only for the first call.
sub visit_commits($$;$)
{
    my ($tips, $args, $cid_opt) = @_;

    my @revs = grep {
        if ($commit_by_id{$_}) {
            print "Already visited $_.\n" if ($debug);
            0;
        } else {
            1;
        }
    } @$tips;
    return if (!@revs);

    # The grep above excludes tips which match previous tips or their
    # ancestors. A tip that is a descendant of a previous tip still
    # needs to be visited, but the traversal needs to be cut off, so
    # pass all previous tips as exclusions to git.
    state %visited;
    my @excl = map { "^$_" } keys %visited;
    $visited{$_} = 1 foreach (@revs);
    push @revs, @excl;

    my $commits = visit_commits_raw(\@revs, $args, $cid_opt);
    foreach my $commit (@$commits) {
        init_commit($commit);
        # This excludes tips that were in fact ancestors of other tips,
        # thereby cutting down the noise in the exclusion list.
        delete $visited{$_} foreach (@{$$commit{parents}});
    }
    return $commits;
}

sub visit_local_commits($;$)
{
    my ($tips, $cid_opt) = @_;

    # We exclude all upstream heads instead of only that of the current branch,
    # because Gerrit will ignore all known commits (reviewed or not).
    # This matters for cross-branch pushes and re-targeted Changes, where a commit
    # can have known ancestors which aren't on its upstream branch.
    # When traversing PatchSets from Gerrit, we need to exclude the heads from the
    # gerrit remote as well, as they may be actually ahead of our merge-base with
    # upstream.
    return visit_commits($tips, \@upstream_excludes, $cid_opt);
}

my $analyzed_local_branch = 0;
# SHA1 of the local branch's merge base with upstream.
our $local_base;
# SHA1 of the local branch's tip.
our $local_tip;
# Mapping of Change-Ids to commits on the local branch.
my %changeid2local;  # { change-id => SHA1 }

sub analyze_local_branch($)
{
    my ($tip) = @_;

    $analyzed_local_branch = 1;

    # Get the revs ...
    print "Enumerating local Changes ...\n" if ($debug);
    my $raw_commits = visit_local_commits([ $tip ]);
    return 0 if (!@$raw_commits);

    # ... then sanity-check a bit ...
    my %seen;
    foreach my $commit (@$raw_commits) {
        my $subject = $$commit{subject};
        fail("Commit on ".($local_branch // "<detached HEAD>")." was meant to be squashed:\n  "
                .format_subject($$commit{id}, $subject, -2)."\n")
            if ($subject =~ /^(squash|fixup)! /);
        my $changeid = $$commit{changeid};
        my $excommit = $seen{$changeid};
        fail("Duplicate Change-Id $changeid on ".($local_branch // "<detached HEAD>").":\n  "
                .format_subject($$excommit{id}, $$excommit{subject}, -2)."\n  "
                .format_subject($$commit{id}, $subject, -2)."\n")
            if (defined($excommit));
        $seen{$changeid} = $commit;
    }

    # Iff we have a detached HEAD, we don't know the tip yet, because
    # we resolve only named branches. In other cases, this is a no-op.
    $local_tip = $$raw_commits[-1]{id};

    my $commits = get_commits_free($local_tip);

    $local_base = $$commits[0]{parents}[0];

    $changeid2local{$$_{changeid}} = $$_{id} foreach (@$commits);

    # ... and then add them to the set of local Changes.
    my $idx = 0;
    foreach my $commit (@$commits) {
        my $change = change_for_id($$commit{changeid}, CREATE);
        $$commit{change} = $change;
        $$change{local} = $commit;
        $$change{index} = $idx++;
    }

    return 1;
}

##### ... and also for upstream commits.

# The requirements are quite different than for local commits:
# - we need only the Change-Id as meta data
# - we can just discard Changes without Id
# - we don't want to pollute the %commit_by_id namespace, as doing that
#   would violate the assumption that upstream commits are not visited

use constant _GIT_UPSTREAM_LOG_ARGS => ('-z', '--pretty=%H%x00%B');

sub visit_upstream_commits($$)
{
    my ($tips, $bases) = @_;

    my $base;
    if (@$bases == 1) {
        $base = $$bases[0];
    } else {
        # If we have multiple bases, we need to find the oldest one.
        $base = read_cmd_line(0, 'git', 'merge-base', '--octopus', @$bases);
    }

    my %changeids;
    my $log = open_process(USE_STDIN | USE_STDOUT | FWD_STDERR,
                           'git', 'log', _GIT_UPSTREAM_LOG_ARGS, @$tips, "^$base");
    while (read_fields($log, my ($commit, $message))) {
        my @ids = ($message =~ /^Change-Id: (.+)$/mg);
        $changeids{$ids[-1]} = 1 if (@ids);
        # We don't print debug messages here, as this would completely
        # flood the log.
    }
    close_process($log);
    print "Found ".int(keys %changeids)." Changes.\n" if ($debug);
    return \%changeids;
}

#####################
# change resolution #
#####################

# Resolve a possibly abbreviated Change-Id referring to a commit in
# the local branch.
# NB, the most likely source of abbreviated Ids is the gpush output.
sub _sha1_for_partial_local_id($)
{
    my ($id) = @_;

    state %changeid2local_cache;
    return $changeid2local_cache{$id} if (exists($changeid2local_cache{$id}));

    my $sha1 = $changeid2local{$id};
    if (!defined($sha1)) {
        my @sha1s;
        my $rx = qr/^\Q$id\E/;
        foreach my $changeid (keys %changeid2local) {
            push @sha1s, $changeid2local{$changeid} if ($changeid =~ $rx);
        }
        if (@sha1s) {
            fail("$id is ambiguous.\n") if (@sha1s != 1);
            $sha1 = $sha1s[0];
        }
    }

    $changeid2local_cache{$id} = $sha1;
    return $sha1;
}

use constant {
    SPEC_BASE => 0,
    SPEC_TIP => 1,
    SPEC_PARENT => 2
};

sub _finalize_parse_local_rev($$$)
{
    my ($rev, $out, $scope) = @_;

    # There is no point in restricting the base here - subsequent
    # use will find out soon enough if it is not reachable.
    return $out if ($scope == SPEC_BASE);
    return $out if (!$analyzed_local_branch || $commit_by_id{$out});
    fail("$rev is outside the local branch.\n");
}

sub _parse_local_rev_sym($$)
{
    my ($rev, $scope) = @_;

    my $out;
    if ($rev eq 'HEAD') {
        fail("HEAD is not valid for base revspecs.\n") if ($scope == SPEC_BASE);
        $out = $local_tip;
    } elsif ($rev eq 'ROOT') {
        fail("ROOT is not valid for tip revspecs.\n") if ($scope == SPEC_TIP);
        $out = $rev;
    } elsif (($rev eq '@{u}') || ($rev eq '@{upstream}')) {
        fail("\@{upstream} is not valid for tip revspecs.\n") if ($scope == SPEC_TIP);
        $out = "";
    } else {
        return (undef, undef);
    }
    return (_finalize_parse_local_rev($rev, $out, $scope), 1);
}

sub _parse_local_rev_id_only($$)
{
    my ($rev, $scope) = @_;

    fail("$rev is not a valid revspec.\n") if ($rev !~ /^(\w+)(.*)$/);

    # This looks like a valid revspec, but git failed to parse it.
    # Try to parse it as a Change-Id instead.
    my ($id, $rest) = ($1, $2);
    my $sha1 = _sha1_for_partial_local_id($id);
    wfail("$rev does not refer to a Change on the local branch.\n") if (!$sha1);
    return $sha1 if (!$rest);

    my $out = read_cmd_line(SOFT_FAIL, 'git', 'rev-parse', '--verify', '-q', $sha1.$rest);
    fail("$rev is not a valid revspec.\n") if (!$out);
    return _finalize_parse_local_rev($rev, $out, $scope);
}

sub parse_local_rev_id($$)
{
    my ($rev, $scope) = @_;

    my ($sout, $done) = _parse_local_rev_sym($rev, $scope);
    return $sout if ($done);
    return _parse_local_rev_id_only($rev, $scope);
}

# Parse a revision specification referring to a commit in the local branch.
# This will return undef for @{u}, HEAD, and Change-Ids if the local branch
# was not visited yet; call parse_local_rev_id() after doing so.
sub parse_local_rev($$)
{
    my ($rev, $scope) = @_;

    $rev = "HEAD".$rev if ($rev =~ /^[~^]/);
    my ($sout, $done) = _parse_local_rev_sym($rev, $scope);
    return $sout if ($done);
    my $out = read_cmd_line(SOFT_FAIL, 'git', 'rev-parse', '--verify', '-q', $rev);
    return _finalize_parse_local_rev($rev, $out, $scope) if ($out);
    return undef if (!$analyzed_local_branch);  # Come back later!
    return _parse_local_rev_id_only($rev, $scope);
}

###################
# commit creation #
###################

# Cache of diffs. Global, so it can be flushed from the outside.
our %commit2diff;

# Apply one commit's diff on top of another commit; return the new tree.
sub apply_diff($$$)
{
    my ($commit, $base_id, $flags) = @_;

    my $sha1 = $$commit{id};
    my $diff = $commit2diff{$sha1};
    if (!defined($diff)) {
        my $show = open_cmd_pipe(0, 'git', 'diff-tree', '--binary', '--root', "$sha1^!");
        $diff = get_process_output($show, 'stdout');
        close_process($show);
        $commit2diff{$sha1} = $diff;
    }

    # We don't know the tree when the base is an upstream commit.
    # This is just fine, as this will be the first commit in the
    # series by definition, so we need to load it anyway. The
    # subsequent apply will change it in every case, so there
    # is no chance to recycle it, either.
    state $curr_tree = "";
    my $base = $commit_by_id{$base_id};
    run_process(FWD_STDERR, 'git', 'read-tree', ($base_id eq 'ROOT') ? '--empty' : $base_id)
        if (!$base || ($curr_tree ne $$base{tree}));
    $curr_tree = "";

    my $proc = open_process(SOFT_FAIL | USE_STDIN | SILENT_STDIN | NUL_STDOUT | $flags,
                            'git', 'apply', '--cached', '-C1', '--whitespace=nowarn');
    write_process($proc, $diff);
    my $errors = get_process_output($proc, 'stderr')
        if ($flags & USE_STDERR);
    close_process($proc);
    return (undef, $errors) if ($?);
    $curr_tree = read_cmd_line(0, 'git', 'write-tree');
    return ($curr_tree, undef);
}

# Create a commit object from the specified metadata.
sub create_commit($$$$$)
{
    my ($parents, $tree, $commit_msg, $author, $committer) = @_;

    ($ENV{GIT_AUTHOR_NAME}, $ENV{GIT_AUTHOR_EMAIL}, $ENV{GIT_AUTHOR_DATE}) = @$author;
    ($ENV{GIT_COMMITTER_NAME}, $ENV{GIT_COMMITTER_EMAIL}, $ENV{GIT_COMMITTER_DATE}) = @$committer;
    my @pargs = map { ('-p', $_) } @$parents;
    my $proc = open_process(USE_STDIN | SILENT_STDIN | USE_STDOUT | FWD_STDERR,
                            'git', 'commit-tree', $tree, @pargs);
    write_process($proc, $commit_msg);
    my $sha1 = read_process($proc);
    close_process($proc);

    my $commit = {
        id => $sha1,
        parents => $parents,
        tree => $tree
    };
    init_commit($commit);
    return $commit;
}

###################
# branch tracking #
###################

# Update the target branches of local Changes according to the data
# from a Gerrit query.
# Each SHA1 is assigned to exactly one PatchSet, which in turn is
# assigned to exactly one Change. That way we can identify each Change
# by the last SHA1 we pushed it with, irrespective of the branch it is
# targeting. If the latter changes on Gerrit, we just follow it, as
# this is what the user usually wants.
sub _update_target_branches($)
{
    my ($ginfos) = @_;

    state %trackable_changes;
    if (!%trackable_changes) {
        # Changes on multiple local branches may have the same _pushed commit,
        # so make sure to collect only the Changes on the current branch.
        foreach my $change (values %change_by_key) {
            next if ($$change{garbage});
            next if (!$$change{local});
            my $pushed = $$change{pushed};
            $trackable_changes{$pushed} = $change if (defined($pushed));
        }
    }

    my @changed;
    my $need_save;
    foreach my $ginfo (@$ginfos) {
        foreach my $rev (@{$$ginfo{revs}}) {
            my $change = $trackable_changes{$$rev{id}};
            next if (!$change);
            my $pbr = $$change{tgt} // "";
            my $abr = $$ginfo{branch};
            next if ($pbr eq $abr);
            # Old gpush versions don't store the target branch. Make no noise about that.
            if ((length($pbr) && !$quiet) || $debug) {
                $$change{annotation} = "  [$pbr => $abr]";
                push @changed, $change;
            }
            $$change{tgt} = $abr;
            $need_save = 1;
        }
    }
    if (@changed) {
        my @reports;
        report_flowed(\@reports,
                "Notice: Adjusting ".int(@changed)." Change(s) to server-side re-targeting:");
        report_local_changes(\@reports, \@changed);
        print format_reports(\@reports)."\n";  # Delimit from remaining output.
        # The Changes may be printed again later.
        delete $$_{annotation} foreach (@changed);
    }
    save_state() if ($need_save);
}

#######################
# gerrit ssh handling #
#######################

# SSH arguments for connecting the Gerrit instance.
our @gerrit_ssh;
# Target repository name on the Gerrit instance.
our $gerrit_project;

# Extract Gerrit configuration from the previously determined Gerrit remote.
sub set_gerrit_config($)
{
    my ($rmt) = @_;

    my $url = git_config('remote.'.$rmt.'.url');
    fail("Remote '$rmt' does not exist.\n") if (!$url);
    if ($url =~ m,^ssh://([^/:]+)(?::(\d+))?/(.*?)(?:\.git)?/?$,) {
        push @gerrit_ssh, '-p', $2 if (defined($2));
        push @gerrit_ssh, $1;
        $gerrit_project = $3;
    } elsif ($url =~ m,^([^/:]+):([^/].*?)(?:\.git)?/?$,) {
        push @gerrit_ssh, $1;
        $gerrit_project = $2;
    } else {
        fail("Remote '$rmt' does not use a supported protocol.\n")
    }
}

sub query_gerrit($;$)
{
    my ($ids, $extra) = @_;

    my @ginfos;
    my $info = open_cmd_pipe(0, 'ssh', @gerrit_ssh, 'gerrit', 'query', '--format', 'JSON',
                                '--no-limit', '--patch-sets', $extra ? @$extra : (),
                                "project:$gerrit_project", '\\('.join(' OR ', @$ids).'\\)');
    while (read_process($info)) {
        my $review = decode_json($_);
        defined($review) or fail("Cannot decode JSON string '".chomp($_)."'\n");
        my ($key, $changeid) = ($$review{'number'}, $$review{'id'});
        next if (!defined($key) || !defined($changeid));
        my $ginfo = \%{$gerrit_info_by_key{$key}};
        push @{$gerrit_infos_by_id{$changeid}}, $ginfo;
        my ($subject, $status) = ($$review{'subject'}, $$review{'status'});
        defined($subject) or fail("Huh?! $changeid has no subject?\n");
        defined($status) or fail("Huh?! $changeid has no status?\n");
        my ($branch, $topic) = ($$review{'branch'}, $$review{'topic'});
        defined($branch) or fail("Huh?! $changeid has no branch?\n");
        my $pss = $$review{'patchSets'};
        defined($pss) or fail("Huh?! $changeid has no PatchSets?\n");
        my (@revs, %rev_map);
        foreach my $cps (@{$pss}) {
            my ($number, $ts, $revision, $base, $ref) =
                    ($$cps{'number'}, $$cps{'createdOn'}, $$cps{'revision'},
                     $$cps{'gpush-base'}, $$cps{'ref'});
            defined($number) or fail("Huh?! PatchSet in $changeid has no number?\n");
            defined($ts) or fail("Huh?! PatchSet $number in $changeid has no timestamp?\n");
            defined($revision) or fail("Huh?! PatchSet $number in $changeid has no commit?\n");
            defined($ref) or fail("Huh?! PatchSet $number in $changeid has no ref?\n");
            my %rev = (
                id => $revision,
                ps => $number,
                ts => int($ts),
                base => $base,
                ref => $ref
            );
            $revs[$number] = \%rev;
            $rev_map{$revision} = \%rev;
            $gerrit_info_by_sha1{$revision} = $ginfo;
        }
        $$ginfo{key} = $key;
        $$ginfo{id} = $changeid;
        $$ginfo{subject} = $subject;
        $$ginfo{status} = $status;
        $$ginfo{branch} = $branch;
        $$ginfo{topic} = $topic;
        $$ginfo{revs} = [ grep { $_ } @revs ];  # Drop deleted ones.
        $$ginfo{rev_by_id} = \%rev_map;
        my $rvrs = $$review{'allReviewers'};
        if ($rvrs) {
            # Note: This does not differentiate between reviewers and CCs.
            # Reported upstream as https://crbug.com/gerrit/11709
            my %reviewers;
            foreach my $rvr (@$rvrs) {
                foreach my $ky ('name', 'email', 'username') {
                    my $val = $$rvr{$ky};
                    $reviewers{$val} = RVRTYPE_REV if (defined($val));
                }
            }
            $$ginfo{reviewers} = \%reviewers;
        }
        push @ginfos, $ginfo;
    }
    close_process($info);

    _update_target_branches(\@ginfos);
}

#############################
# export all public symbols #
#############################

sub import()
{
    no strict 'refs';

    my %imported = map { $_ => 1 } @_imported;
    undef @_imported;
    while (my ($name, $symbol) = each %{__PACKAGE__.'::'}) {
        next if (defined($imported{$name}));
        next if ($name =~ /^(_.*|BEGIN|END|a|b|import)$/);
        # $symbol values referring to constants are resolved, but we want to alias the
        # inline function. Other values are typeglobs which can be aliased directly.
        *{caller.'::'.$name} = !length(ref($symbol)) ? *$symbol : \&{__PACKAGE__.'::'.$name};
    }
}

1;