-
Notifications
You must be signed in to change notification settings - Fork 0
/
check_tree.pl
executable file
·2965 lines (2486 loc) · 112 KB
/
check_tree.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/perl -w
# ================================================================
# === ==> -------- HISTORY -------- <== ===
# ================================================================
#
# Version Date Maintainer Changes, Additions, Fixes
# 0.0.1 2017-04-08 sed, PrydeWorX First basic design
# ... a lot of undocumented and partly lost development ...
# 0.8.0 2018-02-23 sed, PrydeWorX 2nd gen rewritten due to loss of the original thanks to stupidity.
# 0.8.1 2018-03-05 sed, PrydeWorX Fixed all outstanding issues and optimized rewriting of shell files.
# 0.8.2 2018-03-06 sed, PrydeWorX Added checks for elogind_*() function call removals.
# 0.8.3 2018-03-08 sed, PrydeWorX Handle systemd-logind <=> elogind renames. Do not allow moving of
# commented out includes under out elogind block.
# 0.8.4 2018-03-09 sed, PrydeWorX Added handling of .gperf and .xml files.
# 0.8.5 2018-03-13 sed, PrydeWorX Added possibility to (manualy) check root files and enhanced the
# handling of shell masks and unmasks.
# 0.8.6 2018-03-16 sed, PrydeWorX Enhanced mask block handling and added handling of .sym files.
# 0.8.7 2018-04-20 sed, PrydeWorX Add [un]preparation for XML files.
# 0.8.8 2018-05-08 sed, PrydeWorX Use Git::Wrapper to checkout the wanted commit in the upstream tree.
# 0.8.9 2018-05-09 sed, PrydeWorX Add new option --create to create non-existing files. Needs --file.
# + Add new option --stay to to not reset back from --commit.
# 0.9.0 2018-05-15 sed, PrydeWorX Do not prefix mask block content in XML file patch hunks with a '# '.
# 0.9.1 2018-05-17 sed, PrydeWorX Replace the source in creation patches with /dev/null.
# + Remember mask starts and elses in hunks, so the resulting patches
# can be reworked without ignoring changes in useless hunks.
# 0.9.2 2018-05-24 sed, PrydeWorX Enhance the final processing of shell and xml files and their patches
# by remembering mask changes that get pruned from the hunks.
# 0.9.3 2018-05-25 sed, PrydeWorX Made check_musl() and check_name_reverts() safer. Further policy.in
# consist of XML code, and are now handled by (un)prepare_xml().
# 0.9.4 2018-05-29 sed, PrydeWorX Fixed a bug that caused #else to not be unremoved in __GLIBC__ blocks.
# + The word "systemd" is no longer changed to "elogind", if it was
# found in a comment block that is added by the patch.
# + Added missing detection of mask else switches in prune_hunk().
# + Move move upstream appends from after our mask blocks up before
# found #else switches.
# 0.9.5 2018-05-30 sed, PrydeWorX Do not allow diff to move name reverts into a mask block.
# + Do not replace double dashes in XML comments, that are either the
# comment start or end.
# 0.9.6 2018-06-06 sed, PrydeWorX Prune changes that change nothing. This eliminates some useless hunks.
# 0.9.7 2018-06-21 sed, PrydeWorX Includes masked by C90 conformant /**/ are now handled as well.
# 0.9.8 2018-08-14 sed, PrydeWorX Let .m4 files be prepared/unprepared, too.
# 0.9.9 2018-11-23 sed, PrydeWorX Fix check_name_reverts() to no longer double lines, and allow to "fix"
# name changes we did in mask blocks.
# 0.9.10 2019-01-18 sed, PrydeWorX Make sure that empty commented lines do not get trailing spaces in
# shell files.
# 0.9.11 2019-01-28 sed, PrydeWorX Do not include trailing spaces in empty comment lines in patches for
# shell files.
# 0.9.12 2019-02-20 sed, PrydeWorX Do not leave an undef hunk in $hFile{hunks}, report and ignore.
# + Issue #1/#4: Move additions right after mask endings up into the mask.
# + Issue #2: Protect src/login/logind.conf.in
# + Issue #3: Do not consider files in man/rules/
# 1.0.0 2019-03-19 sed, PrydeWorX Allow __GLIBC__ to be a mask/insert start/end keyword to make musl-libc
# compatibility easier to accomplish.
# 1.0.1 2019-09-30 sed, PrydeWorX Don't assume __GLIBC__ preprocessor masks to be regular masks, as they
# are already handled in check_musl().
# 1.0.2 2019-10-01 sed, PrydeWorX Completely handle __GLIBC__ masks/inserts in check_musl()
# 1.1.0 2019-10-02 sed, PrydeWorX Add check_empty_masks() to detect masks that became empty
# 1.2.0 2019-10-11 sed, PrydeWorX Fixed check_empty_masks() to eliminate false positives and rewrote
# check_useless() so it can catch useless blocks, too.
# 1.2.1 2020-01-23 sed, PrydeWorX Fixed a bug that caused large removals to be undone if they started
# right after additional includes for elogind. Further improved
# check_masks() greatly!
# 1.2.2 2020-01-31 sed, PrydeWorX Do the checking whether shell/xml preparations are needed a bit more
# sophisticated and effectively.
# 1.3.0 2020-02-06 sed, PrydeWorX From now on mask elses must be "#else // 0" to be recognized.
# 1.3.1 2020-08-18 sed, PrydeWorX As this is easy to get wrong, elogind include additions can be be marked
# with "needed for elogind", too.
# 1.3.2 2021-03-02 sed, PrydeWorX Add LINGUAS to the list of shell files, as elogind has additional locales now.
# 1.4.0 2023-05-12 sed, EdenWorX Fix accidential renaming of systemd-only apps and revert reversals into mask blocks.
# 1.4.1 2023-12-28 sed, EdenWorX Do not revert a name change if the reversal moves the line into a mask.
# Also check for reversals where the removal is anywhere before the addition. This fixes
# multiline-comments to magically multiply when patches are applied by migrate_tree.pl..
# 1.4.2 2024-02-03 sed, EdenWorX Do not migrate NEWS and TODO. They are elogind files now
#
# ========================
# === Little TODO list ===
# ========================
#
# ...nothing right now...
#
# ------------------------
use strict;
use warnings;
use Cwd qw( getcwd abs_path );
use File::Basename;
use File::Find;
use Git::Wrapper;
use Readonly;
use Try::Tiny;
# ================================================================
# === ==> ------ Help Text and Version ----- <== ===
# ================================================================
Readonly my $VERSION => "1.4.2"; ## Please keep this current!
Readonly my $VERSMIN => "-" x length( $VERSION );
Readonly my $PROGDIR => dirname( $0 );
Readonly my $PROGNAME => basename( $0 );
Readonly my $WORKDIR => getcwd();
Readonly my $USAGE_SHORT => "$PROGNAME <--help|[OPTIONS] <path to upstream tree>>";
Readonly my $USAGE_LONG => qq#
elogind git tree checker V$VERSION
--------------------------$VERSMIN
Check the current tree, from where this program is called, against an
upstream tree for changes, and generate a patchset out of the differences,
that does not interfere with elogind development markings.
Usage :
-------
$USAGE_SHORT
The path to the upstream tree should have the same layout as the place from
where this program is called. It is best to call this program from the
elogind root path and use a systemd upstream root path for comparison.
Options :
---------
-c|--commit <refid> | Check out <refid> in the upstream tree.
--create | Needs --file. If the file does not exist, create it.
-f|--file <path> | Do not search recursively, check only <path>.
| For the check of multiple files, you can either
| specify -f multiple times, or concatenate paths with
| a comma, or mix both methods.
-h|--help | Print this help text and exit.
--stay | Needs --commit. Do not reset to the current commit,
| stay with the wanted commit.
#;
# ================================================================
# === ==> -------- File name patterns -------- <== ===
# ================================================================
Readonly my %FILE_NAME_PATTERNS => (
"shell" => [
'LINGUAS',
'Makefile',
'meson',
'\.gitignore$',
'\.gperf$',
'\.in$',
'\.m4$',
'\.pl$',
'\.po$',
'\.pot$',
'\.py$',
'\.sh$',
'\.sym$',
'bash/busctl',
'bash/loginctl',
'pam.d/other',
'pam.d/system-auth',
'zsh/_busctl',
'zsh/_loginctl'
],
"xml" => [
'\.xml$',
'\.ent\.in$',
'\.policy\.in$/'
]
);
# And some protected website URLs
Readonly my %SYSTEMD_URLS => (
'fedoraproject.org/projects/systemd' => 1,
'freedesktop.org/software/systemd' => 1
);
# ================================================================
# === ==> -------- Global variables -------- <== ===
# ================================================================
my $do_create = 0; ## If set to 1, a non-existing file is created.
my $do_stay = 0; ## If set to 1, the previous commit isn't restored on exit.
my $file_fmt = ""; ## Format string built from the longest file name in generate_file_list().
my $have_wanted = 0; ## Helper for finding relevant files (see wanted())
my %hToCreate = (); ## The keys are files that do not exist and shall be created.
my %hWanted = (); ## Helper hash for finding relevant files (see wanted())
my $in_else_block = 0; ## Set to 1 if we switched from mask/unmask to 'else'.
my $in_glibc_block = 0; ## Set to 1 if we enter a __GLIBC__ block
my $in_mask_block = 0; ## Set to 1 if we entered an elogind mask block
my $in_insert_block = 0; ## Set to 1 if we entered an elogind addition block
my $main_result = 1; ## Used for parse_args() only, as simple $result is local everywhere.
my @only_here = (); ## List of files that do not exist in $upstream_path.
my $previous_commit = ""; ## Store current upstream state, so we can revert afterwards.
my $show_help = 0;
my @source_files = (); ## Final file list to process, generated in in generate_file_list().
my $upstream_path = "";
my $wanted_commit = "";
my @wanted_files = (); ## User given file list (if any) to limit generate_file_list()
# ================================================================
# === ==> ------- MAIN DATA STRUCTURES ------ <== ===
# ================================================================
my %hFile = (); ## Main data structure to manage a complete compare of two files. (See: build_hFile() )
# Note: %hFile is used globaly for each file that is processed.
# The structure is:
# ( count : Number of hunks stored
# create : Set to 1 if this is a new file to be created, 0 otherwise.
# hunks : Arrayref with the Hunks, stored in %hHunk instances
# is_sh : 1 if the file name has a known shell pattern
# is_xml : 1 if the file name has a known xml pattern
# output : Arrayref with the lines of the final patch
# part : local relative file path
# patch : PROGDIR/patches/<part>.patch (With / replaced by _ in <part>)
# pwxfile: Set to 1 if it is a prepared shell/xml file (See prepare_[shell,xml]())
# source : WORKDIR/<part>
# target : UPSTREAM/<part>
# )
my $hHunk = {}; ## Secondary data structure to describe one diff hunk. (See: build_hHunk() )
# Note: $hHunk is used globally for each Hunk that is processed and points to the
# current $hFile{hunks}[] instance.
# The structure is:
# { count : Number of lines in {lines}
# idx : Index of this hunk in %hFile{hunks}
# lines : list of the lines themselves.
# masked_end : 1 if this hunk ends in a masked block.
# masked_start : 1 if the previous hunk ends in a masked block.
# src_start : line number this hunk starts in the source file.
# tgt_start : line number this hunk becomes in the target file.
# useful : 1 if the hunk is transported, 0 if it is to be omitted.
# }
my %hIncs = (); ## Hash for remembered includes over different hunks.
# Note: Only counted in the first step, actions are only in the second step.
# The structure is:
# { include => {
# applied : Set to 1 once check_includes() has applied any rules on it.
# elogind = { hunkid : Hunk id ; Position where a "needed by elogin" include is
# lineid : Line id ; wanted to be removed by the patch.
# }
# insert = { elogind : Set to 1 if the insert was found under elogind special includes.
# hunkid : Hunk id ; Position where a commented out include is
# lineid : Line id ; wanted to be removed by the patch.
# spliceme: Set to 1 if this insert is later to be spliced.
# sysinc : Set to 1 if it is <include>, 0 otherwise.
# }
# remove = { hunkid : Hunk id ; Position where a new include is wanted to be
# lineid : Line id ; added by the patch.
# sysinc : Set to 1 if it is <include>, 0 otherwise.
# }
# } }
my %hProtected = (); ## check_name_reverts() writes notes down lines here, which check_comments() shall not touch
my @lFails = (); ## List of failed hunks. These are worth noting down in an extra structure, as these
# mean that something is fishy about a file, like elogind mask starts within masks.
# The structure is:
# ( { hunk : the failed hunk for later printing
# msg : a message set by the function that failed
# part : local relative file part
# }
# )
# ================================================================
# === ==> -------- Function list -------- <== ===
# ================================================================
sub build_hFile; ## Inititializes and fills %hFile.
sub build_hHunk; ## Adds a new $hFile{hunks}[] instance.
sub build_output; ## Writes $hFile{output} from all useful $hFile{hunks}.
sub check_blanks; ## Check that useful blank line additions aren't misplaced.
sub check_comments; ## Check comments we added for elogind specific information.
sub check_debug; ## Check for debug constructs
sub check_empty_masks; ## Check for empty mask blocks, remove them and leave a note.
sub check_func_removes; ## Check for attempts to remove elogind_*() special function calls.
sub check_includes; ## performe necessary actions with the help of %hIncs (built by read_includes())
sub check_masks; ## Check for elogind preprocessor masks
sub check_musl; ## Check for musl_libc compatibility blocks
sub check_name_reverts; ## Check for attempts to revert 'elogind' to 'systemd'
sub check_sym_lines; ## Check for attempts to uncomment unsupported API functions in .sym files.
sub check_useless; ## Check for useless updates that do nothing.
sub checkout_upstream; ## Checkout the given refid on $upstream_path
sub clean_hFile; ## Completely clean up the current %hFile data structure.
sub diff_hFile; ## Generates the diff and builds $hFile{hunks} if needed.
sub generate_file_list; ## Find all relevant files and store them in @wanted_files
sub get_hunk_head; ## Generate the "@@ -xx,n +yy,m @@" hunk header line out of $hHunk.
sub hunk_failed; ## Generates a new @lFails entry and terminates the progress line.
sub hunk_is_useful; ## Prunes the hunk and checks whether it stil does anything
sub is_insert_end; ## Return 1 if the argument consists of any insertion end
sub is_insert_start; ## Return 1 if the argument consists of any insertion start
sub is_mask_else; ## Return 1 if the argument consists of any mask else
sub is_mask_end; ## Return 1 if the argument consists of any mask end
sub is_mask_start; ## Return 1 if the argument consists of any mask start
sub parse_args; ## Parse ARGV for the options we support
sub prepare_shell; ## Prepare shell (and meson) files for our processing
sub prepare_xml; ## Prepare XML files for our processing (Unmask double dashes in comments)
sub protect_config; ## Special function to not let diff add unwanted or remove our lines in logind.conf.in
sub prune_hunk; ## remove unneeded prefix and postfix lines.
sub read_includes; ## map include changes
sub splice_includes; ## Splice all includes that were marked for splicing
sub unprepare_shell; ## Unprepare shell (and meson) files after our processing
sub unprepare_xml; ## Unprepare XML files after our processing (Mask double dashes in comments)
sub wanted; ## Callback function for File::Find
# ================================================================
# === ==> -------- Prechecks -------- <== ==
# ================================================================
$main_result = parse_args( @ARGV );
(
( !$main_result ) ## Note: Error or --help given, then exit.
or ( $show_help and print "$USAGE_LONG" ) ) and exit( !$main_result );
length( $wanted_commit )
and (
checkout_upstream( $wanted_commit ) ## Note: Does nothing if $wanted_commit is already checked out.
or exit 1
);
generate_file_list or exit 1; ## Note: @wanted_files is heeded.
# ================================================================
# === ==> -------- = MAIN PROGRAM = -------- <== ===
# ================================================================
for my $file_part ( @source_files ) {
printf( "$file_fmt: ", $file_part );
build_hFile( $file_part ) or next;
diff_hFile or next;
# Reset global state helpers
$in_else_block = 0;
$in_glibc_block = 0;
$in_mask_block = 0;
$in_insert_block = 0;
# Empty the include manipulation hash
%hIncs = ();
# ---------------------------------------------------------------------
# --- Go through all hunks and check them against our various rules ---
# ---------------------------------------------------------------------
for ( my $pos = 0; $pos < $hFile{count}; ++$pos ) {
$hHunk = $hFile{hunks}[$pos]; ## Global shortcut
# === Special 1) protect src/login/logind.conf.in =================
if ( $hFile{source} =~ m,src/login/logind.conf.in, ) {
protect_config and hunk_is_useful and prune_hunk or next;
}
# === 1) Check for elogind masks 1 (normal source code) ===========
check_masks and hunk_is_useful and prune_hunk or next;
# === 2) Check for elogind masks 2 (symbol files) =================
check_sym_lines and hunk_is_useful and prune_hunk or next;
# === 3) Check for musl_libc compatibility blocks =================
check_musl and hunk_is_useful and prune_hunk or next;
# === 4) Check for debug constructs ===============================
check_debug and hunk_is_useful and prune_hunk or next;
# === 5) Check for useful blank line additions ====================
check_blanks and hunk_is_useful and prune_hunk or next;
# === 6) Check for 'elogind' => 'systemd' reverts =================
%hProtected = ();
check_name_reverts and hunk_is_useful and prune_hunk or next;
# === 7) Check for elogind_*() function removals ==================
check_func_removes and hunk_is_useful and prune_hunk or next;
# === 8) Check for elogind extra comments and information =========
check_comments and hunk_is_useful and prune_hunk or next;
# === 9) Check for any useless changes that do nothing ============
check_useless and hunk_is_useful and prune_hunk or next;
# === 10) Check for empty masks that guard nothing any more =======
check_empty_masks and hunk_is_useful and prune_hunk or next;
# ===> IMPORTANT: From here on no more pruning, lines must *NOT* change any more! <===
# === 11) Analyze includes and note their appearance in $hIncs =====
read_includes; ## Never fails, doesn't change anything.
} ## End of first hunk loop
# ---------------------------------------------------------------------
# --- Make sure saved include data is sane ---
# ---------------------------------------------------------------------
for my $inc ( keys %hIncs ) {
$hIncs{$inc}{applied} = 0;
defined( $hIncs{$inc}{elogind} )
or $hIncs{$inc}{elogind} = { hunkid => -1, lineid => -1 };
defined( $hIncs{$inc}{insert} )
or $hIncs{$inc}{insert} = { elogind => 0, hunkid => -1, lineid => -1, spliceme => 0, sysinc => 0 };
defined( $hIncs{$inc}{remove} )
or $hIncs{$inc}{remove} = { hunkid => -1, lineid => -1, sysinc => 0 };
} ## end for my $inc ( keys %hIncs)
# ---------------------------------------------------------------------
# --- Go through all hunks and apply remaining changes and checks ---
# ---------------------------------------------------------------------
for ( my $pos = 0; $pos < $hFile{count}; ++$pos ) {
$hHunk = $hFile{hunks}[$pos]; ## Global shortcut
# (pre -> early out)
hunk_is_useful or next;
# === 1) Apply what we learned about changed includes =============
check_includes and hunk_is_useful or next;
} ## End of second hunk loop
# ---------------------------------------------------------------------
# --- Splice all include insertions that are marked for splicing ---
# ---------------------------------------------------------------------
splice_includes;
# ---------------------------------------------------------------------
# --- Go through all hunks for a last prune and check ---
# ---------------------------------------------------------------------
my $have_hunk = 0;
for ( my $pos = 0; $pos < $hFile{count}; ++$pos ) {
$hHunk = $hFile{hunks}[$pos]; ## Global shortcut
# (pre -> early out)
hunk_is_useful or next;
prune_hunk and ++$have_hunk;
} ## end for ( my $pos = 0 ; $pos...)
# If we have at least 1 useful hunk, create the output and tell the user what we've got.
$have_hunk
and build_output # (Always returns 1)
and printf( "%d Hunk%s\n", $have_hunk, $have_hunk > 1 ? "s" : "" )
or print( "clean\n" );
# Shell and xml files must be unprepared. See unprepare_[shell,xml]()
$hFile{pwxfile} and ( unprepare_shell or unprepare_xml );
# Now skip the writing if there are no hunks
$have_hunk or next;
# That's it, write the file and be done!
if ( open( my $fOut, ">", $hFile{patch} ) ) {
for my $line ( @{ $hFile{output} } ) {
# Do not assume empty comment lines with trailing spaces in shell files
$hFile{pwxfile} and $line =~ s/([+ -]#)\s+$/$1/;
print $fOut "$line\n";
} ## end for my $line ( @{ $hFile...})
close( $fOut );
} else {
printf( "ERROR: %s could not be opened for writing!\n%s\n", $hFile{patch}, $! );
die( "Please fix this first!" );
}
} ## End of main loop
# ===========================
# === END OF MAIN PROGRAM ===
# ===========================
# ================================================================
# === ==> -------- Cleanup -------- <== ===
# ================================================================
END {
# -------------------------------------------------------------------------
# --- Print out the list of files that only exist here and not upstream ---
# -------------------------------------------------------------------------
if ( scalar @only_here ) {
my $count = scalar @only_here;
my $fmt = sprintf( "%%d %d: %%s\n", length( "$count" ));
printf( "\n%d file%s only found in $WORKDIR:\n", $count, $count > 1 ? "s" : "" );
for ( my $i = 0; $i < $count; ++$i ) {
printf( $fmt, $i + 1, $only_here[$i] );
}
} ## end if ( scalar @only_here)
# -------------------------------------------------------------------------
# --- Print out the list of failed hunks -> bug in hunk or program? ---
# -------------------------------------------------------------------------
if ( scalar @lFails ) {
my $count = scalar @lFails;
printf( "\n%d file%s %s at least one fishy hunk:\n", $count, $count > 1 ? "s" : "",
$count > 1 ? "have" : "has" );
for ( my $i = 0; $i < $count; ++$i ) {
print "=== $lFails[$i]{part} ===\n";
print " => $lFails[$i]{msg} <=\n";
print "---------------------------\n";
print " {count} : \"" . $lFails[$i]{info}{count} . "\"\n";
print " {idx} : \"" . $lFails[$i]{info}{idx} . "\"\n";
print " {masked_end} : \"" . $lFails[$i]{info}{masked_end} . "\"\n";
print " {masked_start} : \"" . $lFails[$i]{info}{masked_start} . "\"\n";
print " {offset} : \"" . $lFails[$i]{info}{offset} . "\"\n";
print " {src_start} : \"" . $lFails[$i]{info}{src_start} . "\"\n";
print " {tgt_start} : \"" . $lFails[$i]{info}{tgt_start} . "\"\n";
print " {useful} : \"" . $lFails[$i]{info}{useful} . "\"\n";
print "---------------------------\n";
print "$_\n" foreach ( @{ $lFails[$i]{hunk} } );
} ## end for ( my $i = 0 ; $i < ...)
} ## end if ( scalar @lFails )
$do_stay or length( $previous_commit ) and checkout_upstream( $previous_commit );
} ## end END
# ================================================================
# === ==> ---- Function Implementations ---- <== ===
# ================================================================
# -----------------------------------------------------------------------
# --- Inititializes and fills %hFile. Old values are discarded. ---
# --- Adds files, that do not exist upstream, to @only_here. ---
# --- Returns 1 on success, 0 otherwise. ---
# -----------------------------------------------------------------------
sub build_hFile {
my ( $part ) = @_;
defined( $part ) and length( $part ) or print( "ERROR\n" ) and die( "build_hfile: part is empty ???" );
# Is this a new file?
my $isNew = defined( $hToCreate{$part} ) ? 1 : 0;
# We only prefixed './' to unify things. Now it is no longer needed:
$part =~ s,^\./,,;
# Pre: erase current $hFile, as that is what is expected.
clean_hFile();
# Check the target file
my $tgt = "$upstream_path/$part";
$tgt =~ s/elogind/systemd/g;
$tgt =~ s/\.pwx$//;
-f $tgt
or push( @only_here, $part )
and print "only here\n"
and return 0;
# Build the patch name
my $patch = $part;
$patch =~ s/\//_/g;
# Determine whether this is a shell or xml file needing preparations.
my $is_sh = 0;
my $is_xml = 0;
for my $pat ( @{ $FILE_NAME_PATTERNS{"xml"} } ) {
$part =~ m/$pat/ and $is_xml = 1 and last;
}
if ( 0 == $is_xml ) {
for my $pat ( @{ $FILE_NAME_PATTERNS{"shell"} } ) {
$part =~ m/$pat/ and $is_sh = 1 and last;
}
}
# Build the central data structure.
%hFile = (
count => 0,
create => $isNew,
hunks => [],
is_sh => $is_sh,
is_xml => $is_xml,
output => [],
part => "$part",
patch => "$PROGDIR/patches/${patch}.patch",
pwxfile => 0,
source => "$WORKDIR/$part",
target => "$tgt"
);
return 1;
} ## end sub build_hFile
# -----------------------------------------------------------------------
# --- Build a new $hHunk instance and add it to $hFile{hunks} ---
# -----------------------------------------------------------------------
sub build_hHunk {
my ( $head, @lHunk ) = @_;
my $pos = $hFile{count}++;
my $mark = '@@';
# The first line must be the hunk positional and size data.
# Example: @@ -136,6 +136,8 @@
# That is @@ -<source line>,<source length> +<target line>,<target length> @@
if ( $head =~ m/^${mark} -(\d+),\d+ \+(\d+),\d+ ${mark}/ ) {
%{ $hFile{hunks}[$pos] } = (
count => 0,
idx => $pos,
masked_end => 0,
masked_start => 0,
offset => 0,
src_start => $1,
tgt_start => $2,
useful => 1
);
# We need to chomp the lines:
for my $line ( @lHunk ) {
defined( $line ) or next;
chomp $line;
push @{ $hFile{hunks}[$pos]{lines} }, $line;
$hFile{hunks}[$pos]{count}++;
} ## end for my $line (@lHunk)
return 1;
} ## end if ( $head =~ m/^@@ -(\d+),\d+ \+(\d+),\d+ @@/)
print "Illegal hunk no $hFile{count}\n(Head: \"$head\")\nIgnoring...";
$hFile{count}--;
return 0;
} ## end sub build_hHunk
# -----------------------------------------------------------------------
# --- Writes $hFile{output} from all useful $hFile{hunks}. ---
# --- Important: No more checks, just do it! ---
# -----------------------------------------------------------------------
sub build_output {
my $offset = 0; ## Count building up target offsets
for ( my $pos = 0; $pos < $hFile{count}; ++$pos ) {
$hHunk = $hFile{hunks}[$pos]; ## Global shortcut
# The useless are to be skipped, but we need the hunks masked_end
if ( $hHunk->{useful} ) {
# --- Note down the relevant starting mask status ---
# ---------------------------------------------------
defined( $hHunk->{masked_start} ) and ( 1 == length( "$hHunk->{masked_start}" ) )
or return hunk_failed(
"build_output: Hunk "
. (
defined( $hHunk->{masked_start} )
? "with \"" . $hHunk->{masked_start} . "\""
: "without"
)
. " masked_start key found!"
);
$hFile{pwxfile} and push( @{ $hFile{output} }, "# masked_start " . $hHunk->{masked_start} );
# --- Add the header line ---------------------------
# ---------------------------------------------------
push( @{ $hFile{output} }, get_hunk_head( \$offset ));
# --- Add the hunk lines ----------------------------
# ---------------------------------------------------
for my $line ( @{ $hHunk->{lines} } ) {
push( @{ $hFile{output} }, $line );
}
} ## end if ( $hHunk->{useful} )
# --- Note down the relevant ending mask status -----
# ---------------------------------------------------
defined( $hHunk->{masked_end} ) and ( 1 == length( "$hHunk->{masked_end}" ) )
or return hunk_failed(
"build_output: Hunk "
. (
defined( $hHunk->{masked_end} )
? "with \"" . $hHunk->{masked_end} . "\""
: "without"
)
. " masked_end key found!"
);
$hFile{pwxfile} and push( @{ $hFile{output} }, "# masked_end " . $hHunk->{masked_end} );
} ## End of walking the hunks
return 1;
} ## end sub build_output
# -----------------------------------------------------------------------
# --- Check that useful blank line additions aren't misplaced. ---
# ---- Note: Sometimes the masks aren't placed correctly, and the diff---
# ---- wants to add a missing blank line. As it tried to remove ---
# ---- our mask first, it'll be added after. That's fine for ---
# ---- #endif, but not for #if 0. ---
# ---- At the same time, removal of one blank line after our ---
# ---- endif is also not in order. ---
# -----------------------------------------------------------------------
sub check_blanks {
# Early exits:
defined( $hHunk ) or return 0;
$hHunk->{useful} or return 0;
for ( my $i = 0; $i < $hHunk->{count}; ++$i ) {
my $line = \$hHunk->{lines}[$i]; ## Shortcut
# Check for misplaced addition
if ( ( $$line =~ m/^\+\s*$/ )
&& ( $i > 0 )
&& ( ( is_mask_start( $hHunk->{lines}[ $i - 1 ] ) || is_insert_start( $hHunk->{lines}[ $i - 1 ] ) ) ) ) {
# Simply swap the lines
my $tmp = $$line;
$$line = $hHunk->{lines}[ $i - 1 ];
$hHunk->{lines}[ $i - 1 ] = $tmp;
next;
} ## end if ( ( $$line =~ m/^\+\s*$/...))
# Check for unpleasant removals
if ( ( $$line =~ m/^\-\s*$/ )
&& ( $i > 0 )
&& ( ( is_mask_end( $hHunk->{lines}[ $i - 1 ] ) || is_insert_end( $hHunk->{lines}[ $i - 1 ] ) ) )
&& ( $i < ( $hHunk->{count} - 1 ) )
&& ( !( $hHunk->{lines}[ $i + 1 ] =~ m/^[-+ ]\s*$/ ) ) ) {
# Revert the removal
substr( $$line, 0, 1 ) = " ";
next;
} ## end if ( ( $$line =~ m/^\+\s*$/...))
} ## end for ( my $i = 0 ; $i < ...)
return 1;
} ## end sub check_blanks
# -----------------------------------------------------------------------
# --- Check comments we added for elogind specific information. ---
# --- These are all comments, and can be both single and multi line. ---
# -----------------------------------------------------------------------
sub check_comments {
# Early exits:
defined( $hHunk ) or return 0;
$hHunk->{useful} or return 0;
my $in_comment_block = 0;
for ( my $i = 0; $i < $hHunk->{count}; ++$i ) {
my $line = \$hHunk->{lines}[$i]; ## Shortcut
# Ignore protected lines
defined( $hProtected{$$line} ) and next;
# Check for comment block start
# -----------------------------
if ( $$line =~ m,^-\s*(/\*+|//+)\s+.*elogind, ) {
# Sanity check:
$in_comment_block
and return hunk_failed( "check_comments: Comment block start found in comment block!" );
# Only start the comment block if this is really a multiline comment
( ( $$line =~ m,^-\s*/\*+, ) && !( $$line =~ m,\*/[^/]*$, ) )
and $in_comment_block = 1;
# Revert the substract *if* this is not in a mask block
$in_mask_block and ( 1 > $in_else_block ) or substr( $$line, 0, 1 ) = " ";
next;
} ## end if ( $$line =~ m,^-\s*(/[*]+|/[/]+).*elogind,)
# Check for comment block end
# -----------------------------
if ( $in_comment_block && ( $$line =~ m,^-.*\*/\s*$, ) ) {
substr( $$line, 0, 1 ) = " ";
$in_comment_block = 0;
next;
}
# Check for comment block line
# -----------------------------
if ( $in_comment_block && ( $$line =~ m,^-, ) ) {
# Note: We do not check for anything else, as empty lines must be allowed.
substr( $$line, 0, 1 ) = " ";
next;
} ## end if ( $in_comment_block...)
# If none of the above applied, the comment block is over.
$in_comment_block = 0;
} ## end for ( my $i = 0 ; $i < ...)
return 1;
} ## end sub check_comments
# -----------------------------------------------------------------------
# --- Check for debug constructs ---
# --- Rules: ENABLE_DEBUG_ELOGIND must be taken like #if 1, *but* ---
# --- here an #else is valid and must stay fully. ---
# --- Further there might be multiline calls to ---
# --- log_debug_elogind() that must not be removed either. ---
# -----------------------------------------------------------------------
sub check_debug {
# Early exits:
defined( $hHunk ) or return 0;
$hHunk->{useful} or return 0;
# Count non-elogind block #ifs. This is needed, so normal
# #if/#else/#/endif constructs can be put inside both the
# debug and the release block.
my $regular_ifs = 0;
my $is_debug_func = 0; ## Special for log_debug_elogind()
for ( my $i = 0; $i < $hHunk->{count}; ++$i ) {
my $line = \$hHunk->{lines}[$i]; ## Shortcut
# Entering a debug construct block
# ---------------------------------------
if ( $$line =~ m/^-#if.+ENABLE_DEBUG_ELOGIND/ ) {
## Note: Here it is perfectly fine to be in an elogind mask or insert block.
substr( $$line, 0, 1 ) = " "; ## Remove '-'
$in_insert_block++; ## Increase instead of setting this to 1.
next;
} ## end if ( $$line =~ m/^-#if.+ENABLE_DEBUG_ELOGIND/)
# Count regular #if
$$line =~ m/^-#if/ and ++$regular_ifs;
# Switching to the release variant.
# ---------------------------------------
if ( ( $$line =~ m/^-#else/ ) && $in_insert_block && !$regular_ifs ) {
substr( $$line, 0, 1 ) = " "; ## Remove '-'
$in_else_block++; ## Increase instead of setting this to 1.
next;
}
# Ending a debug construct block
# ---------------------------------------
if ( $$line =~ m,^-#endif\s*///?.*ENABLE_DEBUG_, ) {
( !$in_insert_block )
and return hunk_failed( "check_debug: #endif // ENABLE_DEBUG_* found outside any debug construct" );
substr( $$line, 0, 1 ) = " "; ## Remove '-'
$in_insert_block--; ## Decrease instead of setting to 0. This allows such
$in_else_block--; ## blocks to reside in regular elogind mask/insert blocks.
next;
} ## end if ( $$line =~ m,^-#endif\s*///?.*ENABLE_DEBUG_,)
# End regular #if
$$line =~ m/^-#endif/ and --$regular_ifs;
# Check for log_debug_elogind()
# ---------------------------------------
if ( $$line =~ m/^-.*log_debug_elogind\s*\(/ ) {
substr( $$line, 0, 1 ) = " "; ## Remove '-'
$$line =~ m/\)\s*;/ or ++$is_debug_func;
next;
}
# Remove '-' prefixes in all lines within the debug construct block
# -------------------------------------------------------------------
if ( ( $$line =~ m,^-, ) && ( $in_insert_block || $is_debug_func ) ) {
substr( $$line, 0, 1 ) = " "; ## Remove '-'
# Note: Everything in *any* insert block must not be removed anyway.
}
# Check for the end of a multiline log_debug_elogind() call
# ---------------------------------------------------------
$is_debug_func and $$line =~ m/\)\s*;/ and --$is_debug_func;
} ## End of looping lines
return 1;
} ## end sub check_debug
# -----------------------------------------------------------------------
# --- Check for attempts to remove elogind_*() special function calls. --
# --- We have some special functions, needed only by elogind. ---
# --- One of the most important ones is elogind_set_program_name(), ---
# --- which has an important role in musl_libc compatibility. ---
# --- These calls must not be removed of course. ---
# -----------------------------------------------------------------------
sub check_func_removes {
# Early exits:
defined( $hHunk ) or return 1;
$hHunk->{useful} or return 1;
# Not used in pwx files (meson, xml, sym)
$hFile{pwxfile} and return 1;
# Needed for multi-line calls
my $is_func_call = 0;
for ( my $i = 0; $i < $hHunk->{count}; ++$i ) {
my $line = \$hHunk->{lines}[$i]; ## Shortcut
# Ignore protected lines
defined( $hProtected{$$line} ) and next;
# Check for elogind_*() call
# -------------------------------------------------------------------
if ( $$line =~ m/^-.*elogind_\S+\s*\(/ ) {
substr( $$line, 0, 1 ) = " "; ## Remove '-'
$$line =~ m/\)\s*;/ or ++$is_func_call;
next;
}
# Remove '-' prefixes in all lines that belong to an elogind_*() call
# -------------------------------------------------------------------
if ( ( $$line =~ m,^-, ) && $is_func_call ) {
substr( $$line, 0, 1 ) = " "; ## Remove '-'
}
# Check for the end of a multiline elogind_*() call
# -------------------------------------------------------------------
$is_func_call and $$line =~ m/\)\s*;/ and --$is_func_call;
} ## end for ( my $i = 0 ; $i < ...)
return 1;
} ## end sub check_func_removes
# ------------------------------------------------------------------------
# --- Check for empty masks. These are blocks where the masked sources ---
# --- are gone. If there is an #else block, it will become and insert ---
# --- block. If anything got changed, a message is left as a comment: ---
# --- /// elogind empty mask removed or ---
# --- /// elogind empty mask else converted ---
# ------------------------------------------------------------------------
sub check_empty_masks {
# Early exits:
defined( $hHunk ) or return 1;
$hHunk->{useful} or return 1;
# We must not touch the global values!
# Note: We search for two successive lines, so this should be easy enough.
my $local_ieb = 0;
my $local_iib = 0;
my $local_imb = $hHunk->{masked_start};
# Count non-elogind block #ifs. This is needed, so normal
# #if/#else/#/endif constructs can be put inside elogind mask blocks.
my $regular_ifs = 0;
# Note down the line numbers where we found #if for quicker access
my $mask_block_start = -1;
# We need to know whether to convert an insert line or not
my $need_endif_conversion = 0;
# If we leave a note, add the original mask message
my $mask_message = "";
for ( my $i = 0; $i < $hHunk->{count}; ++$i ) {
my $line = \$hHunk->{lines}[$i]; ## Shortcut
# Entering an elogind mask
# ---------------------------------------
if ( is_mask_start( $$line ) ) {
# No checks needed, check_masks() already did that, and later pruning might make
# checks here fail, if large else block removals got reverted and the hunk(s) pruned.
$local_iib = 0;
$local_imb = 1;
$mask_block_start = $i;
# Note down mask message in case we leave a message
$$line =~ m,///\s*(.+)\s*$, and $mask_message = $1;
next;
} ## end if ( is_mask_start($$line...))
# Entering an elogind insert
# ---------------------------------------
if ( is_insert_start( $$line ) ) {
$local_iib = 1;
$local_ieb = 0;
# Note down mask message in case we leave a message
$$line =~ m,///\s*(.+)\s*$, and $mask_message = $1;
next;
} ## end if ( is_insert_start($$line...))
# Count regular #if
$$line =~ m/^-#if/ and ++$regular_ifs;
# Switching from Mask to else.
# Note: Inserts have no #else, they make no sense.
# ---------------------------------------
if ( is_mask_else( $$line ) ) {
$local_ieb = 1;
# If the else starts right after a mask start, we have to do something about it, if there is enough space left in the patch
# (Which should be the case as the else block would have lengthened it. But better check it to be safe!)
if ( $i && ( $i == ( $mask_block_start + 1 ) ) && ( $i < ( $hHunk->{count} - 2 ) ) ) {
# Re-enable the removal of the "#if 0" and of the "#else" line
substr( $hHunk->{lines}[ $i - 1 ], 0, 1 ) = "-";
substr( $hHunk->{lines}[$i], 0, 1 ) = "-";
# Add a note that we converted this and add an insert mask
splice( @{ $hHunk->{lines} }, $i + 1, 0, (
"+/// elogind empty mask else converted",
"+#if 1 /// $mask_message" ) );
$hHunk->{count} += 2;
$need_endif_conversion = 1;
$i += 2; ## Already known...
} ## end if ( $i == ( $mask_block_start...))
$mask_block_start = -1;
next;
} ## end if ( $local_imb && !$regular_ifs...)
# Ending a Mask block
# ---------------------------------------
if ( is_mask_end( $$line ) ) {
# If the endif is right after the mask start, we have to do something about it, but only if we have enough space left in the patch
if ( $i < ( $hHunk->{count} - 2 ) ) {
if ( $i && ( $i == ( $mask_block_start + 1 ) ) ) {
# Re-enable the removal of the "#if 0" and of the "#endif" line
substr( $hHunk->{lines}[ $i - 1 ], 0, 1 ) = "-";
substr( $hHunk->{lines}[$i], 0, 1 ) = "-";
# Add a note that we converted this