-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathZMOprMerge.pas
1429 lines (1355 loc) · 39.8 KB
/
ZMOprMerge.pas
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
unit ZMOprMerge;
// ZMMergeOpr.pas - MergeZipped operation
(* ***************************************************************************
TZipMaster VCL originally by Chris Vleghert, Eric W. Engler.
Present Maintainers and Authors Roger Aelbrecht and Russell Peters.
Copyright (C) 1997-2002 Chris Vleghert and Eric W. Engler
Copyright (C) 1992-2008 Eric W. Engler
Copyright (C) 2009, 2010, 2011, 2012, 2013 Russell Peters and Roger Aelbrecht
Copyright (C) 2014 Russell Peters and Roger Aelbrecht
All rights reserved.
For the purposes of Copyright and this license "DelphiZip" is the current
authors, maintainers and developers of its code:
Russell Peters and Roger Aelbrecht.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* DelphiZip reserves the names "DelphiZip", "ZipMaster", "ZipBuilder",
"DelZip" and derivatives of those names for the use in or about this
code and neither those names nor the names of its authors or
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL DELPHIZIP, IT'S AUTHORS OR CONTRIBUTERS BE
LIABLE FOR ANYDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
contact: problems AT delphizip DOT org
updates: http://www.delphizip.org
*************************************************************************** *)
// modified 2013-12-05
{$I '.\ZipVers.inc'}
interface
uses
{$IFDEF VERDXE2up}
System.Classes,
{$ELSE}
Classes,
{$ENDIF}
ZMHandler, ZipMstr;
type
TZMOpMerge = class(TZMOperationRoot)
private
FOpts: TZMMergeOpts;
public
constructor Create(Opts: TZMMergeOpts);
function Changes: TZMOperRes; override;
function Execute(TheBody: TZMHandler): Integer; override;
function Name: string; override;
function Needs: TZMOperRes; override;
end;
implementation
uses
{$IFDEF VERDXE2up}
WinApi.Windows, System.SysUtils, VCL.Graphics, VCL.Dialogs, VCL.Controls,
{$ELSE}
Windows, SysUtils, Graphics, Dialogs, Controls,
{$IFNDEF VERD7up}ZMCompat, {$ENDIF}
{$ENDIF}
ZMLister, ZMBody, ZMMisc, ZMArgSplit, ZMZipBase, ZMZipReader, ZMZipWriter,
ZMZipDirectory, ZMUnzipOpr, ZMXcpt, ZMStructs, ZMUtils, ZMDlg, ZMCtx,
ZMMsg, ZMDrv, ZMZipMulti, ZMCore;
const
__UNIT__ = 30;
type
TSFXOps = (SfoNew, SfoZip, SfoExe);
type
TMOArgOptions = record
Arg: string;
Excludes: string;
NFlag: Boolean;
XArg: string;
end;
type
// provides support for auto-open of source zips
TZMZipMerger = class(TZMZipCopier)
private
FLastOpened: TZMZipBase;
procedure SetLastOpened(const Value: TZMZipBase);
protected
function CommitRec(Rec: TZMEntryWriter): Int64; override;
property LastOpened: TZMZipBase read FLastOpened write SetLastOpened;
public
procedure AfterConstruction; override;
end;
TZMEntryMerger = class(TZMEntryCopier)
private
FKeep: Boolean;
protected
function GetTitle: string; override;
public
procedure AfterConstruction; override;
function Process: Int64; override;
property Keep: Boolean read FKeep write FKeep;
end;
type
TZMMergeOpr = class(TZMUnzipOpr)
private
procedure AssignArgOptions(var Locals: TMOArgOptions;
const Args: TMOArgOptions);
procedure ClearAppend;
function CommitAppend: Integer;
function ExtractChildZip(ParentIndex: Integer;
const MyName: string): Integer;
function FlattenExcludes(Excludes: TStrings): string;
function IncludeAZip(const SourceName: string): Integer;
function MergeAnotherZip(const SourceName: string): Integer;
function MergeAnotherZip1(const SourceName: string): Integer;
function MergeAnotherZipInZip(const SourceName: string): Integer;
function MergeIntermediate(SelectedCount: Integer;
const Opts: TZMMergeOpts): Integer;
function MergeIntermedZip(RefZip: TZMZipReader; ZipIndex: Integer;
Opts: TZMMergeOpts): Integer;
function MergePrepareName(var ZName: string; ZRec: TZMEntryBase): Integer;
function MergeResolveConflict(RefRec, NRec: TZMEntryCopier;
const Opts: TZMMergeOpts): Integer;
function MergeSafeName(ZipIndex: Integer; const Name: string): string;
function Prepare(MustExist: Boolean; SafePart: Boolean = False)
: TZMZipReader;
function PrepareAppend: Boolean;
function ProcessInclude(SrcZip: TZMZipReader;
const Args: TMOArgOptions): Integer;
function ProcessIncludeList(var SelectCount: Integer): Integer;
function ResolveConfirm(const ExistName: string; ExistRec: TZMEntryBase;
const ConflictName: string; ConflictRec: TZMEntryBase;
const NewName: string): TZMResolutions;
procedure SetArgsOptionsFromSplitter(var Args: TMOArgOptions;
const ParentExcludes: string);
procedure SetupAppendRecs(Allow: Boolean);
protected
FOutZip: TZMZipCopier;
FSkippedFiles: TStringList;
FSplitter: TZMArgSplitter;
FZipList: TZMZipList;
procedure CreateInterimZip; override;
function FinalizeInterimZip(OrigZip: TZMZipReader): Integer; override;
function MergeWrite: Integer;
public
procedure AfterConstruction; override;
procedure BeforeDestruction; override;
function CleanZipName(const FileName: string): string;
function MergeZippedFiles(Opts: TZMMergeOpts;
TheDest: TZMZipWriter): Integer;
end;
type
TZMMergeArgs = class(TZMSelectArgs)
private
FFromDate: Cardinal;
Flist: TStrings;
FNFlag: Boolean;
FXArg: string;
FZipName: string;
public
function Accept(Rec: TZMEntryBase): Boolean; override;
procedure AfterConstruction; override;
procedure Assign(Other: TZMSelectArgs); override;
property FromDate: Cardinal read FFromDate write FFromDate;
property List: TStrings read Flist write Flist;
property NFlag: Boolean read FNFlag write FNFlag;
property XArg: string read FXArg write FXArg;
property ZipName: string read FZipName write FZipName;
end;
const
DeleteIncludeListThreshold = 20;
MergeIncludeListThreshold = 10;
PrepareAppendThreshold = 10;
function ZM_Error(Line, Error: Integer): Integer;
begin
Result := -((__UNIT__ shl ZERR_UNIT_SHIFTS) + (Line shl ZERR_LINE_SHIFTS) or
AbsErr(Error));
end;
procedure TZMMergeOpr.AfterConstruction;
begin
inherited;
FSkippedFiles := nil;
FZipList := TZMZipList.Create;
FSkippedFiles := TStringList.Create;
FSplitter := TZMArgSplitter.Create;
end;
procedure TZMMergeOpr.AssignArgOptions(var Locals: TMOArgOptions;
const Args: TMOArgOptions);
begin
Locals.Arg := Args.Arg;
Locals.Excludes := Args.Excludes;
Locals.NFlag := Args.NFlag;
Locals.XArg := Args.XArg;
end;
procedure TZMMergeOpr.BeforeDestruction;
begin
FSkippedFiles.Free;
FZipList.Free;
FSplitter.Free;
inherited;
end;
// rebuild file name without spaces
function TZMMergeOpr.CleanZipName(const FileName: string): string;
var
Ancestors: string;
Done: Boolean;
Generation: string;
begin
Result := '';
Ancestors := FileName;
repeat
SplitQualifiedName(Ancestors, Ancestors, Generation);
Done := Generation = '';
if Done then
Generation := Ancestors;
if Result <> '' then
Result := Generation + ZFILE_SEPARATOR + Result
else
Result := Generation;
until Done;
end;
procedure TZMMergeOpr.ClearAppend;
begin
SetupAppendRecs(False); // clear flags
end;
function TZMMergeOpr.CommitAppend: Integer;
var
DstZip: TZMZipReader;
begin
DstZip := FZipList[0];
DstZip.File_Close; // don't aquire handle
FOutZip.Stream := DstZip.ReleaseStream;
FOutZip.ArchiveName := DstZip.ArchiveName;
Result := FOutZip.File_Reopen(FmOpenReadWrite);
if Result >= 0 then
Result := FOutZip.Commit(ZwoZipTime in WriteOptions);
end;
// does not create a temperary file
procedure TZMMergeOpr.CreateInterimZip;
begin
InterimZip := TZMZipMerger.Create(Lister);
end;
// Extract MyName from FZipList[ParentIndex] and add to FZipList if successful
function TZMMergeOpr.ExtractChildZip(ParentIndex: Integer;
const MyName: string): Integer;
var
Entry: TZMEntryBase;
Idx: Integer;
MyFile: TZMZipReader;
Parent: TZMZipReader;
ParentName: string;
TheZip: TZMZipReader;
begin
// be safe
if (ParentIndex <= 0) or (MyName = '') then
begin
Result := ZM_Error({_LINE_}288, ZE_NoInFile);
Exit;
end;
Parent := FZipList[ParentIndex];
ParentName := Parent.ArchiveName;
if ParentName = '' then
begin
Result := ZM_Error({_LINE_}295, ZE_NoInFile);
Exit;
end;
TheZip := TZMZipReader.Create(Lister);
try
TheZip.ArchiveName := ParentName;
Body.Trace('Loading parent zip', {_LINE_}301, __UNIT__);
Result := TheZip.OpenZip(False, False);
if Result >= 0 then
begin
// loaded ok - see if file exists
Idx := -1;
Entry := TheZip.SearchName(MyName, True, Idx);
// find first matching pattern
if Entry <> nil then
begin
// create a temporary file
MyFile := TZMZipReader.Create(Lister);
try
MyFile.Alias :=
QualifiedName(FZipList[ParentIndex].Name(False), MyName);
MyFile.File_CreateTemp('Zcy', '');
Result := UnzipAStream(MyFile.Stream, Entry);
if Result = 0 then
begin
// good
MyFile.File_Close;
Result := MyFile.OpenZip(False, False);
MyFile.File_Close;
if Result >= 0 then
begin
Result := FZipList.Add(MyFile); // add to list and return Index
MyFile.File_Close;
if Result > 0 then
MyFile := nil; // do not free
end;
end
else
begin
// extracting zip failed
MyFile.Position := 0;
MyFile.SetEndOfFile;
MyFile.File_Close;
Result := ZM_Error({_LINE_}338, ZE_NoWrite);
// error does not matter
end;
finally
MyFile.Free;
end;
end;
end;
finally
TheZip.Free;
end;
end;
function TZMMergeOpr.FinalizeInterimZip(OrigZip: TZMZipReader): Integer;
begin
if (InterimZip.ArchiveName = '') and not InterimZip.File_CreateTemp
(PRE_INTER, '') then
raise EZipMaster.CreateMsg(Body, ZE_NoOutFile, {_LINE_}355, __UNIT__);
Result := inherited FinalizeInterimZip(OrigZip);
end;
function TZMMergeOpr.FlattenExcludes(Excludes: TStrings): string;
var
I: Integer;
begin
Result := '';
// flatten the list
for I := 0 to Excludes.Count - 1 do
begin
if Excludes[I] = '' then
Continue;
if Result <> '' then
Result := Result + SPEC_SEP;;
Result := Result + Excludes[I];
end;
end;
function TZMMergeOpr.IncludeAZip(const SourceName: string): Integer;
var
Skip: TZMSkipTypes;
begin
Result := FZipList.Find(SourceName); // already in list?
if Result = 0 then
begin
Result := ZM_Error({_LINE_}382, ZE_SourceIsDest);
Exit;
end;
if Result < 0 then
begin
// have not opened file yet _ not in list
Result := MergeAnotherZip(SourceName);
if AbsErr(Result) = ZE_SameAsSource then
Exit;
if Result = 0 then
begin
Result := ZM_Error({_LINE_}393, ZE_SourceIsDest);
Exit;
end;
if Result < 0 then
begin
// file does not exist or could not be opened
Body.InformFmt('Skipped missing or bad zip [%d] %s',
[AbsErr(Result), SourceName], {_LINE_}400, __UNIT__);
case AbsErr(Result) of
ZE_NoInFile:
Skip := StNotFound;
ZE_FileOpen:
Skip := StNoOpen;
else
Skip := StReadError;
end;
if not Skipping(SourceName, Skip, Result) then
Result := 0; // we can ignore it
end;
end;
end;
// opens a zip file for merging and adds to FZipList
// return <0 _ error, >= 0 _ Index in FZipList
function TZMMergeOpr.MergeAnotherZip(const SourceName: string): Integer;
begin
if Pos(ZFILE_SEPARATOR, SourceName) > 0 then
Result := MergeAnotherZipInZip(SourceName) // handle Zip in Zip
else
Result := MergeAnotherZip1(SourceName);
end;
// opens a zip file for merging and adds to FZipList
// return <0 _ error, >= 0 _ Index in FZipList
function TZMMergeOpr.MergeAnotherZip1(const SourceName: string): Integer;
var
Dzip: TZMZipReader;
SrcZip: TZMZipReader;
begin
// have not opened file yet
SrcZip := TZMZipReader.Create(Lister);
try
begin
SrcZip.ArchiveName := SourceName;
Result := SrcZip.OpenZip(False, False);
if Result >= 0 then
begin
Dzip := FZipList[0];
if (SrcZip.WorkDrive.DriveLetter = Dzip.WorkDrive.DriveLetter) and
(not Dzip.WorkDrive.DriveIsFixed) and
(Dzip.MultiDisk or SrcZip.MultiDisk or (ZwoDiskSpan in WriteOptions))
then
Result := ZM_Error({_LINE_}445, ZE_SameAsSource)
else
begin
Result := FZipList.Add(SrcZip); // add to list and return Index
SrcZip.File_Close;
if Result > 0 then
SrcZip := nil; // accepted so do not free
end;
end;
end;
finally
SrcZip.Free;
end;
end;
// handle Zip in Zip
function TZMMergeOpr.MergeAnotherZipInZip(const SourceName: string): Integer;
var
MyName: string;
MyOwner: string;
begin
SplitQualifiedName(SourceName, MyOwner, MyName);
// find MyOwner
Result := FZipList.Find(MyOwner);
if Result < 0 then
begin
// not found _ maybe MyOwner not added yet
Result := MergeAnotherZip(MyOwner); // recursively add parents
end;
if Result > 0 then
begin
// we have owner in FZipList
// open MyOwner and extract MyName to temporary
Result := ExtractChildZip(Result, MyName);
end;
end;
// create the intermediate from DstZip and selected entries
function TZMMergeOpr.MergeIntermediate(SelectedCount: Integer;
const Opts: TZMMergeOpts): Integer;
var
MaxCount: Integer;
RefZip: TZMZipReader;
RefZipIndex: Integer;
SelCount: Integer;
begin
Result := 0;
PrepareInterimZip;
FOutZip := InterimZip as TZMZipMerger;
// replicate all records and settings
FOutZip.Select('*', ZzsSet); // want all (initially)
Progress.NewXtraItem(ZxMerging, FZipList.Count);
// add the possibly altered selected entries
// [0] is 'DstZip'
MaxCount := 0;
for RefZipIndex := 0 to FZipList.Count - 1 do
MaxCount := MaxCount + FZipList[RefZipIndex].SelCount;
FOutZip.HTAutoSize(MaxCount);
for RefZipIndex := 0 to FZipList.Count - 1 do
begin
Progress.AdvanceXtra(1);
CheckCancel;
RefZip := FZipList[RefZipIndex];
SelCount := RefZip.SelCount;
Body.TraceFmt('Processing %d files: %s', [SelCount, RefZip.Name],
{_LINE_}510, __UNIT__);
if SelCount < 1 then
Continue;
Result := MergeIntermedZip(RefZip, RefZipIndex, Opts);
end;
end;
// Merge selected entries from RefZip into FOutZip
function TZMMergeOpr.MergeIntermedZip(RefZip: TZMZipReader; ZipIndex: Integer;
Opts: TZMMergeOpts): Integer;
var
Cnt: Integer;
NewRec: TZMEntryMerger;
Rec: TZMEntryBase;
RefRec: TZMEntryCopier;
Skp: TZMSkipTypes;
ZName: string;
ZRec: TZMEntryBase;
begin
Result := 0; // keep compiler happy
// process each selected entry
Rec := RefZip.FirstSelected;
Cnt := 0;
while (Rec <> nil) do
begin
Inc(Cnt);
if (Cnt and 63) = 0 then
CheckCancel;
Result := 0;
ZRec := Rec;
Rec := RefZip.NextSelected(Rec);
ZName := ZRec.FileName;
if ZipIndex > 0 then
begin
Result := MergePrepareName(ZName, ZRec);
if Result < 0 then
Break; // error
if ZName = '' then
Continue; // entry ignored by user
end;
// make new CopyRec
NewRec := TZMEntryMerger.Create(FOutZip); // make a entry
NewRec.AssignFrom(ZRec);
NewRec.Link := ZRec; // link to original
if Result = 1 then
begin
NewRec.SetStatusBit(ZsbRenamed);
Result := NewRec.ChangeName(ZName);
if Result < 0 then
begin
NewRec.Free; // stop leak
Body.InformFmt('Failed rename [%d] %s to %s',
[-Result, ZRec.FileName, ZName], {_LINE_}562, __UNIT__);
Skp := StUser;
case AbsErr(Result) of
ZE_BadFileName:
Skp := StBadName;
ZE_DuplFileName:
Skp := StDupName;
end;
if Skp = StUser then
Break; // unknown error - fatal
if Skipping(QualifiedName(RefZip.Name, ZName), Skp, Result) then
Break; // fatal
Continue; // ignore
end;
Body.InformFmt('Renamed %s to %s', [ZRec.FileName, NewRec.FileName],
{_LINE_}577, __UNIT__);
end;
// does it exist
RefRec := TZMEntryCopier(FOutZip.FindName(ZName, nil));
Result := 0;
if RefRec <> nil then
begin
// duplicate found - resolve it
Result := MergeResolveConflict(RefRec, NewRec, Opts);
end;
if Result = 0 then
begin
Result := FOutZip.Add(NewRec); // use NewRec
FOutZip.HTAdd(NewRec, False);
end
else
NewRec.Free; // stop leak
if Result < 0 then
Break;
end;
end;
// returns <0 = error, 0 = no change, 1 = changed, 2 = ignored by user
function TZMMergeOpr.MergePrepareName(var ZName: string;
ZRec: TZMEntryBase): Integer;
var
Args: TZMMergeArgs;
Changed: Boolean;
FileName: string;
Old: string;
Sep: Integer;
Subst: string;
TmpOnSetAddName: TZMSetAddNameEvent;
ZipName: string;
begin
Result := 0;
ZName := ZRec.FileName;
Args := TZMMergeArgs(ZRec.SelectArgs);
ZipName := ZRec.MyFile.Name;
if (Args = nil) or not Args.NFlag then
begin
TmpOnSetAddName := Master.OnSetAddName;
if Assigned(TmpOnSetAddName) then
begin
Changed := False;
FileName := ZName;
TmpOnSetAddName(Master, FileName, QualifiedName(ZipName,
FileName), Changed);
if Changed then
begin
Result := 1; // changed
// verify valid
if FileName = '' then
begin
Result := ZM_Error({_LINE_}632, ZE_EntryCancelled);
if not Skipping(QualifiedName(ZipName, ZRec.FileName), StUser, Result)
then
Result := 2; // ignore entry
ZName := FileName;
Exit;
end;
FileName := SetSlash(FileName, PsdExternal);
ZName := FileName;
end;
end;
end;
if (Args <> nil) and (Args.XArg <> '') then
begin
Old := Args.XArg;
Sep := Pos('::', Old);
Subst := Copy(Old, Sep + 2, 2048);
Old := Copy(Old, 1, Sep - 1);
if Old = '' then
FileName := Subst + ZName
else
begin
Old := SetSlash(Old, PsdExternal);
if Pos(Old, ZName) <= 0 then
begin
// no change
Result := 0;
Exit;
end;
FileName := StringReplace(ZName, Old, Subst,
[RfReplaceAll, RfIgnoreCase]);
end;
FileName := SetSlash(FileName, PsdExternal);
Result := 1; // changed
// verify valid
ZName := FileName;
end;
end;
// return <0 = error, 0 = use NRec, 1 = discard NRec
function TZMMergeOpr.MergeResolveConflict(RefRec, NRec: TZMEntryCopier;
const Opts: TZMMergeOpts): Integer;
var
ConflictZipName: string;
NewName: string;
RefZipName: string;
Resolve: TZMResolutions;
begin
RefZipName := RefRec.Link.MyFile.Name;
ConflictZipName := NRec.Link.MyFile.Name;
if Verbosity >= ZvTrace then
Body.TraceFmt('Found conflict for %s in %s',
[QualifiedName(RefZipName, RefRec.FileName), ConflictZipName],
{_LINE_}685, __UNIT__);
Resolve := ZmrConflicting;
NewName := MergeSafeName(1, RefRec.FileName);
case Opts of
ZmoConfirm:
Resolve := ResolveConfirm(RefZipName, RefRec, ConflictZipName,
NRec, NewName);
ZmoAlways:
;
ZmoNewer:
if RefRec.ModifDateTime >= NRec.ModifDateTime then
Resolve := ZmrExisting;
ZmoOlder:
if RefRec.ModifDateTime <= NRec.ModifDateTime then
Resolve := ZmrExisting;
ZmoNever:
Resolve := ZmrExisting;
ZmoRename:
Resolve := ZmrRename;
end;
Result := 0;
case Resolve of
ZmrExisting:
begin
Result := Body.PrepareErrMsg(ZE_Existing, [NRec.FileName],
{_LINE_}710, __UNIT__);
if not Skipping(QualifiedName(ConflictZipName, NRec.FileName),
StFileExists, Result) then
begin
NRec.Selected := False;
NRec.SetStatusBit(ZsbDiscard);
Result := 1; // discard NRec
end;
end;
ZmrConflicting:
begin
Result := Body.PrepareErrMsg(ZE_Existing, [RefRec.FileName],
{_LINE_}722, __UNIT__);
if not Skipping(QualifiedName(RefZipName, RefRec.FileName),
StFileExists, Result) then
begin
RefRec.Selected := False;
RefRec.SetStatusBit(ZsbDiscard);
Result := 0;
end;
end;
ZmrRename:
begin
// zmrRename _ keep RefRec, rename and keep NRec
NRec.SetStatusBit(ZsbRenamed);
Result := NRec.ChangeName(NewName);
if (Result < 0) then
begin
Result := Body.PrepareErrMsg(ZE_Existing, [RefRec.FileName],
{_LINE_}739, __UNIT__);
if not Skipping(QualifiedName(RefZipName, RefRec.FileName),
StFileExists, Result) then
Result := 1; // ignore
end
else
begin
NRec.Selected := True;
NRec.SetStatusBit(ZsbRenamed);
Result := 0;
end;
end;
end;
end;
function TZMMergeOpr.MergeSafeName(ZipIndex: Integer;
const Name: string): string;
var
EName: string;
Extn: string;
N: Cardinal;
begin
EName := ExtractFilePath(Name) + ExtractNameOfFile(Name);
Extn := ExtractFileExt(Name);
N := 0;
repeat
if N = 0 then
Result := Format('%s[%d]%s', [EName, ZipIndex, Extn])
else
Result := Format('%s[%d.%x]%s', [EName, ZipIndex, N, Extn]);
Inc(N);
until (FOutZip.FindName(Result, nil) = nil);
end;
function TZMMergeOpr.MergeWrite: Integer;
var
DstZip: TZMZipReader; // orig dest zip (read only)
Existed: Boolean;
Includes: Integer;
Rec: TZMEntryCopier;
RenamedCnt: Integer;
ReplaceCnt: Integer;
Rubbish: Integer;
SourceZip: TZMZipReader;
TotalCnt: Integer;
WillSplit: Boolean;
ZRec: TZMEntryBase;
begin
// find total files in dest and list of files added/replaced
DstZip := FZipList[0];
Body.ClearIncludeSpecs; // add names of files to be added
Includes := 0;
TotalCnt := 0;
ReplaceCnt := 0;
Rubbish := 0;
RenamedCnt := 0;
ZRec := FOutZip.FirstRec;
while ZRec <> nil do
begin
CheckCancel;
Rec := TZMEntryCopier(ZRec);
ZRec := ZRec.Next;
if Rec.StatusBit[ZsbError or ZsbDiscard or ZsbSelected] <> ZsbSelected then
begin
Inc(Rubbish);
Continue;
end;
SourceZip := TZMZipReader(Rec.Link.MyFile);
if Rec.StatusBit[ZsbDiscard] <> 0 then
begin
if SourceZip = DstZip then
Inc(ReplaceCnt);
Inc(Rubbish);
Continue;
end;
Inc(TotalCnt);
if SourceZip = DstZip then
Continue;
// count and mark for later adding to FSpecArgs
if Rec.StatusBit[ZsbRenamed] <> 0 then
Inc(RenamedCnt);
Rec.Status[ZsbHail] := True;
Inc(Includes);
end;
Body.TraceFmt('Total=%d, Replaced=%d, New=%d, Discarded=%d, Renamed=%d',
[TotalCnt, ReplaceCnt, Includes, Rubbish, RenamedCnt], {_LINE_}824,
__UNIT__);
if (TotalCnt < 1) or (Includes < 1) then
begin
Body.Inform('nothing to do', {_LINE_}828, __UNIT__);
Result := ZM_Error({_LINE_}829, ZE_NothingToDo);
if not Skipping(DstZip.Name, StNothingToDo, Result) then
Result := 0;
Exit;
end;
// can we just append to original
Existed := (Zfi_Loaded and DstZip.Info) <> 0;
WillSplit := DstZip.MultiDisk or
((not Existed) and (ZwoDiskSpan in WriteOptions));
if (not WillSplit) or (not(ZwoSafe in WriteOptions)) then
begin
if not Existed then
begin // need to create the new file
// write new file
FOutZip.ArchiveName := DstZip.ArchiveName;
FOutZip.ZipComment := Lister.ZipComment; // keep orig
ShowProgress := ZspFull;
if Assigned(DstZip.Stub) and DstZip.UseSFX then
begin
FOutZip.AssignStub(DstZip);
FOutZip.UseSFX := True;
end;
Result := ZM_Error({_LINE_}852, ZE_NoOutFile);
FOutZip.File_Create(DstZip.ArchiveName);
if FOutZip.IsOpen then
begin
Result := FOutZip.Commit(ZwoZipTime in WriteOptions);
FOutZip.File_Close;
FZipList.CloseAll; // close all source files
end;
if Result < 0 then
Body.InformFmt('Merging new file failed: %d', [AbsErr(Result)],
{_LINE_}862, __UNIT__);
Exit;
end
else
begin
// try to append to existing zip
if PrepareAppend then
begin
// commit it
Result := CommitAppend;
if Result >= 0 then
Body.Trace('Merging append successful', {_LINE_}873, __UNIT__);
if AbsErr(Result) <> ZE_NoAppend then
Exit;
// fix to allow safe write
ClearAppend;
Body.InformFmt('Merging append failed: %d', [-Result],
{_LINE_}879, __UNIT__);
end;
end;
end;
// write to intermediate
if WillSplit then
FOutZip.File_CreateTemp(PRE_INTER, '')
else
FOutZip.File_CreateTemp(PRE_INTER, DstZip.ArchiveName);
if not FOutZip.IsOpen then
begin
Result := ZM_Error({_LINE_}891, ZE_NoOutFile);
Exit;
end;
if not WillSplit then
begin
// initial temporary destination
if Assigned(DstZip.Stub) and DstZip.UseSFX then
begin
FOutZip.AssignStub(DstZip);
FOutZip.UseSFX := True;
end;
FOutZip.DiskNr := 0;
end;
FOutZip.ZipComment := DstZip.ZipComment; // keep orig
ShowProgress := ZspFull;
// now we write it
Result := FOutZip.Commit(ZwoZipTime in WriteOptions);
FOutZip.File_Close;
FZipList.CloseAll; // close all source files
if Result >= 0 then
begin
if (FOutZip.Count - Rubbish) <> TotalCnt then
Result := ZM_Error({_LINE_}913, ZE_InternalError)
else
Result := Recreate(FOutZip, DstZip); // all correct so Recreate source
end;
end;
// IncludeSpecs = Zips and files to include
// zipname
// ExcludeSpecs = files to exclude
function TZMMergeOpr.MergeZippedFiles(Opts: TZMMergeOpts;
TheDest: TZMZipWriter): Integer;
var
DstZip: TZMZipReader;
SelectCount: Integer;
begin
if Body.Logging then
Body.LogSpecs('');
ShowProgress := ZspFull;
FOutZip := nil; // will be used to write the output
if IncludeSpecs.Count < 1 then
raise EZipMaster.CreateMsg(Body, ZE_InvalidArguments, {_LINE_}933,
__UNIT__);
if ZipFileName = '' then
raise EZipMaster.CreateMsg(Body, ZE_NoZipSpecified, {_LINE_}936, __UNIT__);
FZipList.Clear;
FSkippedFiles.Clear;
if TheDest <> nil then
DstZip := TheDest
else
DstZip := Prepare(False, True);
DstZip.Select('*', ZzsSet); // initial want all
FZipList.ProtectZero := True; // do not destroy DstZip
FZipList.Add(DstZip);
// add source zips to list and select their files
Result := ProcessIncludeList(SelectCount);
if Result < 0 then
raise EZipMaster.CreateMsg(Body, Result, 0, 0);
Body.ClearIncludeSpecs; // for new/updated files
if SelectCount >= 1 then
begin
// add all selected to OutZip
Result := MergeIntermediate(SelectCount, Opts);
if Result < 0 then
raise EZipMaster.CreateMsg(Body, Result, 0, 0);
// we have processed list now resolve merge conflicts
// write the results
if Result >= 0 then
Result := MergeWrite;
// Update the Zip Directory by calling List method
// for spanned exe avoid swapping to last disk
Reload := ZlrReload; // force reload
end;
if Result < 0 then
raise EZipMaster.CreateMsg(Body, Result, 0, 0);
// it was successful
SuccessCnt := IncludeSpecs.Count;
FZipList.Clear;
FSkippedFiles.Clear;
if Body.Logging then
Body.LogSpecs('');
end;
(* TZMMergeOpr.Prepare
Prepare destination and get SFX stub as needed
*)
function TZMMergeOpr.Prepare(MustExist: Boolean; SafePart: Boolean = False)
: TZMZipReader;
var
Err: Integer;
begin
Result := CurrentZip(MustExist, SafePart);
Err := PrepareZip(Result);
if Err < 0 then
raise EZipMaster.CreateMsg(Body, Err, 0, 0);
end;
// prepare to commit by appending to orig file, return false if not possible
function TZMMergeOpr.PrepareAppend: Boolean;
var
DstZip: TZMZipReader;
HighKept: Int64;
I: Integer;
LocalOfs: Int64;
LowDiscard: Int64;
OrigCnt: Integer;
Rec: TZMEntryMerger;
ShowXProgress: Boolean;
ZRec: TZMEntryBase;