Menu

[r1149]: / branches / v4-dev / Src / UFolderBackup.pas  Maximize  Restore  History

Download this file

771 lines (689 with data), 23.6 kB

  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
{
* UFolderBackup.pas
*
* Class that can back up all the files in a folder into a single file. All
* files to be backed up must be text files.
*
* $Rev$
* $Date$
*
* ***** BEGIN LICENSE BLOCK *****
*
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
*
* The Original Code is UFolderBackup.pas
*
* The Initial Developer of the Original Code is Peter Johnson
* (http://www.delphidabbler.com/).
*
* Portions created by the Initial Developer are Copyright (C) 2009-2010 Peter
* Johnson. All Rights Reserved.
*
* Contributor(s)
* NONE
*
* ***** END LICENSE BLOCK *****
}
unit UFolderBackup;
// TODO: Tidy up and re comment this unit.
interface
type
{
TFolderBackup:
Class that can back up and restore all the files in a folder to or from a
single file. All files to be backed up must be text files.
}
TFolderBackup = class(TObject)
strict private
var
fSrcFolder: string; // Folder to be backed up or restored
fBakFile: string; // Full path to backup file
fFileID: SmallInt; // Identifies the type of file
const
cWatermark = SmallInt($FFFF); // File watermark (v2 and later)
function SourceFileSpec(const FileName: string): string;
{Full path to a file in backed up folder.
@param FileName [in] Base name of file.
@return Full file spec of FileName in source folder.
}
public
constructor Create(const SrcFolder, BakFile: string;
const FileID: SmallInt);
{Class constructor. Creates backup object for specified folder and backup
file.
@param SrcFolder [in] Folder to be backed up / restored. Must contain
only text files. Sub folders are ignored.
@param BakFile [in] Name of backup file.
@param FileID [in] File type identifier.
}
procedure Backup;
{Backs up source folder into single backup file. Backup file is marked
with the file ID passed to constructor.
}
procedure Restore;
{Restores folder from backup file.
@except ECodeSnip raised if any checksum errors are found or, for v3 and
later format files, if file type id is incorrect.
}
end;
implementation
uses
// Delphi
SysUtils, Classes, Generics.Collections, IOUtils,
// DelphiDabbler library
PJMD5,
// Project
UBaseObjects, UDataStreamIO, UDOSDateTime, UEncodings, UExceptions, UUtils;
type
TBackupFileLoaderClass = class of TBackupFileLoader;
TBackupFileInfo = class(TNoConstructObject)
public
class function CurrentLoader: TBackupFileLoaderClass;
class function WatermarkBytes(const Watermark: string): TBytes;
end;
TBackupFileWriter = class(TObject)
strict private
var fFiles: TStrings;
var fStream: TStream;
var fFileID: SmallInt;
procedure WriteHeader;
procedure WriteFileInfo(const FileName: string);
public
constructor Create(const Files: TStrings; const Stream: TStream;
const FileID: SmallInt);
procedure Save;
end;
/// <summary>
/// Abstract base class for classes that load backup files. There is a
/// different sub class for each supported version of the backup file format.
/// </summary>
TBackupFileLoader = class abstract(TObject)
public
type
/// Provides information about a file to be restored from backup
TFileInfo = record
/// File name without path
Name: string;
/// File's timestamp
TimeStamp: LongInt;
/// Content of file as bytes to be written to file
Content: TBytes;
end;
/// Value used for FileID in file formats that do not support it
const NulFileID = 0;
strict private
var fFileID: SmallInt; // Value of FileID property
var fFiles: TList<TFileInfo>; // List of file info records
var fEncoding: TEncoding;
var fStream: TStream;
strict protected
/// Checks that two checksums that relate to a specified file and the same.
/// Raises an exception if checksums are different.
procedure TestChecksums(const FileName: string;
const Required, Actual: TPJMD5Digest);
/// Gets the encoding used for the backup file.
function GetFileEncoding: TEncoding; virtual; abstract;
/// Skips over watermark at start of file.
procedure SkipWatermark;
/// Reads header information from the backup file.
procedure ReadHeader(out FileID, FileCount: SmallInt); virtual; abstract;
/// Reads information about a file to be restored from the backup file.
procedure ReadFileInfo(out FileInfo: TFileInfo); virtual; abstract;
/// Reference to object used to read data from the backup file stream.
property Encoding: TEncoding read fEncoding;
public
/// Object constructor. Sets up object to get data from a given stream.
constructor Create(const Stream: TStream); virtual;
/// Object destructor. Tears down object.
destructor Destroy; override;
/// Loads the backup file from the stream storing required information in
/// the properties and file list.
procedure Load;
/// Backup file identifier.
property FileID: SmallInt read fFileID;
/// Gets enumerator for file list.
function GetEnumerator: TEnumerator<TFileInfo>;
/// Gets file's unique watermark
class function GetWatermark: TBytes; virtual; abstract;
end;
TTextBackupFileLoader = class abstract(TBackupFileLoader)
strict private
fReader: TDataStreamReader;
strict protected
property Reader: TDataStreamReader read fReader;
public
constructor Create(const Stream: TStream); override;
destructor Destroy; override;
end;
TBinaryBackupFileLoader = class abstract(TBackupFileLoader)
strict private
fReader: TBinDataStreamReader;
strict protected
property Reader: TBinDataStreamReader read fReader;
public
constructor Create(const Stream: TStream); override;
destructor Destroy; override;
end;
/// <summary>
/// Loads and provides access to data from a backup file that has the version
/// 1 file format.
/// </summary>
TV1BackupFileLoader = class(TTextBackupFileLoader)
strict protected
/// Returns the backup file's text encoding
function GetFileEncoding: TEncoding; override;
/// Reads header information from the backup file.
procedure ReadHeader(out FileID, FileCount: SmallInt); override;
/// Reads information about a file to be restored from the backup file.
/// Validates the file's content against a recorded checksum.
procedure ReadFileInfo(out FileInfo: TBackupFileLoader.TFileInfo); override;
class function GetWatermark: TBytes; override;
end;
/// <summary>
/// Loads and provides access to data from a backup file that has the version
/// 2 file format.
/// </summary>
TV2BackupFileLoader = class(TTextBackupFileLoader)
strict protected
/// Returns the backup file's text encoding
function GetFileEncoding: TEncoding; override;
/// Reads header information from the backup file.
procedure ReadHeader(out FileID, FileCount: SmallInt); override;
/// Reads information about a file to be restored from the backup file.
/// Validates the file's content against a recorded checksum.
procedure ReadFileInfo(out FileInfo: TBackupFileLoader.TFileInfo); override;
class function GetWatermark: TBytes; override;
end;
/// <summary>
/// Loads and provides access to data from a backup file that has the version
/// 3 file format.
/// </summary>
TV3BackupFileLoader = class(TTextBackupFileLoader)
strict protected
/// Returns the backup file's text encoding
function GetFileEncoding: TEncoding; override;
/// Reads header information from the backup file.
procedure ReadHeader(out FileID, FileCount: SmallInt); override;
/// Reads information about a file to be restored from the backup file.
/// Validates the file's content against a recorded checksum.
procedure ReadFileInfo(out FileInfo: TBackupFileLoader.TFileInfo); override;
class function GetWatermark: TBytes; override;
end;
TV4BackupFileLoader = class(TBinaryBackupFileLoader)
strict protected
/// Returns the backup file's text encoding
function GetFileEncoding: TEncoding; override;
/// Reads header information from the backup file.
procedure ReadHeader(out FileID, FileCount: SmallInt); override;
/// Reads information about a file to be restored from the backup file.
/// Validates the file's content against a recorded checksum.
procedure ReadFileInfo(out FileInfo: TBackupFileLoader.TFileInfo); override;
class function GetWatermark: TBytes; override;
end;
/// <summary>
/// Factory class that creates the required TBackupFileLoader object to load
/// different backup file formats.
/// </summary>
TBackupFileLoaderFactory = class sealed(TNoConstructObject)
strict private
class var fClassMap: TArray<TBackupFileLoaderClass>;
/// Gets file format version from backup file stream.
class function GetLoaderClass(const Stream: TStream):
TBackupFileLoaderClass;
public
class constructor Create;
/// Creates an instance of the correct backup file loader required to load
/// the backup file from the given stream.
class function Create(const Stream: TStream): TBackupFileLoader;
end;
/// Type of exception raised by backup file loader objects.
EBackupFileLoader = class(ECodeSnip);
{ TFolderBackup }
procedure TFolderBackup.Backup;
{Backs up source folder into single backup file. Backup file is marked with
the file ID passed to constructor.
}
var
Files: TStringList; // list of files to back up
FS: TFileStream; // stream onto backup file
FileWriter: TBackupFileWriter; // writes backup file
begin
// Get list of files in database
Files := TStringList.Create;
try
ListFiles(fSrcFolder, '*.*', Files, False);
FS := TFileStream.Create(fBakFile, fmCreate);
try
FileWriter := TBackupFileWriter.Create(Files, FS, fFileID);
try
FileWriter.Save;
finally
FileWriter.Free;
end;
finally
FS.Free;
end;
finally
Files.Free;
end;
end;
constructor TFolderBackup.Create(const SrcFolder, BakFile: string;
const FileID: SmallInt);
{Class constructor. Creates backup object for specified folder and backup
file.
@param SrcFolder [in] Folder to be backed up / restored. Must contain only
text files. Sub folders are ignored.
@param BakFile [in] Name of backup file.
@param FileID [in] File type identifier.
}
begin
inherited Create;
fSrcFolder := ExcludeTrailingPathDelimiter(SrcFolder);
fBakFile := BakFile;
fFileID := FileID;
end;
procedure TFolderBackup.Restore;
{Restores folder from backup file.
@except ECodeSnip raised if any checksum errors are found or, for v3 and
later format files, if file type id is incorrect.
}
var
BakFileStream: TStream; // stream onto backup file
BakFileLoader: TBackupFileLoader; // loads & analyses backup file
FileSpec: string; // name & path of each file to restore
DOSDateTime: IDOSDateTime; // date stamp of each file to restore
FileInfo: TBackupFileLoader.TFileInfo; // info about each file to restore
resourcestring
// Error message
sBadFileID = 'Invalid file ID for file "%s"';
begin
// Make sure restore folder exists
EnsureFolders(fSrcFolder);
// Load backup file contents
BakFileLoader := nil;
BakFileStream := TFileStream.Create(fBakFile, fmOpenRead or fmShareDenyNone);
try
BakFileLoader := TBackupFileLoaderFactory.Create(BakFileStream);
BakFileLoader.Load;
// Test for correct file ID if present (NulFileID indicates not present)
if (BakFileLoader.FileID <> TBackupFileLoader.NulFileID)
and (BakFileLoader.FileID <> fFileID) then
raise EBackupFileLoader.CreateFmt(sBadFileID, [FileSpec]);
// Restore each file
for FileInfo in BakFileLoader do
begin
FileSpec := SourceFileSpec(FileInfo.Name);
DOSDateTime := TDOSDateTimeFactory.CreateFromDOSTimeStamp(
FileInfo.TimeStamp
);
// restore file
TFile.WriteAllBytes(FileSpec, FileInfo.Content);
DOSDateTime.ApplyToFile(FileSpec);
end;
finally
BakFileLoader.Free;
BakFileStream.Free;
end;
end;
function TFolderBackup.SourceFileSpec(const FileName: string): string;
{Full path to a file in backed up folder.
@param FileName [in] Base name of file.
@return Full file spec of FileName in source folder.
}
begin
Result := IncludeTrailingPathDelimiter(fSrcFolder) + FileName;
end;
{ TBackupFileLoader }
constructor TBackupFileLoader.Create(const Stream: TStream);
begin
inherited Create;
fFiles := TList<TFileInfo>.Create;
fEncoding := GetFileEncoding;
fStream := Stream;
end;
destructor TBackupFileLoader.Destroy;
begin
TEncodingHelper.FreeEncoding(fEncoding);
fFiles.Free;
inherited;
end;
function TBackupFileLoader.GetEnumerator: TEnumerator<TFileInfo>;
begin
Result := fFiles.GetEnumerator;
end;
procedure TBackupFileLoader.Load;
resourcestring
// Error message
sReadError = 'Error reading backup file: %s';
var
FileCount: SmallInt; // number of files in backup
I: Integer; // loops through all files in backup
FI: TFileInfo; // stores information about each file
begin
try
SkipWatermark;
ReadHeader(fFileID, FileCount);
for I := 1 to FileCount do
begin
ReadFileInfo(FI);
fFiles.Add(FI);
end;
except
on E: EStreamError do
raise EBackupFileLoader.CreateFmt(sReadError, [E.Message]);
else
raise;
end;
end;
procedure TBackupFileLoader.SkipWatermark;
begin
fStream.Position := Length(GetWatermark);
end;
procedure TBackupFileLoader.TestChecksums(const FileName: string;
const Required, Actual: TPJMD5Digest);
resourcestring
// Error message
sCorruptFile = 'Backup file is corrupt. Checksum error in file %s';
begin
if Required <> Actual then
raise EBackupFileLoader.CreateFmt(sCorruptFile, [FileName]);
end;
{ TTextBackupFileLoader }
constructor TTextBackupFileLoader.Create(const Stream: TStream);
begin
inherited Create(Stream);
fReader := TDataStreamReader.Create(Stream, Encoding, []);
end;
destructor TTextBackupFileLoader.Destroy;
begin
fReader.Free;
inherited;
end;
{ TBinaryBackupFileLoader }
constructor TBinaryBackupFileLoader.Create(const Stream: TStream);
begin
inherited Create(Stream);
fReader := TBinDataStreamReader.Create(Stream, Encoding, []);
end;
destructor TBinaryBackupFileLoader.Destroy;
begin
fReader.Free;
inherited;
end;
{ TV1BackupFileLoader }
function TV1BackupFileLoader.GetFileEncoding: TEncoding;
begin
Result := TEncoding.Default;
end;
class function TV1BackupFileLoader.GetWatermark: TBytes;
begin
SetLength(Result, 0);
end;
procedure TV1BackupFileLoader.ReadFileInfo(
out FileInfo: TBackupFileLoader.TFileInfo);
var
Content: AnsiString; // content of file being restored
Checksum: TPJMD5Digest; // file checksum recorded in backup
begin
FileInfo.Name := Reader.ReadSizedString;
FileInfo.TimeStamp := Reader.ReadLongInt;
Checksum := Reader.ReadString(32);
// checksum was made of content as ANSI string so we load it as such, test
// checksum and only then convert to Unicode
Content := Reader.ReadSizedAnsiString;
TestChecksums(FileInfo.Name, Checksum, TPJMD5.Calculate(Content));
SetLength(FileInfo.Content, Length(Content));
if Length(Content) > 0 then
Move(Content[1], FileInfo.Content[0], Length(Content));
end;
procedure TV1BackupFileLoader.ReadHeader(out FileID, FileCount: SmallInt);
begin
FileID := NulFileID;
FileCount := Reader.ReadSmallInt;
end;
{ TV2BackupFileLoader }
function TV2BackupFileLoader.GetFileEncoding: TEncoding;
begin
Result := TEncoding.Default;
end;
class function TV2BackupFileLoader.GetWatermark: TBytes;
begin
Result := TBackupFileInfo.WatermarkBytes('FFFF0002');
end;
procedure TV2BackupFileLoader.ReadFileInfo(
out FileInfo: TBackupFileLoader.TFileInfo);
var
Content: AnsiString; // content of file being restored
Checksum: TPJMD5Digest; // file checksum recorded in backup
begin
FileInfo.Name := Reader.ReadSizedString;
FileInfo.TimeStamp := Reader.ReadLongInt;
Checksum := Reader.ReadString(32);
// Checksum was made of content as ANSI string so we load it as such, test
// checksum and only then convert to Unicode
Content := Reader.ReadSizedLongAnsiString;
TestChecksums(FileInfo.Name, Checksum, TPJMD5.Calculate(Content));
SetLength(FileInfo.Content, Length(Content));
if Length(Content) > 0 then
Move(Content[1], FileInfo.Content[0], Length(Content));
end;
procedure TV2BackupFileLoader.ReadHeader(out FileID, FileCount: SmallInt);
begin
FileID := NulFileID;
FileCount := Reader.ReadSmallInt;
end;
{ TV3BackupFileLoader }
function TV3BackupFileLoader.GetFileEncoding: TEncoding;
begin
// Earlier version of CodeSnip that supported file format v3 wrote the backup
// file using the system default encoding while later versions of CodeSnip
// used Windows-1252. Windows-1252 is used here for greater compatibility with
// files written by later program versions.
Result := TEncodingHelper.GetEncoding(TEncodingHelper.Windows1252CharSetName);
end;
class function TV3BackupFileLoader.GetWatermark: TBytes;
begin
Result := TBackupFileInfo.WatermarkBytes('FFFF0003');
end;
procedure TV3BackupFileLoader.ReadFileInfo(
out FileInfo: TBackupFileLoader.TFileInfo);
var
Content: Windows1252String; // content of file being restored
Checksum: TPJMD5Digest; // file checksum recorded in backup
begin
FileInfo.Name := Reader.ReadSizedString;
FileInfo.TimeStamp := Reader.ReadLongInt;
Checksum := Reader.ReadString(32);
// checksum was made of content as ANSI string so we load it as such, test
// checksum and only then convert to Unicode
Content := Reader.ReadSizedLongAnsiString;
TestChecksums(FileInfo.Name, Checksum, TPJMD5.Calculate(Content));
SetLength(FileInfo.Content, Length(Content));
if Length(Content) > 0 then
Move(Content[1], FileInfo.Content[0], Length(Content));
end;
procedure TV3BackupFileLoader.ReadHeader(out FileID, FileCount: SmallInt);
begin
FileID := Reader.ReadSmallInt;
FileCount := Reader.ReadSmallInt;
end;
{ TV4BackupFileLoader }
function TV4BackupFileLoader.GetFileEncoding: TEncoding;
begin
Result := TEncoding.UTF8;
end;
class function TV4BackupFileLoader.GetWatermark: TBytes;
begin
Result := TBackupFileInfo.WatermarkBytes('FFFF000400000000');
end;
procedure TV4BackupFileLoader.ReadFileInfo(
out FileInfo: TBackupFileLoader.TFileInfo);
var
Checksum: TPJMD5Digest;
begin
FileInfo.Name := Reader.ReadSmallSizedString;
FileInfo.TimeStamp := Reader.ReadLongInt;
CheckSum := Reader.ReadSmallSizedBytes;
FileInfo.Content := Reader.ReadLongSizedBytes;
TestCheckSums(FileInfo.Name, Checksum, TPJMD5.Calculate(FileInfo.Content));
end;
procedure TV4BackupFileLoader.ReadHeader(out FileID, FileCount: SmallInt);
begin
FileID := Reader.ReadSmallInt;
FileCount := Reader.ReadSmallInt;
end;
{ TBackupFileWriter }
constructor TBackupFileWriter.Create(const Files: TStrings;
const Stream: TStream; const FileID: SmallInt);
begin
inherited Create;
fFiles := Files;
fStream := Stream;
fFileID := FileID;
end;
procedure TBackupFileWriter.Save;
var
FileName: string;
begin
WriteHeader;
for FileName in fFiles do
WriteFileInfo(FileName);
end;
procedure TBackupFileWriter.WriteFileInfo(const FileName: string);
var
DOSDateTime: IDOSDateTime;
FileBytes: TBytes;
BinWriter: TBinDataStreamWriter;
begin
// Get content and date stamp of file
FileBytes := TFile.ReadAllBytes(FileName);
DOSDateTime := TDOSDateTimeFactory.CreateFromFile(FileName);
// Write the data
BinWriter := TBinDataStreamWriter.Create(fStream, TEncoding.UTF8, []);
try
BinWriter.WriteSmallSizedString(ExtractFileName(FileName));
BinWriter.WriteLongInt(DOSDateTime.DateStamp);
BinWriter.WriteSmallSizedBytes(TPJMD5.Calculate(FileBytes));
BinWriter.WriteLongSizedBytes(FileBytes);
finally
BinWriter.Free;
end;
end;
procedure TBackupFileWriter.WriteHeader;
var
BinWriter: TBinDataStreamWriter;
begin
BinWriter := TBinDataStreamWriter.Create(fStream, False);
try
BinWriter.WriteBytes(
TBackupFileInfo.CurrentLoader.GetWatermark
);
BinWriter.WriteSmallInt(fFileID);
BinWriter.WriteSmallInt(fFiles.Count);
finally
BinWriter.Free;
end;
end;
{ TBackupFileLoaderFactory }
class function TBackupFileLoaderFactory.Create(
const Stream: TStream): TBackupFileLoader;
resourcestring
// Error messages
sUnknownFormat = 'Unsupported backup file format';
sBadFormat = 'Backup file is not in required format';
var
LoaderCls: TBackupFileLoaderClass;
begin
try
LoaderCls := GetLoaderClass(Stream);
Stream.Position := 0;
if not Assigned(LoaderCls) then
raise EBackupFileLoader.Create(sUnknownFormat);
Result := LoaderCls.Create(Stream);
except
on E: EStreamError do
raise EBackupFileLoader.Create(sBadFormat);
else
raise;
end;
end;
class constructor TBackupFileLoaderFactory.Create;
begin
fClassMap := TArray<TBackupFileLoaderClass>.Create(
TV1BackupFileLoader, TV2BackupFileLoader,
TV3BackupFileLoader, TV4BackupFileLoader
);
end;
class function TBackupFileLoaderFactory.GetLoaderClass(
const Stream: TStream): TBackupFileLoaderClass;
function MaxWatermarkSize: Integer;
var
LoaderCls: TBackupFileLoaderClass;
Size: Integer;
begin
Result := 0;
for LoaderCls in fClassMap do
begin
Size := Length(LoaderCls.GetWatermark);
if Size > Result then
Result := Size;
end;
end;
function LoadFirstFewBytes(Count: Integer): TBytes;
begin
SetLength(Result, Count);
FillChar(Pointer(Result)^, Count, 0);
Stream.Read(Pointer(Result)^, Length(Result));
end;
function FirstBytesMatch(const Buf, Test: TBytes): Boolean;
var
I: Integer;
begin
Assert(Length(Buf) >= Length(Test), ClassName
+ '.GetLoaderClass:LoadFirstFewBytes: Buf shorter than Test');
if Length(Test) = 0 then
Exit(False);
Result := True;
for I := 0 to Pred(Length(Test)) do
begin
if Buf[I] <> Test[I] then
Exit(False);
end;
end;
var
Buffer: TBytes;
LoaderCls: TBackupFileLoaderClass;
Watermark: TBytes;
begin
Buffer := LoadFirstFewBytes(MaxWatermarkSize);
Result := TV1BackupFileLoader;
for LoaderCls in fClassMap do
begin
Watermark := LoaderCls.GetWatermark;
if FirstBytesMatch(Buffer, Watermark) then
Exit(LoaderCls);
end;
if FirstBytesMatch(
Buffer, TEncoding.ASCII.GetBytes('FFFF')
) then
Exit(nil);
end;
{ TBackupFileInfo }
class function TBackupFileInfo.CurrentLoader: TBackupFileLoaderClass;
begin
Result := TV4BackupFileLoader;
end;
class function TBackupFileInfo.WatermarkBytes(const Watermark: string):
TBytes;
begin
Result := TEncoding.ASCII.GetBytes(Watermark);
end;
end.
Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.