-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcj-git-applypatches
executable file
·643 lines (575 loc) · 17.7 KB
/
cj-git-applypatches
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
#!/usr/bin/perl -w
use strict;
use Cwd 'abs_path';
my ($mydir, $myname);
BEGIN {
my $location = (-l $0) ? abs_path($0) : $0;
$location =~ /(.*?)([^\/]+)\z/s or die "?";
($mydir, $myname) = ($1, $2);
}
use lib "$mydir/lib";
use Chj::Git::Functions qw(make_xgit_do_hack git_wait_lock xgit_do);
use Chj::xperlfunc;
use Chj::xopen 'xopen_read';
use Date::Parse ();
use Chj::xperlfunc 'dirname';
use Chj::FP::lazy;
use Chj::Backtrace;
use Chj::Git::Patchtool 'git_commit_options';
(my $email='ch%christianjaeger,ch')=~ tr/%,/@./;
sub usage {
print STDERR map{"$_\n"} @_ if @_;
print "$myname listfile
Apply the patches in the listfile to the current git dir; assumes
the patches are in the same dir as listfile.
Like with rebase -i, prefixing patches with 's' is possible. The
ordering is as in the file.
Options:
--no-early do *not* check for missing titles etc. before starting
the patching process.
(Christian Jaeger <$email>)
";
exit (@_ ? 1 : 0);
}
use Getopt::Long;
our $verbose=0;
our $opt_no_early;
our $opt_dry;
GetOptions("verbose"=> \$verbose,
"help"=> sub{usage},
"dry-run"=> \$opt_dry,
"no-early"=> \$opt_no_early,
) or exit 1;
usage unless @ARGV==1;
our ($listfile)=@ARGV;
package _Error {
sub new {
my $cl=shift;
@_==1 or die "expect 1 arg";
my ($msg)=@_;
bless \$msg, $cl
}
sub string {
my $s=shift;
$$s
}
}
package _NoCommitmsgError {
our @ISA=("_Error");
}
package _MissingCommitidError {
our @ISA=("_Error");
}
sub xgit_do_hack;
*xgit_do_hack= make_xgit_do_hack
(sub {
my ($base)=@_;
xsystem "rm", "-rf", "--", "$base/rebase-apply";
git_wait_lock ($base);
xgit_do "reset","--hard"; # needed?
git_wait_lock ($base);
});
package ClusterItem {
use Class::Array -fields=> -publica=>
();
sub is_patch { 0 }
sub is_command { 0 }
end Class::Array;
}
package Patch {
use Chj::xperlfunc qw(xsymlink xunlink);
use Class::Array -class=> 'ClusterItem', -extend=> -publica=>
(
'basedir',
'filename',
'is_message_leader', # provides the message.
'is_time_leader', # provides the author time.
'is_author_leader', # provides the author name/email.
'commitid', # set-once.
'headers', # cache
);
sub is_patch { 1 }
sub new {
my $cl=shift;
bless [@_],$cl
}
sub desc {
my $s=shift;
$s->filename
}
sub path {
my $s=shift;
"$$s[Basedir]/$$s[Filename]"
}
sub set_commitid {
my $s=shift;
my ($commitid)=@_;
die "commitid already set"
if $$s[Commitid];
$$s[Commitid]=$commitid
}
use Chj::FP::lazy;
sub message {
my $s=shift;
Delay {
if ($$s[Commitid]) {
# to be added to git commit for the cluster
[ "-C",$$s[Commitid] ]
} else {
my $msg= "missing commitid for patchfile $$s[Filename]";
if ($opt_dry) {
_MissingCommitidError->new($msg)
} else {
# would fail too but only after giving the
# stringified representation to git
die $msg
}
}
}
}
sub get_orig_message {
my $s=shift;
# read message from original commit
if (my $id= $$s[Commitid]) {
my $rf= Chj::Git::Functions::maybe_cat_file("commit",$id)
or die "could not get commit message for '$id'";
$$rf=~ s/.*?\n\n//s
or die "cannot match to strip headers from '$$rf'";
$$rf
} else {
my $msg= "missing commitid for patchfile $$s[Filename]";
if ($opt_dry) {
_MissingCommitidError->new($msg)
} else {
# would fail too but only after giving the stringified
# representation to git
die $msg
}
}
}
sub headers {
my $s=shift;
$$s[Headers] ||= do {
my $headers={};
my $lastkey;
{
my $f= Chj::xopen::xopen_read $s->path;
local $_; # !!!!!!
while (<$f>) {
chomp;
last if /^$/;
next if /^From /;
if (/^\s+(.*)/) {
$$headers{$lastkey}[-1] .= "\n".$1;
} elsif (my ($key,$val)= /^([\w-]+):\s*(.*)/) {
$lastkey=lc $key;
push @{$$headers{$lastkey}},$val;
} else {
die "invalid header in file: '$_' ".$s->path;
}
}
$f->xclose;
}
$headers
}
}
my $get_single_header_named= sub {
my ($name)= @_;
sub {
my $s=shift;
my $headers= $s->headers;
my @res= @{$$headers{$name}||[]};
@res == 1 ? $res[0] : do {
my $msg= @res ? "more than one" : "no";
die "contains $msg '$name' header: ".$s->path;
}
}
};
sub author_date; *author_date= $get_single_header_named->("date");
sub author; *author= $get_single_header_named->("from");
sub author_name_and_email {
my $s=shift;
my $author= $s->author;
my ($name, $mail)= $author=~ m/^\s*(.*?)\s*<([^<>]+)>\s*$/
or die "no match on author '$author'";
($name, $mail)
}
sub apply {
my $s=shift;
my $applying_path = $$s[Basedir] . "/_applying";
unlink $applying_path;
xsymlink $s->path, $applying_path;
main::xgit_do_hack "am", "-3", "--ignore-whitespace", $s->path;
# ^ does not output the new commitid in a clear way, thus:
xunlink $applying_path;
my $commitid= Chj::Git::Functions::xgit_rev_parse "HEAD";
$s->set_commitid ($commitid);
}
end Class::Array;
}
package Command {
use Chj::xperlfunc 'xxsystem';
use Class::Array -class=> 'ClusterItem', -extend=> -publica=>
('commandline');
sub is_command { 1 }
sub new {
my $cl=shift;
@_==1 or die "wrong number of arguments";
bless [@_],$cl
}
sub desc {
my $s=shift;
'% ' . $s->commandline
}
sub apply {
my $s=shift;
xxsystem $s->commandline;
}
end Class::Array;
}
package Cluster {
use Chj::FP::lazy;
use Class::Array -fields=> -publica=>
(
'line', #of the start, in source file.
'message', # string
'items', # array_of ClusterItem
'maybe_prefix', # undef or string to be prepended to commit message
'maybe_postfix_subject', # undef or string to be appended to subject line
'maybe_postfix', # undef or string to be appended to commit message
'_patches', # cache of items that are patches (premature opt?)
'_commands', # dito
);
sub new {
my $cl=shift;
my ($line)=@_;
my $s=$cl->SUPER::new;
$$s[Line]=$line;
$$s[Items]=[];
$s
}
sub add_item {
my $s=shift;
undef $$s[_Patches];
undef $$s[_Commands];
push @{$$s[Items]},@_
}
sub patches {
my $s=shift;
$$s[_Patches] ||=
[ grep { $_->is_patch } @{$$s[Items]} ];
}
sub has_patches {
my $s=shift;
@{ $s->patches } > 0
}
sub commands {
my $s=shift;
$$s[_Commands] ||=
[ grep { $_->is_command } @{$$s[Items]} ];
}
sub has_commands {
my $s=shift;
@{ $s->commands } > 0
}
sub perhaps_singlepatch {
my $s=shift;
my $ps= $s->patches;
@$ps == 1 ? $$ps[0] : ()
}
sub is_empty { # really empty (nothing to apply to history),
# regardless of kind of item
my $s=shift;
not @{$$s[Items]}
}
sub perhaps_the_patch_that {
# incl. sanitation, i.e. throws exception if more than one
# leader is present
my $s=shift;
my ($method)=@_;
my @leaders= grep { $_->$method } @{$s->patches};
@leaders==1 ? $leaders[0]
: @leaders ?
die "more than one $method patch selected"
: ();
}
sub perhaps_author_date { # -> perhaps (git time format)
my $s=shift;
return ()
unless $s->has_patches;
if (my ($leader)= $s->perhaps_the_patch_that ("is_time_leader")) {
$leader->author_date
} else {
# select the *latest* author_date of all patches.
my @p= map {
[
((scalar Date::Parse::str2time($_))
|| die "invalid time?: '$_'"),
$_
]
} map {
$_->author_date
} @{$s->patches};
(sort {
$$a[0] cmp $$b[0]
} @p)[-1][1]
}
}
sub perhaps_author {
my $s=shift;
return ()
unless $s->has_patches;
if (my ($leader)= $s->perhaps_the_patch_that ("is_author_leader")) {
$leader->author
} else {
my @_authors= map {
$_->author
} @{$s->patches};
my %authors= map {
$_ => 1
} @_authors;
my @authors= keys %authors;
if (@authors==1) {
$authors[0]
} else {
warn "**NOTE**: more than one author in cluster on line "
.($s->line).", maybe specify 'a' on a patch:\n"
.join("", sort map { " $_\n" } @authors);
()
}
}
}
sub maybe_msgoptions_promise {
# either false if message does not need to be changed,
# or a promise of an array of options to be fed to git.
my $s=shift;
my $prefix= $$s[Maybe_prefix] // "";
my $postfix= $$s[Maybe_postfix] // "";
my $fix_message = sub {
my ($message) = @_;
my $subjected_message = do {
if (defined (my $str = $$s[Maybe_postfix_subject])) {
my ($subject, @rest) = split /\n/, $message;
join("\n", ($subject.$str, @rest))
} else {
$message
}
};
#warn "subjected_message= '$subjected_message'";
$prefix . $subjected_message . $postfix
};
if ($$s[Message]) {
# Explicit message in `[ ]` was given.
# (Delay just for consistency, so that I can Force
# it. Should use FP::Lazy instead or so.)
Delay {
["-m", $fix_message->($$s[Message]) ]
}
} else {
if (my ($leader)= $s->perhaps_the_patch_that ("is_message_leader")) {
Delay {
[
"-m",
$fix_message->($leader->get_orig_message)
]
}
} else {
if (my ($thepatch)= $s->perhaps_singlepatch) {
if (length $prefix or length $postfix
or defined($$s[Maybe_postfix_subject]))
{
Delay {
[
"-m",
$fix_message->($thepatch->get_orig_message)
]
}
} else {
if (@{$s->items} == 1) {
# optimization: no need to reset --soft
# and re-commit
undef
} else {
# single patch, but also shell commands
Delay {
[
"-m",
$fix_message->($thepatch->get_orig_message)
]
}
}
}
} elsif (not $s->has_patches) {
undef
} else {
my $msg="Cluster starting at line $$s[Line]: ".
"neither leader patch indication nor ".
"explicit message given";
#new _NoCommitmsgError ;
# XX find something better. right now it's broken
# as it is not checked in "check" anymore, and on
# "patch" it will feed that to Force and break
# this way. !
die $msg
}
}
}
}
end Class::Array;
}
our $basedir= dirname $listfile;
our $listfh= xopen_read $listfile;
our @clusters;
my $line=1;
our $curcluster= new Cluster ($line);
my $curcluster_add_string = sub {
my ($fieldname, $str)= @_;
my $old = $curcluster->$fieldname // "";
my $setmethod = "set_$fieldname";
$curcluster->$setmethod($old.$str);
};
sub end_cluster {
push @clusters, $curcluster
unless $curcluster->is_empty;
}
while (<$listfh>) {
chomp;
$line++;
next if /^\s*#/;
if (/^([*"ta]*)(\d+(?:\w+)?-.+)/) {
my ($is_some_leader,$path)=($1,$2);
# a squash. extend existing cluster.
my $p= Patch->new ($basedir,
$path,
# message leader:
scalar
($is_some_leader
and $is_some_leader=~ /[*"]/),
# time leader:
scalar
($is_some_leader
and $is_some_leader=~ /[*t]/),
# author leader:
scalar
($is_some_leader
and $is_some_leader=~ /[*a]/));
$curcluster->add_item ($p);
} elsif (/^\%\s*(.*?)\s*$/s) {
# a shell command
$curcluster->add_item (Command->new ($1));
} elsif (/^\s*$/) {
# a new cluster.
end_cluster;
$curcluster= new Cluster ($line);
} elsif (/^prefix: ?(.*)/) {
# not trimming whitespace (other than that single expected space),
# and not adding ": ". have to do that yourself, ok?
$curcluster_add_string->("maybe_prefix", $1);
} elsif (/^postfix-subject: ?(.*)/) {
$curcluster_add_string->("maybe_postfix_subject", $1);
} elsif (/^postfix-para(?:graph)?: ?(.*)/) {
$curcluster_add_string->("maybe_postfix", "\n\n$1\n");
} elsif (/^\[\s*$/) {
# inline commit message
my @c;
while (<$listfh>) {
chomp;
$line++;#!
if (/^\]\s*(?:#.*)?$/) {
last;
}
if (/^#/) {
warn "NOTE: comments inside commit message: '$_'\n";
}
push @c, $_
}
$curcluster->set_message
(join ("\n", map { my $s=$_; $s=~ s/\s+\z//; $s } @c));
} else {
die "no match for '$_'";
}
}
end_cluster;
$listfh->xclose;
sub check {
my $errs=0;
for my $c (@clusters) {
# ugly COPY from apply.
for my $p (@{$c->patches}) {
#$p->apply($basedir);
#now we calculate paths anyway ourselves?? ~td:
my $path= $basedir."/".$p->filename;
-e $path or do {
warn "patch file '$path' missing\n";
$errs++;
};
}
}
$errs
}
sub apply {
my ($early)=@_; # early means, just check for errors in the source
# file (similar? to dry-run)
for my $cluster (@clusters) {
my $applypatches=sub {
for my $p (@{$cluster->items}) {
print "==== ".$p->desc." ====\n";
$p->apply;
}
};
if (my $msgoptions= $cluster->maybe_msgoptions_promise) {
unless ($early) {
my $oldhead= Chj::Git::Functions::xgit_rev_parse "HEAD";
&$applypatches();
main::xgit_do_hack "reset", "--soft", $oldhead;
}
my @moreoptions=
(
do {
if (my ($author_date)= $cluster->perhaps_author_date) {
("--date", $author_date)
} else {
# '%' command only, no patches
()
}
},
do {
if (my ($author)= $cluster->perhaps_author) {
("--author", $author)
} else {
()
}
}
);
unless ($early) {
main::xgit_do_hack "commit", git_commit_options, "-a",
@{Force $msgoptions}, @moreoptions;
}
} else {
# "message does not need to be changed" (singlepatch [or
# not has_patches])
unless ($early) {
&$applypatches();
}
}
}
}
my $errors= check;
if ($errors) {
print "$errors errors in input file, stopping.\n";
exit 1;
} else {
if ($opt_dry) {
print "no errors in input file; ".
"not running because in dry-run mode.\n";
# NOTE: dry mode does not check for missing cluster titles and
# such! Pointless?!!! Implemented new early checking behaviour
# instead (--no-early).
} else {
unless ($opt_no_early) {
apply 1;
}
apply 0;
print "Ok.\n";
}
}