-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathcmirror.cpp
More file actions
3914 lines (3481 loc) · 131 KB
/
cmirror.cpp
File metadata and controls
3914 lines (3481 loc) · 131 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
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
/* ========================================================================
cmirror.cpp v1.3c
The authors of this software MAKE NO WARRANTY as to the RELIABILITY,
SUITABILITY, or USABILITY of this software. USE IT AT YOUR OWN RISK.
This is a simple source code control utility. It was initially
written by Casey Muratori but has since grown to include the fine
work of Sean Barrett and Jeff Roberts. It is in the public domain.
Anyone can use it, modify it, roll'n'smoke hardcopies of the source
code, sell it to the terrorists, etc.
But the authors make absolutely no warranty as to the reliability,
suitability, or usability of the software. It works with files -
probably files that are important to you. There might be bad bugs
in here. It could delete them all. It could format your hard drive.
We have no idea. If you lose all your files from using it, we will
point and laugh. Cmirror is not a substitute for making backups.
If you're a snappy coder and you'd like to contribute bug fixes or
feature additions, please see http://www.mollyrocket.com/tools
======================================================================== */
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <windows.h>
#include <limits.h>
#include <ctype.h>
#define STB_DEFINE
#include "stb.h"
// To try to be extra safe when people make changes, we have all the
// "low level" file delete/move/copy operations at the beginning of
// the file, wrapped in these "LowLevel" functions that do some sanity
// checking and maybe even prompt the user if it's potentially legit
// but rare. Then we scan the source and make sure all the unwrapped
// calls appear before the EOLLFO tag below. So if you write some new
// code and forget and call the unwrapped functions, hopefully it'll
// catch this and print a warning.
static bool
ShouldContinue(bool &ContinueAlways, char *Message, char *Alternatives=NULL, char *ResultChar=NULL)
{
bool Result = ContinueAlways;
if(!Result)
{
if (Message == NULL)
Message = "Continue? (y/n/a)";
printf("%s\n", Message);
bool ValidResponse = false;
do
{
char Character;
scanf("%c", &Character);
switch(Character)
{
case 'y':
{
Result = true;
ValidResponse = true;
} break;
case 'n':
{
Result = false;
ValidResponse = true;
} break;
case 'a':
{
Result = ContinueAlways = true;
ValidResponse = true;
} break;
default:
{
if (Alternatives) {
char *s = stb_strichr(Alternatives, Character);
if (s) {
*ResultChar = *s;
Result = false;
ValidResponse = true;
}
}
}
}
} while(!ValidResponse);
}
return(Result);
}
static BOOL DeleteFileLowLevel(char *File)
{
BOOL Result = DeleteFile(File);
// If deletion fails, try to move the offending file to the
// Windows temp directory so it will be out of the repository
// and hopefully cleaned up by Windows sometime in the future
// when it is no longer in use.
if(!Result)
{
char TempPath[MAX_PATH];
char TempFile[MAX_PATH];
GetTempPath(sizeof(TempPath), TempPath);
if(GetTempFileName(TempPath, "cm", 0, TempFile))
{
// TODO: DeleteFile is required here because Windows actually
// creates the file, and so the move would fail.
DeleteFile(TempFile);
printf("\nUnable to delete \"%s\", attempting rename to \"%s\".\n",
File, TempFile);
Result = MoveFile(File, TempFile);
}
}
return Result;
}
static bool CopyFileAlways;
static bool DeleteFileAlways;
//#if !defined CopyFileEx
#define COPY_FILE_FAIL_IF_EXISTS 0x00000001
#define COPY_FILE_RESTARTABLE 0x00000002
#define COPY_FILE_OPEN_SOURCE_FOR_WRITE 0x00000004
#define COPY_FILE_ALLOW_DECRYPTED_DESTINATION 0x00000008
typedef
DWORD
(WINAPI *LPPROGRESS_ROUTINE)(LARGE_INTEGER TotalFileSize,
LARGE_INTEGER TotalBytesTransferred,
LARGE_INTEGER StreamSize,
LARGE_INTEGER StreamBytesTransferred,
DWORD dwStreamNumber,
DWORD dwCallbackReason,
HANDLE hSourceFile,
HANDLE hDestinationFile,
LPVOID lpData
);
typedef BOOL WINAPI copy_file_ex_a(LPCSTR lpExistingFileName,
LPCSTR lpNewFileName,
LPPROGRESS_ROUTINE lpProgressRoutine,
LPVOID lpData,
LPBOOL pbCancel,
DWORD dwCopyFlags);
//#endif
static BOOL
Win32CopyFile(char *ExistingName, char *NewName, bool FailIfExists)
{
BOOL Result = FALSE;
static copy_file_ex_a *CopyFileExPtr;
static bool InitializationAttempted;
if(!InitializationAttempted)
{
HINSTANCE Kernel32 = LoadLibrary("kernel32.dll");
if(Kernel32)
{
CopyFileExPtr = (copy_file_ex_a *)GetProcAddress(Kernel32, "CopyFileExA");
}
InitializationAttempted = true;
}
if(CopyFileExPtr)
{
Result = CopyFileExPtr(ExistingName, NewName, 0, 0, 0, COPY_FILE_ALLOW_DECRYPTED_DESTINATION | (FailIfExists ? COPY_FILE_FAIL_IF_EXISTS : 0));
}
else
{
Result = CopyFile(ExistingName, NewName, FailIfExists ? TRUE : FALSE);
}
return(Result);
}
BOOL CopyFileWrapped(char *Workspace, char *ExistingName, char *NewName, bool FailIfExists)
{
if (FailIfExists)
{
BOOL res = Win32CopyFile(ExistingName, NewName, FailIfExists);
if (!res) {
int err = GetLastError();
}
return res;
} else {
if (!stb_prefixi(NewName, Workspace))
{
printf(" Internal error! Attempted to copy '%s' over '%s' with overwrite allowed,\n"
"but the target filename was not in the workspace.\n", ExistingName, NewName);
exit(1);
}
#if 0
if (stb_fexists(NewName))
{
if (!CopyFileAlways)
printf("About to copy '%s' over existing '%s'.\n", ExistingName, NewName);
bool OkToProceed = ShouldContinue(CopyFileAlways, "Continue? (y/n/a, choose 'a' to allow all copy-overwrites)");
if (!OkToProceed)
return FALSE;
}
#endif
return Win32CopyFile(ExistingName, NewName, FailIfExists);
}
}
BOOL DeleteFileWrapped(char *Workspace, char *Local, char *Central,
char *File)
{
if (stb_prefixi(File, Local) || stb_prefixi(File, Central))
{
// PARANOIA:
// make sure there's a cmirror version number in the filename
if (!strstr(File, ",cm")) {
printf("Internal error! Attempted to delete '%s', which is in the %s repository, but it\n"
"does not have a cmirror version number, so we have no business deleting it!\n",
File, stb_prefixi(File,Local) ? "local" : "central");
exit(1);
}
// ok, go ahead and delete it
return DeleteFileLowLevel(File);
}
else if (stb_prefixi(File, Workspace))
{
#if 0
if (!DeleteFileAlways)
printf("About to delete file '%s'.\n", File);
bool OkToProceed = ShouldContinue(DeleteFileAlways, "Continue? (y/n/a, choose 'a' to allow all workspace deletes)");
if (!OkToProceed)
return FALSE;
#endif
return DeleteFileLowLevel(File);
}
else
{
printf("Internal error! Attempted to delete '%s', which does not come from any\n"
"directory that cmirror is supposed to be manipulating.\n", File);
exit(1);
}
}
// EOLLFO: end of low-level file operations (this marker is for source-checking tools; do not delete it)
enum file_type
{
NullFileType,
WorkspaceFileType,
LocalFileType,
CentralFileType,
OnePastLastFileType
};
char *FileTypeText[] =
{
"NullFileType",
"WorkspaceFileType",
"LocalFileType",
"CentralFileType",
};
struct file_version
{
int VersionNumber;
bool Deleted;
unsigned int dwHighDateTime;
unsigned int dwLowDateTime;
bool OldStyle;
file_version stb_bst_fields_parent(fv);
};
stb_bst_parent(file_version, // node name
fv, // same name as field above; also name prefix for functions that take nodes
file_versions, // name of (optional) 'tree' data type that holds the root
Version, // function name prefix for functions that take the tree type
VersionNumber, // name of field to compare
int, // type of that field
a - b) // comparison function for that field
struct file_record
{
bool Present;
bool Deleted;
int MinVersion;
int MaxVersion;
file_versions Versions;
};
struct directory_entry
{
char *Name;
file_record File[OnePastLastFileType];
directory_entry stb_bst_fields_parent(dire);
};
stb_bst_parent(directory_entry, dire, directory_contents, Dir, Name, char *, stricmp(a,b))
enum conflict_behavior
{
HaltOnConflicts = 0,
IgnoreConflicts,
};
enum ignore_behavior
{
NoIgnoreEffect,
DoIgnore,
DoNotIgnore
};
struct file_rule
{
// NOTE: When you add something to this structure, please make sure
// to fill in a default value in the UpdateRuleFor function immediately
// following.
char *WildCard;
int WildCardLength; // for reverse scanning
conflict_behavior Behavior;
// When Ignore is set to true, files matching the wildcard behave
// literally as if they did not exist. They will not be sync'd,
// versioned, or copied by cmirror.
ignore_behavior Ignore;
// When CapVersionCount is set to true, files matching the wildcard
// will have their last MaxVersionCount versions stored instead of
// an unbounded number of versions. If the file is deleted from
// the repository, on the next sync, cmirror will delete all versions
// stored that are later than MaxVersionCountIfDeleted.
bool CapVersionCount;
int MaxVersionCount;
int MaxVersionCountIfDeleted;
// When PreCheckinCommand is non-zero, it is treated as an
// executable name that will be run with the workspace file and
// version information as arguments when cmirror detects that it
// has changed from the repository version (this is designed to
// faciliate keyword substitution and such)
char *PreCheckinCommand;
char *PreCheckinCommandParameters;
};
typedef file_rule* file_rule_list;
static file_rule *
UpdateRuleFor(file_rule_list *FileRuleList, char *Wildcard)
{
// NOTE: These used to be kept sorted, but now they are left
// as a linked list to facilitate processing them in the order
// in which they appeared.
// file_rule *Rule = Find(FileRuleList, Wildcard);
file_rule *Rule = stb_arr_add(*FileRuleList);
Rule->WildCard = Wildcard;
Rule->WildCardLength = strlen(Wildcard);
Rule->Behavior = HaltOnConflicts;
Rule->Ignore = NoIgnoreEffect;
Rule->CapVersionCount = false;
Rule->MaxVersionCount = INT_MAX;
Rule->MaxVersionCountIfDeleted = INT_MAX;
Rule->PreCheckinCommand = 0;
Rule->PreCheckinCommandParameters = 0;
return(Rule);
}
enum mirror_mode
{
FullSyncMode,
LocalSyncMode,
SidewaysSyncMode,
CheckpointMode,
};
enum diff_method
{
ByteByByteDiff,
ModificationStampDiff,
TimestampRepresentationTolerantStampDiff,
TRTSWithByteFallbackDiff,
};
struct mirror_config
{
file_rule_list FileRuleList;
mirror_mode MirrorMode;
diff_method DiffMethod[OnePastLastFileType][OnePastLastFileType];
char *CopyCommand;
char *DeleteCommand;
bool WritableWorkspace;
bool ContinueAlways;
bool SyncWorkspace;
bool SyncCentral;
char *CentralCache;
bool SuppressIgnores;
bool SummarizeIgnores;
int SyncPrintThreshold;
int LineLength;
bool PrintReason;
bool SummarizeSync;
bool SummarizeSyncIfNotPrinted;
bool SummarizeDirs;
bool SummarizeDirsIfNotPrinted;
int RetryTimes[OnePastLastFileType];
char *Directory[OnePastLastFileType];
};
struct string_table
{
char *StoreCurrent;
char *StoreBase;
};
//
// --- === ---
//
static void
InitializeStringTable(string_table &Table)
{
Table.StoreCurrent = Table.StoreBase = (char *)malloc(1 << 24);
}
static char *
PushTableState(string_table &Table)
{
return(Table.StoreCurrent);
}
static void
PopTableState(string_table &Table, char *Mark)
{
Table.StoreCurrent = Mark;
}
static void
Cat(string_table &Table, char *String)
{
while(*String) {*Table.StoreCurrent++ = *String++;}
}
static void
CatSlash(string_table &Table, char *String)
{
while(*String)
{
if(*String == '\\')
{
*Table.StoreCurrent++ = '/';
}
else
{
*Table.StoreCurrent++ = *String++;
}
}
}
static void
Cat(string_table &Table, char Character)
{
*Table.StoreCurrent++ = Character;
}
static char *
StoreDirectoryFile(string_table &Table, char *Directory, char *File)
{
char *Result = Table.StoreCurrent;
if(Directory && *Directory)
{
CatSlash(Table, Directory);
Cat(Table, '/');
}
CatSlash(Table, File);
Cat(Table, '\0');
return(Result);
}
static void
Unixify(char *String)
{
stb_fixpath(String);
}
static void
FreeStringTable(string_table &Table)
{
free(Table.StoreBase);
Table.StoreBase = 0;
Table.StoreCurrent = 0;
}
static char *
FindLastChar(char *String, int ch)
{
return strrchr(String,ch);
}
static char *
FindLastSlash(char *Path)
{
char *p = stb_strrchr2((char *) Path, '/', '\\');
return p ? p : Path;
}
static void
AddFileVersion(file_record &Record, int VersionIndex, unsigned int dwLowDateTime, unsigned int dwHighDateTime, bool Deleted, bool OldStyle)
{
Record.Present = true;
if(VersionIndex != -1)
{
if((Record.MinVersion == -1) || (Record.MinVersion > VersionIndex))
{
Record.MinVersion = VersionIndex;
}
if((Record.MaxVersion == -1) || (Record.MaxVersion < VersionIndex))
{
Record.Deleted = Deleted;
Record.MaxVersion = VersionIndex;
}
}
file_version *Version = (file_version *) malloc(sizeof(*Version));
if(!Version)
{
fprintf(stderr, "Fatal error we're toast\n");
return;
}
Version->VersionNumber = VersionIndex;
Version->dwLowDateTime = dwLowDateTime;
Version->dwHighDateTime = dwHighDateTime;
Version->Deleted = Deleted;
Version->OldStyle = OldStyle;
VersionInsert(&Record.Versions, Version);
}
static void
RemoveFileVersion(file_record &Record, int VersionIndex)
{
file_versions *VersionList = &Record.Versions;
file_version *Version = VersionFind(VersionList, VersionIndex);
if (!Version)
{
fprintf(stderr, "Tried to remove a version that wasn't present.\n");
return;
}
VersionRemove(VersionList, Version);
if (VersionFind(VersionList, VersionIndex))
fprintf(stderr, "Internal error: attempt to remove version failed -- problem with stb_bst\n");
}
static bool
Win32FindFile(char *FileName, WIN32_FIND_DATA &Data)
{
HANDLE Handle = FindFirstFile(FileName, &Data);
if(Handle != INVALID_HANDLE_VALUE)
{
FindClose(Handle);
return(true);
}
return(false);
}
static bool
WildCardMatch(char* name, char* wild)
{
return stb_wildmatchi(wild, name) != 0;
}
static bool
Accept(file_rule_list &IgnoreList, char *Name)
{
int NameLen = strlen(Name);
bool result = true;
{for(file_rule *Ignore = IgnoreList;
!stb_arr_end(IgnoreList,Ignore);
++Ignore)
{
if (Ignore->Ignore == NoIgnoreEffect)
continue;
// could put this in WildCardMatch, but the recursion there screws us up
if (Ignore->WildCard[0] == '*') {
// check the ending
char *WildEnd = Ignore->WildCard + Ignore->WildCardLength;
char *NameEnd = Name + NameLen;
// scan backwards until we exhaust name characters or
// until we hit a '*' in the pattern
for (int i=0; i < NameLen; ++i) {
--NameEnd, --WildEnd;
if (*WildEnd == '*') break;
if (*WildEnd == '?') continue;
if (tolower(*WildEnd) != tolower(*NameEnd))
goto no_effect; // 'continue' at next level of nesting
}
}
switch(Ignore->Ignore) {
case DoIgnore:
if(WildCardMatch(Name, Ignore->WildCard)) {
result = false;
}
break;
case DoNotIgnore:
if(WildCardMatch(Name, Ignore->WildCard)) {
result = true;
}
break;
}
no_effect:
;
}}
return result;
}
static bool
GetFileVersionCap(mirror_config &Config, directory_entry *Entry, int &MaxVersionCount)
{
bool Result = false;
MaxVersionCount = 1 << 24;
if(Entry)
{
// This always returns the LAST version cap it finds, because that
// way the user can control which wildcard takes precendence by
// intelligently ordering them in the file.
{for(file_rule *Cap = Config.FileRuleList;
!stb_arr_end(Config.FileRuleList,Cap);
++Cap)
{
if(WildCardMatch(Entry->Name, Cap->WildCard) &&
Cap->CapVersionCount)
{
if(Entry->File[CentralFileType].Deleted)
{
MaxVersionCount = Cap->MaxVersionCountIfDeleted;
}
else
{
MaxVersionCount = Cap->MaxVersionCount;
}
Result = true;
}
}}
}
return(Result);
}
static conflict_behavior
GetConflictBehaviorFor(mirror_config &Config, directory_entry *Entry)
{
conflict_behavior Result = HaltOnConflicts;
if(Entry)
{
// This always returns the LAST conflict behavior it finds, because that
// way the user can control which wildcard takes precendence by
// intelligently ordering them in the file.
{for(file_rule *Behavior = Config.FileRuleList;
!stb_arr_end(Config.FileRuleList, Behavior);
++Behavior)
{
if(WildCardMatch(Entry->Name, Behavior->WildCard))
{
Result = Behavior->Behavior;
}
}}
}
return(Result);
}
static char SearchString[3 * MAX_PATH];
bool
ProcessFilename(string_table &Strings, directory_contents &Contents,
file_rule_list &IgnoreList,
file_type FileType, char *Name, FILETIME ftLastWriteTime,
bool SuppressIgnores, int &IgnoredFileCount)
{
bool Result = false;
bool OldStyle = false;
bool Deleted = false;
int Version = -1;
if(FileType != WorkspaceFileType)
{
char *LastComma = FindLastChar(Name, ',');
if(LastComma)
{
char *CommaLoc = LastComma;
// check for new-style internal comma
if (LastComma[1] == 'c' && LastComma[2] == 'm') {
char *Dot = strchr(LastComma, '.');
LastComma += 3;
if (Dot) {
// double-check that it's the last dot
if (strchr(Dot+1, '.')) {
// ok, somehow we ended up with a file of the form:
// "somefile,cm00001.foo.bar"
// even though we only insert ",cm000001" before the _last_ dot!
// so this code path is for future expansion, and for now is an error
// what do we do on error? casey just lets it through with version -1
// so do nothing
} else {
if ( LastComma[ 0 ] == 'd' ) {
Deleted = true;
++LastComma;
}
*Dot = '\0';
Version = atoi(LastComma);
*Dot = '.';
// splice the extension over the ",cm0000" part
strcpy(CommaLoc, Dot);
}
} else {
// no dot!
*CommaLoc = '\0';
if ( LastComma[ 0 ] == 'd') {
Deleted = true;
++LastComma;
}
Version = atoi(LastComma);
}
} else {
OldStyle = true;
*LastComma = '\0';
++LastComma;
if ( ( LastComma[ 0 ] == 'd' ) )
{
Deleted = true;
++LastComma;
}
Version = atoi(LastComma);
}
}
}
assert(Name[0]);
if(Accept(IgnoreList, Name))
{
directory_entry *Entry = DirFind(&Contents, Name);
if(!Entry)
{
Entry = (directory_entry *) malloc(sizeof(*Entry));
if(!Entry)
{
fprintf(stderr, "Fatal error we're toast\n");
return(false);
}
Entry->Name = Name;
DirInsert(&Contents, Entry);
{for(int FileIndex = 0;
FileIndex < OnePastLastFileType;
++FileIndex)
{
file_record &Record = Entry->File[FileIndex];
Record.Present = false;
Record.Deleted = false;
Record.MinVersion = -1;
Record.MaxVersion = -1;
VersionInit(&Record.Versions);
}}
}
assert(stricmp(Entry->Name, Name) == 0);
file_record &Record = Entry->File[FileType];
AddFileVersion(Record, Version,
ftLastWriteTime.dwLowDateTime,
ftLastWriteTime.dwHighDateTime, Deleted, OldStyle);
Result = true;
}
else
{
++IgnoredFileCount;
if (!SuppressIgnores)
{
printf("\n (ignored: %s)\n", Name);
}
}
return(Result);
}
void
BuildDirectoryRecursive(string_table &Strings, directory_contents &Contents,
file_rule_list &IgnoreList,
file_type FileType, char *Base, char *Directory,
char *Description, int &EntryIndex,
bool SuppressIgnores, int &IgnoredFiles, int &IgnoredDirectories)
{
if(Directory)
{
sprintf(SearchString, "%s/%s/*", Base, Directory);
}
else
{
sprintf(SearchString, "%s/*", Base);
}
WIN32_FIND_DATA FindData;
HANDLE SearchHandle = FindFirstFile(SearchString, &FindData);
if(SearchHandle != INVALID_HANDLE_VALUE)
{
do
{
if(stricmp(FindData.cFileName, ".") && stricmp(FindData.cFileName, ".."))
{
bool IsDirectory = ((FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
// TODO: This potentially stores the string multiple times
char *Name = StoreDirectoryFile(Strings, Directory, FindData.cFileName);
if(IsDirectory)
{
if(Accept(IgnoreList, Name))
{
BuildDirectoryRecursive(Strings, Contents, IgnoreList,
FileType, Base, Name,
Description, EntryIndex,
SuppressIgnores, IgnoredFiles, IgnoredDirectories);
} else {
++IgnoredDirectories;
if (!SuppressIgnores)
{
printf("\n (ignored: %s)\n", Name);
}
}
}
else
{
if(ProcessFilename(Strings, Contents, IgnoreList,
FileType, Name, FindData.ftLastWriteTime,
SuppressIgnores, IgnoredFiles))
{
++EntryIndex;
if ( ( EntryIndex & 127 ) == 0 )
{
printf("\r %s: %d ", Description, EntryIndex);
}
}
}
}
} while(FindNextFile(SearchHandle, &FindData));
FindClose(SearchHandle);
}
}
bool
AcceptDirectories(file_rule_list &IgnoreList, char *filename)
{
char path[MAX_PATH * 3], *s;
strcpy(path, filename);
s = path + strlen(path) - 1;
while (s >= path) {
if (*s == '/' || *s == '\\') {
*s = 0;
if (!Accept(IgnoreList, path))
return false;
}
--s;
}
return true;
}
int unsigned
ReadUnsigned(char *From)
{
int unsigned Number = 0;
while((*From >= '0') && (*From <= '9'))
{
Number *= 10;
Number += (*From - '0');
++From;
}
return(Number);
}
bool
BuildDirectoryFromCache(string_table &Strings, directory_contents &Contents,
file_rule_list &IgnoreList,
file_type FileType, char *CacheFileName,
char *Description, int &EntryIndex,
bool &SuppressIgnores, int &IgnoredFiles, int &IgnoredDirectories)
{
bool Result = false, Compressed = true;
unsigned int FileSize;
size_t FileSize_t;
char *CacheBuffer;
if (!CacheFileName[0]) {
return Result;
}
// try a compressed file
CacheBuffer = stb_decompress_fromfile(CacheFileName, &FileSize);
if (!CacheBuffer) {
// try uncompressed
CacheBuffer = stb_filec(CacheFileName, &FileSize_t);
Compressed = false;
}
if (CacheBuffer)
{
// drawback to stb_file is this doesn't get printed until AFTER we read it!
printf("Using%s directory cache (%dkb)...\n", Compressed ? " compressed": "", FileSize / 1024);
Result = true;
char *Parse = CacheBuffer;
while(*Parse)
{
FILETIME ftLastWriteTime;
ftLastWriteTime.dwHighDateTime = ReadUnsigned(Parse);
while(*Parse && (*Parse != ' ')) {++Parse;}
while(*Parse == ' ') {++Parse;}
ftLastWriteTime.dwLowDateTime = ReadUnsigned(Parse);
while(*Parse && (*Parse != ' ')) {++Parse;}
while(*Parse == ' ') {++Parse;}
char *ParsedName = Parse;
while(*Parse && (*Parse != '\n' && *Parse != '\r')) {++Parse;}
if(*Parse)
{
*Parse = '\0';
++Parse;
while((*Parse == '\n') ||
(*Parse == '\r')) {++Parse;}
}
char *Name = StoreDirectoryFile(Strings, 0, ParsedName);
if(AcceptDirectories(IgnoreList, Name))
{
if(ProcessFilename(Strings, Contents, IgnoreList,
FileType, Name, ftLastWriteTime,
SuppressIgnores, IgnoredFiles))
{
++EntryIndex;
if ( ( EntryIndex & 127 ) == 0 )
{
printf("\r %s: %d ", Description, EntryIndex);
}
}
} else {
++IgnoredDirectories;
if (!SuppressIgnores)
{
printf("\n (ignored: %s)\n", Name);
}
}
}
free(CacheBuffer);
}
return(Result);
}
static char BufferA[4096];
static char BufferB[4096];
static void
GetVersionFileNameRelative(char *Directory, directory_entry *Entry, file_type FileType,
int VersionIndex, bool Deleted, bool OldStyle, char *Buffer)
{