-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDuplicateCleaner.cpp
More file actions
809 lines (729 loc) · 33.1 KB
/
Copy pathDuplicateCleaner.cpp
File metadata and controls
809 lines (729 loc) · 33.1 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
// DuplicateCleaner.cpp
// ---------------------------------------------------------------------------
// A single-file, pure Win32 / C++ GUI that compares two folders recursively
// and reports differences as CSV files.
//
// Milestone 1 (this file):
// * Pick two folders (classic SHBrowseForFolder dialog -- works on Win XP+).
// * "Compare & Generate CSV" walks both trees and writes three CSVs:
// 1. diff_same_name.csv -> same relative path in BOTH, contents differ.
// 2. only_in_folder1.csv -> present in folder 1, missing from folder 2.
// 3. only_in_folder2.csv -> present in folder 2, missing from folder 1.
// * "Merge to Folder 1" / "Merge to Folder 2" are STUBS for now -- the merge
// logic is intentionally not implemented yet (to be designed together).
//
// Backward compatibility: targets the Windows XP API surface (_WIN32_WINNT
// 0x0501). No Vista+ APIs (e.g. IFileOpenDialog) are used. The PE subsystem
// version is set to 5.01 (x86) / 5.02 (x64) via a linker pragma so the binary
// will load on XP. (Caveat: the VS2022 UCRT is not officially XP-supported; a
// true XP run may require the v141_xp platform toolset.)
//
// Build (from the matching x86 or x64 Native Tools Command Prompt):
// cl /nologo /W4 /EHsc /O2 /DUNICODE /D_UNICODE DuplicateCleaner.cpp ^
// /Fe:DuplicateCleaner.exe /link /SUBSYSTEM:WINDOWS
// ---------------------------------------------------------------------------
#ifndef WINVER
#define WINVER 0x0501
#endif
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0501
#endif
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <windows.h>
#include <windowsx.h>
#include <shlobj.h> // SHBrowseForFolder
#include <commctrl.h> // InitCommonControlsEx (visual styles)
#include <string>
#include <vector>
#include <algorithm>
#include <set>
#include <map>
#include <cwctype>
#pragma comment(lib, "user32.lib")
#pragma comment(lib, "gdi32.lib")
#pragma comment(lib, "shell32.lib")
#pragma comment(lib, "ole32.lib")
#pragma comment(lib, "comctl32.lib")
// Pin the PE subsystem version so the binary loads on Windows XP.
#ifdef _WIN64
#pragma comment(linker, "/SUBSYSTEM:WINDOWS,5.02")
#else
#pragma comment(linker, "/SUBSYSTEM:WINDOWS,5.01")
#endif
// Enable the v6 common controls (themed look) where available (XP+).
#pragma comment(linker, "/manifestdependency:\"type='win32' " \
"name='Microsoft.Windows.Common-Controls' version='6.0.0.0' " \
"processorArchitecture='*' publicKeyToken='6595b64144ccf1df' " \
"language='*'\"")
// ----------------------------- Control IDs ---------------------------------
#define IDC_LABEL1 1001
#define IDC_LABEL2 1002
#define IDC_BTN_SEL1 1003
#define IDC_BTN_SEL2 1004
#define IDC_BTN_COMPARE 1005
#define IDC_STATUS 1006
#define IDC_BTN_MERGE1 1007
#define IDC_BTN_MERGE2 1008
#define IDC_HDR1 1009
#define IDC_HDR2 1010
// ----------------------------- Globals -------------------------------------
static std::wstring g_folder1;
static std::wstring g_folder2;
static HFONT g_font = NULL;
static HWND g_hLabel1, g_hLabel2, g_hStatus;
// ----------------------------- Helpers -------------------------------------
// One file found during a recursive walk: path relative to the root, + size.
struct FileEntry {
std::wstring rel; // e.g. L"sub\\dir\\file.txt"
LONGLONG size;
};
// Convert a wide string to UTF-8 bytes.
static std::string ToUtf8(const std::wstring& w) {
if (w.empty()) return std::string();
int n = WideCharToMultiByte(CP_UTF8, 0, w.c_str(), (int)w.size(),
NULL, 0, NULL, NULL);
std::string s((size_t)n, '\0');
WideCharToMultiByte(CP_UTF8, 0, w.c_str(), (int)w.size(),
&s[0], n, NULL, NULL);
return s;
}
// Case-insensitive comparator (Windows file systems are case-insensitive).
static bool RelLess(const FileEntry& a, const FileEntry& b) {
return _wcsicmp(a.rel.c_str(), b.rel.c_str()) < 0;
}
// Recursively list every file under `root`. `rel` is the current sub-path
// relative to root (empty at the top level).
static void WalkDir(const std::wstring& root, const std::wstring& rel,
std::vector<FileEntry>& out) {
std::wstring dir = root;
if (!rel.empty()) dir += L"\\" + rel;
std::wstring pattern = dir + L"\\*";
WIN32_FIND_DATAW fd;
HANDLE h = FindFirstFileW(pattern.c_str(), &fd);
if (h == INVALID_HANDLE_VALUE) return;
do {
if (wcscmp(fd.cFileName, L".") == 0 || wcscmp(fd.cFileName, L"..") == 0)
continue;
std::wstring childRel = rel.empty() ? std::wstring(fd.cFileName)
: rel + L"\\" + fd.cFileName;
if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
// Do not follow junctions/symlinks: avoids loops and runaway copies.
if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT))
WalkDir(root, childRel, out);
} else {
FileEntry e;
e.rel = childRel;
e.size = ((LONGLONG)fd.nFileSizeHigh << 32) | fd.nFileSizeLow;
out.push_back(e);
}
} while (FindNextFileW(h, &fd));
FindClose(h);
}
// Compare two files byte-for-byte.
// Returns: 0 = identical, 1 = differ, -1 = error opening/reading.
static int FilesDiffer(const std::wstring& p1, const std::wstring& p2,
LONGLONG size1, LONGLONG size2) {
if (size1 != size2) return 1; // different size => definitely differ
HANDLE h1 = CreateFileW(p1.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL,
OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL);
HANDLE h2 = CreateFileW(p2.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL,
OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL);
if (h1 == INVALID_HANDLE_VALUE || h2 == INVALID_HANDLE_VALUE) {
if (h1 != INVALID_HANDLE_VALUE) CloseHandle(h1);
if (h2 != INVALID_HANDLE_VALUE) CloseHandle(h2);
return -1;
}
const DWORD CHUNK = 64 * 1024;
std::vector<char> b1(CHUNK), b2(CHUNK);
int result = 0;
for (;;) {
DWORD r1 = 0, r2 = 0;
BOOL ok1 = ReadFile(h1, &b1[0], CHUNK, &r1, NULL);
BOOL ok2 = ReadFile(h2, &b2[0], CHUNK, &r2, NULL);
if (!ok1 || !ok2) { result = -1; break; }
if (r1 != r2) { result = 1; break; } // shouldn't happen (sizes equal)
if (r1 == 0) { result = 0; break; } // both hit EOF together
if (memcmp(&b1[0], &b2[0], r1) != 0) { result = 1; break; }
}
CloseHandle(h1);
CloseHandle(h2);
return result;
}
// Append one CSV field (UTF-8) to `out`, quoting/escaping per RFC 4180.
static void CsvField(std::string& out, const std::wstring& w) {
std::string s = ToUtf8(w);
bool quote = s.find_first_of(",\"\r\n") != std::string::npos;
if (!quote) { out += s; return; }
out += '"';
for (size_t i = 0; i < s.size(); ++i) {
if (s[i] == '"') out += '"'; // double up embedded quotes
out += s[i];
}
out += '"';
}
// Write a CSV file (UTF-8 with BOM so Excel reads Unicode correctly).
// Returns true on success.
static bool WriteCsv(const std::wstring& path, const std::string& content) {
HANDLE h = CreateFileW(path.c_str(), GENERIC_WRITE, 0, NULL,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (h == INVALID_HANDLE_VALUE) return false;
const unsigned char bom[3] = { 0xEF, 0xBB, 0xBF };
DWORD written = 0;
BOOL ok = WriteFile(h, bom, 3, &written, NULL);
if (ok && !content.empty())
ok = WriteFile(h, content.data(), (DWORD)content.size(), &written, NULL);
CloseHandle(h);
return ok != FALSE;
}
// Classic folder picker (XP-compatible). Returns selected path, or empty.
static std::wstring BrowseForFolder(HWND owner, const wchar_t* title) {
BROWSEINFOW bi;
ZeroMemory(&bi, sizeof(bi));
bi.hwndOwner = owner;
bi.lpszTitle = title;
bi.ulFlags = BIF_RETURNONLYFSDIRS | BIF_NEWDIALOGSTYLE;
std::wstring result;
LPITEMIDLIST pidl = SHBrowseForFolderW(&bi);
if (pidl) {
wchar_t buf[MAX_PATH];
if (SHGetPathFromIDListW(pidl, buf))
result = buf;
CoTaskMemFree(pidl);
}
return result;
}
// ----------------------------- Compare driver ------------------------------
// Run the comparison and write the three CSVs. Fills `summary` with a report.
static void RunCompare(std::wstring& summary) {
std::vector<FileEntry> list1, list2;
WalkDir(g_folder1, L"", list1);
WalkDir(g_folder2, L"", list2);
std::sort(list1.begin(), list1.end(), RelLess);
std::sort(list2.begin(), list2.end(), RelLess);
std::string csvDiff = "Relative Path,Folder1 Size,Folder2 Size\r\n";
std::string csvOnly1 = "Relative Path,Size\r\n";
std::string csvOnly2 = "Relative Path,Size\r\n";
size_t nDiff = 0, nOnly1 = 0, nOnly2 = 0, nSame = 0, nErr = 0;
// Merge-join the two sorted lists.
size_t i = 0, j = 0;
while (i < list1.size() && j < list2.size()) {
int c = _wcsicmp(list1[i].rel.c_str(), list2[j].rel.c_str());
if (c == 0) {
// Present in both -> compare contents.
std::wstring p1 = g_folder1 + L"\\" + list1[i].rel;
std::wstring p2 = g_folder2 + L"\\" + list2[j].rel;
int d = FilesDiffer(p1, p2, list1[i].size, list2[j].size);
if (d != 0) {
CsvField(csvDiff, list1[i].rel);
csvDiff += ",";
csvDiff += std::to_string(list1[i].size);
csvDiff += ",";
csvDiff += std::to_string(list2[j].size);
csvDiff += "\r\n";
++nDiff;
if (d < 0) ++nErr;
} else {
++nSame;
}
++i; ++j;
} else if (c < 0) {
// Only in folder 1.
CsvField(csvOnly1, list1[i].rel);
csvOnly1 += ",";
csvOnly1 += std::to_string(list1[i].size);
csvOnly1 += "\r\n";
++nOnly1; ++i;
} else {
// Only in folder 2.
CsvField(csvOnly2, list2[j].rel);
csvOnly2 += ",";
csvOnly2 += std::to_string(list2[j].size);
csvOnly2 += "\r\n";
++nOnly2; ++j;
}
}
for (; i < list1.size(); ++i) {
CsvField(csvOnly1, list1[i].rel);
csvOnly1 += ",";
csvOnly1 += std::to_string(list1[i].size);
csvOnly1 += "\r\n";
++nOnly1;
}
for (; j < list2.size(); ++j) {
CsvField(csvOnly2, list2[j].rel);
csvOnly2 += ",";
csvOnly2 += std::to_string(list2[j].size);
csvOnly2 += "\r\n";
++nOnly2;
}
// Write the CSVs next to the working directory.
wchar_t cwd[MAX_PATH];
GetCurrentDirectoryW(MAX_PATH, cwd);
std::wstring base = cwd;
std::wstring pDiff = base + L"\\diff_same_name.csv";
std::wstring pOnly1 = base + L"\\only_in_folder1.csv";
std::wstring pOnly2 = base + L"\\only_in_folder2.csv";
bool ok = true;
ok &= WriteCsv(pDiff, csvDiff);
ok &= WriteCsv(pOnly1, csvOnly1);
ok &= WriteCsv(pOnly2, csvOnly2);
wchar_t buf[2048];
wsprintfW(buf,
L"Done.\r\n"
L"Files in folder 1: %u Files in folder 2: %u\r\n"
L"Same name, identical: %u\r\n"
L"Same name, DIFFERENT: %u (read errors: %u)\r\n"
L"Only in folder 1 (missing from 2): %u\r\n"
L"Only in folder 2 (missing from 1): %u\r\n"
L"%s\r\n"
L"CSVs written to: %s",
(unsigned)list1.size(), (unsigned)list2.size(),
(unsigned)nSame, (unsigned)nDiff, (unsigned)nErr,
(unsigned)nOnly1, (unsigned)nOnly2,
ok ? L"" : L"WARNING: one or more CSV files could not be written!",
base.c_str());
summary = buf;
}
// ============================ Merge =========================================
//
// "Merge to Folder 1" pulls folder 2 (source) into folder 1 (destination):
// * identical file (same rel path + content) -> delete the source copy
// (destination already has it; this is the storage-reduction case).
// * different file (same rel path, diff content) -> move source in, renamed
// "stem_LastMod_<YYYYMMDDhhmmss>.ext" (timestamp = source's last-modified).
// * file/folder only in source -> move in, tagging the TOPMOST new node with
// "(merged from <label>)". A whole new folder becomes
// "name(merged from folder 2)"; a new file inside an existing folder
// becomes "stem(merged from folder 2).ext"; items beneath a marked folder
// keep their names.
// Move = copy-then-delete (MoveFileEx), so the source folder is emptied; empty
// source directories are removed afterward. Every action is written to a log.
static std::wstring Lc(std::wstring s) {
for (size_t i = 0; i < s.size(); ++i) s[i] = (wchar_t)towlower(s[i]);
return s;
}
static std::wstring DirOf(const std::wstring& rel) {
size_t p = rel.find_last_of(L'\\');
return (p == std::wstring::npos) ? std::wstring() : rel.substr(0, p);
}
static std::wstring BaseOf(const std::wstring& rel) {
size_t p = rel.find_last_of(L'\\');
return (p == std::wstring::npos) ? rel : rel.substr(p + 1);
}
static void SplitExt(const std::wstring& name, std::wstring& stem, std::wstring& ext) {
size_t dot = name.find_last_of(L'.');
if (dot == std::wstring::npos || dot == 0) { stem = name; ext.clear(); } // no ext / dotfile
else { stem = name.substr(0, dot); ext = name.substr(dot + 1); }
}
static std::wstring JoinExt(const std::wstring& stem, const std::wstring& ext) {
return ext.empty() ? stem : stem + L"." + ext;
}
static std::wstring LastModStamp(const std::wstring& full) {
WIN32_FILE_ATTRIBUTE_DATA fad; FILETIME lt; SYSTEMTIME st; wchar_t buf[32];
if (GetFileAttributesExW(full.c_str(), GetFileExInfoStandard, &fad) &&
FileTimeToLocalFileTime(&fad.ftLastWriteTime, <) &&
FileTimeToSystemTime(<, &st)) {
wsprintfW(buf, L"%04u%02u%02u%02u%02u%02u",
st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
return buf;
}
return L"00000000000000";
}
static std::wstring DiffName(const std::wstring& fname, const std::wstring& ts) {
std::wstring stem, ext; SplitExt(fname, stem, ext);
return JoinExt(stem + L"_LastMod_" + ts, ext);
}
static std::wstring MarkFileName(const std::wstring& fname, const std::wstring& label) {
std::wstring stem, ext; SplitExt(fname, stem, ext);
return JoinExt(stem + L"(merged from " + label + L")", ext);
}
static std::wstring MarkDirName(const std::wstring& name, const std::wstring& label) {
return name + L"(merged from " + label + L")";
}
static bool Exists(const std::wstring& p) {
return GetFileAttributesW(p.c_str()) != INVALID_FILE_ATTRIBUTES;
}
// If `full` exists, insert _2, _3, ... before the extension until unique.
static std::wstring MakeUnique(const std::wstring& full) {
if (!Exists(full)) return full;
size_t slash = full.find_last_of(L'\\');
std::wstring dir = full.substr(0, slash);
std::wstring name = full.substr(slash + 1);
std::wstring stem, ext; SplitExt(name, stem, ext);
for (int i = 2; i < 1000000; ++i) {
std::wstring cand = dir + L"\\" + JoinExt(stem + L"_" + std::to_wstring(i), ext);
if (!Exists(cand)) return cand;
}
return full;
}
// Recursively create a directory path. Returns false if a non-dir blocks it.
static bool EnsureDir(const std::wstring& dir) {
if (dir.empty()) return true;
DWORD a = GetFileAttributesW(dir.c_str());
if (a != INVALID_FILE_ATTRIBUTES) return (a & FILE_ATTRIBUTE_DIRECTORY) != 0;
size_t slash = dir.find_last_of(L'\\');
if (slash != std::wstring::npos) EnsureDir(dir.substr(0, slash));
return CreateDirectoryW(dir.c_str(), NULL) != 0 ||
GetLastError() == ERROR_ALREADY_EXISTS;
}
// Relative dir paths (lowercased) under root -> set.
static void CollectDirsSet(const std::wstring& root, const std::wstring& rel,
std::set<std::wstring>& out) {
std::wstring dir = root; if (!rel.empty()) dir += L"\\" + rel;
WIN32_FIND_DATAW fd; HANDLE h = FindFirstFileW((dir + L"\\*").c_str(), &fd);
if (h == INVALID_HANDLE_VALUE) return;
do {
if (wcscmp(fd.cFileName, L".")==0 || wcscmp(fd.cFileName, L"..")==0) continue;
if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) continue;
if (fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) continue;
std::wstring childRel = rel.empty()? std::wstring(fd.cFileName) : rel+L"\\"+fd.cFileName;
out.insert(Lc(childRel));
CollectDirsSet(root, childRel, out);
} while (FindNextFileW(h, &fd));
FindClose(h);
}
// Relative dir paths (original case) under root -> vector.
static void CollectDirsVec(const std::wstring& root, const std::wstring& rel,
std::vector<std::wstring>& out) {
std::wstring dir = root; if (!rel.empty()) dir += L"\\" + rel;
WIN32_FIND_DATAW fd; HANDLE h = FindFirstFileW((dir + L"\\*").c_str(), &fd);
if (h == INVALID_HANDLE_VALUE) return;
do {
if (wcscmp(fd.cFileName, L".")==0 || wcscmp(fd.cFileName, L"..")==0) continue;
if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) continue;
if (fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) continue;
std::wstring childRel = rel.empty()? std::wstring(fd.cFileName) : rel+L"\\"+fd.cFileName;
out.push_back(childRel);
CollectDirsVec(root, childRel, out);
} while (FindNextFileW(h, &fd));
FindClose(h);
}
// Resolves each source-relative directory to its destination-relative path,
// marking the topmost new folder and caching the mapping so sibling files reuse
// the same (possibly renamed) destination folder.
struct MergeCtx {
std::wstring dstRoot, label;
std::set<std::wstring> existDirs; // lc rel dirs present in dst originally
std::map<std::wstring, std::wstring> cache; // lc(srcRelDir) -> dst rel dir
bool dirExisted(const std::wstring& rel) {
return rel.empty() || existDirs.find(Lc(rel)) != existDirs.end();
}
std::wstring resolveDir(const std::wstring& srcRel) {
if (srcRel.empty()) return L"";
std::wstring key = Lc(srcRel);
std::map<std::wstring,std::wstring>::iterator it = cache.find(key);
if (it != cache.end()) return it->second;
std::wstring parent = DirOf(srcRel), last = BaseOf(srcRel);
std::wstring destParent = resolveDir(parent);
std::wstring destSeg;
if (dirExisted(srcRel)) {
destSeg = last; // already exists in dst
} else if (dirExisted(parent)) { // topmost new -> mark, create, uniquify
std::wstring base = dstRoot + (destParent.empty()? L"" : L"\\"+destParent);
std::wstring full = MakeUnique(base + L"\\" + MarkDirName(last, label));
EnsureDir(full);
destSeg = full.substr(full.find_last_of(L'\\') + 1);
} else {
destSeg = last; // inside a new folder -> keep name
}
std::wstring destRel = destParent.empty()? destSeg : destParent + L"\\" + destSeg;
cache[key] = destRel;
return destRel;
}
};
struct MergeCounts { size_t dup, diff, neu, fail, skip; };
static void LogRow(std::string& log, const wchar_t* action, const std::wstring& src,
const std::wstring& dst, const std::wstring& result) {
CsvField(log, action); log += ",";
CsvField(log, src); log += ",";
CsvField(log, dst); log += ",";
CsvField(log, result); log += "\r\n";
}
// Move a source-only file into the destination, tagging new files/folders.
static void DoMoveNew(MergeCtx& ctx, const std::wstring& srcRoot,
const std::wstring& rel, std::string& log, MergeCounts& cnt) {
std::wstring srcDir = DirOf(rel), fname = BaseOf(rel);
std::wstring destDirRel = ctx.resolveDir(srcDir);
std::wstring destName = ctx.dirExisted(srcDir) ? MarkFileName(fname, ctx.label) : fname;
std::wstring destDirFull = ctx.dstRoot + (destDirRel.empty()? L"" : L"\\"+destDirRel);
if (!EnsureDir(destDirFull)) { // e.g. a FILE sits where we need a dir
LogRow(log, L"NEW", rel, destDirRel + L"\\" + destName, L"SKIPPED (cannot create dir)");
++cnt.skip; return;
}
std::wstring srcFull = srcRoot + L"\\" + rel;
std::wstring destFull = MakeUnique(destDirFull + L"\\" + destName);
BOOL ok = MoveFileExW(srcFull.c_str(), destFull.c_str(), MOVEFILE_COPY_ALLOWED);
std::wstring rdst = destFull.substr(ctx.dstRoot.size() + 1);
if (ok) { LogRow(log, L"NEW", rel, rdst, L"OK"); ++cnt.neu; }
else {
wchar_t e[64]; wsprintfW(e, L"FAILED (err %lu)", GetLastError());
LogRow(log, L"NEW", rel, rdst, e); ++cnt.fail;
}
}
// Run a merge from srcRoot into dstRoot. `label` is e.g. L"folder 2".
static void MergeFolders(const std::wstring& srcRoot, const std::wstring& dstRoot,
const std::wstring& label, const std::wstring& logName,
std::wstring& summary) {
MergeCtx ctx; ctx.dstRoot = dstRoot; ctx.label = label;
CollectDirsSet(dstRoot, L"", ctx.existDirs);
std::vector<FileEntry> S, D;
WalkDir(srcRoot, L"", S);
WalkDir(dstRoot, L"", D);
std::sort(S.begin(), S.end(), RelLess);
std::sort(D.begin(), D.end(), RelLess);
std::string log = "Action,Source (relative),Destination (relative),Result\r\n";
MergeCounts cnt = {0,0,0,0,0};
size_t i = 0, j = 0;
while (i < S.size() && j < D.size()) {
int c = _wcsicmp(S[i].rel.c_str(), D[j].rel.c_str());
if (c == 0) {
std::wstring srcFull = srcRoot + L"\\" + S[i].rel;
std::wstring dstFull = dstRoot + L"\\" + D[j].rel;
int d = FilesDiffer(srcFull, dstFull, S[i].size, D[j].size);
if (d == 0) { // identical -> drop redundant source
BOOL ok = DeleteFileW(srcFull.c_str());
LogRow(log, L"DUPLICATE", S[i].rel, D[j].rel,
ok ? L"SOURCE DELETED" : L"FAILED to delete source");
if (ok) ++cnt.dup; else ++cnt.fail;
} else { // different -> move in, tagged _LastMod_
std::wstring ts = LastModStamp(srcFull);
std::wstring ddir = DirOf(S[i].rel);
std::wstring ddirFull = dstRoot + (ddir.empty()? L"" : L"\\"+ddir);
std::wstring destFull = MakeUnique(ddirFull + L"\\" + DiffName(BaseOf(S[i].rel), ts));
BOOL ok = MoveFileExW(srcFull.c_str(), destFull.c_str(), MOVEFILE_COPY_ALLOWED);
std::wstring rdst = destFull.substr(dstRoot.size() + 1);
if (ok) { LogRow(log, L"DIFFERENT", S[i].rel, rdst, L"OK"); ++cnt.diff; }
else {
wchar_t e[64]; wsprintfW(e, L"FAILED (err %lu)", GetLastError());
LogRow(log, L"DIFFERENT", S[i].rel, rdst, e); ++cnt.fail;
}
}
++i; ++j;
} else if (c < 0) { // only in source
DoMoveNew(ctx, srcRoot, S[i].rel, log, cnt); ++i;
} else { // only in destination -> already present
++j;
}
}
for (; i < S.size(); ++i) DoMoveNew(ctx, srcRoot, S[i].rel, log, cnt);
// Remove now-empty source directories, deepest first (RemoveDirectory is a
// no-op on non-empty dirs, so anything we couldn't move is left intact).
std::vector<std::wstring> sdirs;
CollectDirsVec(srcRoot, L"", sdirs);
std::sort(sdirs.begin(), sdirs.end(),
[](const std::wstring& a, const std::wstring& b){ return a.size() > b.size(); });
size_t removed = 0;
for (size_t k = 0; k < sdirs.size(); ++k)
if (RemoveDirectoryW((srcRoot + L"\\" + sdirs[k]).c_str())) ++removed;
wchar_t cwd[MAX_PATH]; GetCurrentDirectoryW(MAX_PATH, cwd);
std::wstring logPath = std::wstring(cwd) + L"\\" + logName;
bool wrote = WriteCsv(logPath, log);
wchar_t buf[2048];
wsprintfW(buf,
L"Merge complete (source = %s).\r\n"
L"Identical duplicates removed from source: %u\r\n"
L"Different files moved (tagged _LastMod_): %u\r\n"
L"New files/folders moved (tagged merged-from): %u\r\n"
L"Failures: %u Skipped: %u\r\n"
L"Empty source folders removed: %u\r\n"
L"%s%s",
label.c_str(),
(unsigned)cnt.dup, (unsigned)cnt.diff, (unsigned)cnt.neu,
(unsigned)cnt.fail, (unsigned)cnt.skip, (unsigned)removed,
wrote ? L"Log: " : L"WARNING: could not write log: ", logPath.c_str());
summary = buf;
}
// True if either path equals or is nested inside the other (case-insensitive).
static bool SameOrNested(const std::wstring& a, const std::wstring& b) {
std::wstring la = Lc(a), lb = Lc(b);
while (!la.empty() && la[la.size()-1] == L'\\') la.erase(la.size()-1);
while (!lb.empty() && lb[lb.size()-1] == L'\\') lb.erase(lb.size()-1);
const std::wstring& shorter = (la.size() <= lb.size()) ? la : lb;
const std::wstring& longer = (la.size() <= lb.size()) ? lb : la;
if (longer.compare(0, shorter.size(), shorter) != 0) return false;
return longer.size() == shorter.size() || longer[shorter.size()] == L'\\';
}
// ----------------------------- Window procedure ----------------------------
static HWND MakeButton(HWND parent, const wchar_t* text, int id,
int x, int y, int w, int h) {
HWND b = CreateWindowExW(0, L"BUTTON", text,
WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
x, y, w, h, parent, (HMENU)(INT_PTR)id,
NULL, NULL);
SendMessageW(b, WM_SETFONT, (WPARAM)g_font, TRUE);
return b;
}
static HWND MakeStatic(HWND parent, const wchar_t* text, int id,
int x, int y, int w, int h, DWORD extra) {
HWND s = CreateWindowExW(0, L"STATIC", text,
WS_CHILD | WS_VISIBLE | extra,
x, y, w, h, parent, (HMENU)(INT_PTR)id,
NULL, NULL);
SendMessageW(s, WM_SETFONT, (WPARAM)g_font, TRUE);
return s;
}
static void OnCreate(HWND hwnd) {
const int M = 12; // margin
const int colW = 258; // column width
const int x1 = M; // left column x
const int x2 = M + colW + M; // right column x
int y = M;
MakeStatic(hwnd, L"Folder 1", IDC_HDR1, x1, y, colW, 18, SS_LEFT);
MakeStatic(hwnd, L"Folder 2", IDC_HDR2, x2, y, colW, 18, SS_LEFT);
y += 20;
g_hLabel1 = MakeStatic(hwnd, L"(no folder selected)", IDC_LABEL1,
x1, y, colW, 48, SS_LEFT | WS_BORDER);
g_hLabel2 = MakeStatic(hwnd, L"(no folder selected)", IDC_LABEL2,
x2, y, colW, 48, SS_LEFT | WS_BORDER);
y += 52;
MakeButton(hwnd, L"Select Folder 1...", IDC_BTN_SEL1, x1, y, colW, 30);
MakeButton(hwnd, L"Select Folder 2...", IDC_BTN_SEL2, x2, y, colW, 30);
y += 30 + M;
int fullW = colW * 2 + M;
MakeButton(hwnd, L"Compare && Generate CSV", IDC_BTN_COMPARE,
x1, y, fullW, 34);
y += 34 + M;
g_hStatus = MakeStatic(hwnd,
L"Pick two folders, then Compare.", IDC_STATUS,
x1, y, fullW, 120, SS_LEFT);
y += 120 + M;
MakeButton(hwnd, L"Merge to Folder 1", IDC_BTN_MERGE1, x1, y, colW, 32);
MakeButton(hwnd, L"Merge to Folder 2", IDC_BTN_MERGE2, x2, y, colW, 32);
}
static void SetLabel(HWND label, const std::wstring& path) {
SetWindowTextW(label, path.empty() ? L"(no folder selected)"
: path.c_str());
}
static LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
switch (msg) {
case WM_CREATE:
OnCreate(hwnd);
return 0;
case WM_COMMAND:
switch (LOWORD(wParam)) {
case IDC_BTN_SEL1: {
std::wstring f = BrowseForFolder(hwnd, L"Select Folder 1");
if (!f.empty()) { g_folder1 = f; SetLabel(g_hLabel1, f); }
return 0;
}
case IDC_BTN_SEL2: {
std::wstring f = BrowseForFolder(hwnd, L"Select Folder 2");
if (!f.empty()) { g_folder2 = f; SetLabel(g_hLabel2, f); }
return 0;
}
case IDC_BTN_COMPARE: {
if (g_folder1.empty() || g_folder2.empty()) {
MessageBoxW(hwnd, L"Please select both folders first.",
L"DuplicateCleaner", MB_OK | MB_ICONWARNING);
return 0;
}
SetWindowTextW(g_hStatus, L"Comparing, please wait...");
UpdateWindow(g_hStatus);
std::wstring summary;
RunCompare(summary);
SetWindowTextW(g_hStatus, summary.c_str());
return 0;
}
case IDC_BTN_MERGE1:
case IDC_BTN_MERGE2: {
bool toFolder1 = (LOWORD(wParam) == IDC_BTN_MERGE1);
// Source is the OTHER folder; destination is the one named on the button.
const std::wstring& src = toFolder1 ? g_folder2 : g_folder1;
const std::wstring& dst = toFolder1 ? g_folder1 : g_folder2;
std::wstring label = toFolder1 ? L"folder 2" : L"folder 1";
std::wstring logName = toFolder1 ? L"merge_log_to_folder1.csv"
: L"merge_log_to_folder2.csv";
if (g_folder1.empty() || g_folder2.empty()) {
MessageBoxW(hwnd, L"Please select both folders first.",
L"DuplicateCleaner", MB_OK | MB_ICONWARNING);
return 0;
}
if (SameOrNested(g_folder1, g_folder2)) {
MessageBoxW(hwnd,
L"The two folders are the same or one is inside the other.\r\n"
L"Pick two separate folders before merging.",
L"DuplicateCleaner", MB_OK | MB_ICONWARNING);
return 0;
}
wchar_t prompt[1024];
wsprintfW(prompt,
L"This MOVES files from %s into %s.\r\n\r\n"
L" * identical duplicates are deleted from the source\r\n"
L" * conflicting files are brought in renamed with _LastMod_\r\n"
L" * new files/folders are tagged \"(merged from %s)\"\r\n\r\n"
L"Source: %s\r\n"
L"Destination: %s\r\n\r\n"
L"The source folder will be modified. Continue?",
label.c_str(), toFolder1 ? L"folder 1" : L"folder 2",
label.c_str(), src.c_str(), dst.c_str());
if (MessageBoxW(hwnd, prompt, L"Confirm Merge",
MB_YESNO | MB_ICONWARNING | MB_DEFBUTTON2) != IDYES)
return 0;
SetWindowTextW(g_hStatus, L"Merging, please wait...");
UpdateWindow(g_hStatus);
std::wstring summary;
MergeFolders(src, dst, label, logName, summary);
SetWindowTextW(g_hStatus, summary.c_str());
return 0;
}
}
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
return DefWindowProcW(hwnd, msg, wParam, lParam);
}
// ----------------------------- Entry point ---------------------------------
static HFONT CreateUiFont() {
// Use the system message font: Tahoma on XP, Segoe UI on Vista+.
NONCLIENTMETRICSW ncm;
ZeroMemory(&ncm, sizeof(ncm));
ncm.cbSize = sizeof(ncm);
if (SystemParametersInfoW(SPI_GETNONCLIENTMETRICS, sizeof(ncm), &ncm, 0))
return CreateFontIndirectW(&ncm.lfMessageFont);
return (HFONT)GetStockObject(DEFAULT_GUI_FONT);
}
int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE, LPWSTR, int nCmdShow) {
OleInitialize(NULL); // required for BIF_NEWDIALOGSTYLE folder dialog
INITCOMMONCONTROLSEX icc;
icc.dwSize = sizeof(icc);
icc.dwICC = ICC_STANDARD_CLASSES;
InitCommonControlsEx(&icc);
g_font = CreateUiFont();
WNDCLASSEXW wc;
ZeroMemory(&wc, sizeof(wc));
wc.cbSize = sizeof(wc);
wc.lpfnWndProc = WndProc;
wc.hInstance = hInst;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_BTNFACE + 1);
wc.lpszClassName = L"DuplicateCleanerWnd";
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
RegisterClassExW(&wc);
// Fixed-size window sized to fit the layout in OnCreate.
const int clientW = 12 + 258 + 12 + 258 + 12; // 552
const int clientH = 12 + 18 + 2 + 48 + 4 + 30 + 12 + 34 + 12 + 120 + 12 + 32 + 12; // ~358
RECT rc = { 0, 0, clientW, clientH };
DWORD style = (WS_OVERLAPPEDWINDOW & ~WS_THICKFRAME & ~WS_MAXIMIZEBOX);
AdjustWindowRect(&rc, style, FALSE);
HWND hwnd = CreateWindowExW(0, wc.lpszClassName,
L"DuplicateCleaner - Folder Comparison",
style, CW_USEDEFAULT, CW_USEDEFAULT,
rc.right - rc.left, rc.bottom - rc.top,
NULL, NULL, hInst, NULL);
if (!hwnd) { OleUninitialize(); return 1; }
ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);
MSG msg;
while (GetMessageW(&msg, NULL, 0, 0) > 0) {
if (!IsDialogMessageW(hwnd, &msg)) { // Tab navigation between controls
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
}
if (g_font) DeleteObject(g_font);
OleUninitialize();
return (int)msg.wParam;
}