/
dustmite.d
1406 lines (1221 loc) · 31.3 KB
/
dustmite.d
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
/// DustMite, a D test case minimization tool
/// Written by Vladimir Panteleev <vladimir@thecybershadow.net>
/// Released into the Public Domain
module dustmite;
import std.stdio;
import std.file;
import std.path;
import std.string;
import std.getopt;
import std.array;
import std.process;
import std.algorithm;
import std.exception;
import std.datetime;
import std.regex;
import std.conv;
import std.ascii;
import std.random;
import splitter;
alias Splitter = splitter.Splitter;
// Issue 314 workarounds
alias std.string.join join;
alias std.string.startsWith startsWith;
string dir, resultDir, tester, globalCache;
string dirSuffix(string suffix) { return (dir.absolutePath().buildNormalizedPath() ~ "." ~ suffix).relativePath(); }
size_t maxBreadth;
Entity root;
size_t origDescendants;
bool concatPerformed;
int tests; bool foundAnything;
bool noSave, trace, noRedirect;
string strategy = "inbreadth";
struct Times { StopWatch total, load, testSave, resultSave, test, clean, cacheHash, globalCache, misc; }
Times times;
static this() { times.total.start(); times.misc.start(); }
void measure(string what)(void delegate() p)
{
times.misc.stop(); mixin("times."~what~".start();");
p();
mixin("times."~what~".stop();"); times.misc.start();
}
struct Reduction
{
enum Type { None, Remove, Unwrap, Concat, ReplaceWord }
Type type;
// Remove / Unwrap / Concat
size_t[] address;
Entity target;
// ReplaceWord
string from, to;
size_t index, total;
string toString()
{
string name = .to!string(type);
final switch (type)
{
case Reduction.Type.None:
return name;
case Reduction.Type.ReplaceWord:
return format(`%s [%d/%d: %s -> %s]`, name, index+1, total, from, to);
case Reduction.Type.Remove:
case Reduction.Type.Unwrap:
case Reduction.Type.Concat:
string[] segments = new string[address.length];
Entity e = root;
size_t progress;
bool binary = maxBreadth == 2;
foreach (i, a; address)
{
segments[i] = binary ? text(a) : format("%d/%d", e.children.length-a, e.children.length);
foreach (c; e.children[0..a])
progress += c.descendants;
progress++; // account for this node
e = e.children[a];
}
progress += e.descendants;
return format("[%5.1f%%] %s [%s]", (origDescendants-progress) * 100.0 / origDescendants, name, segments.join(binary ? "" : ", "));
}
}
}
auto nullReduction = Reduction(Reduction.Type.None);
int main(string[] args)
{
bool force, dump, dumpHtml, showTimes, stripComments, obfuscate, keepLength, showHelp, noOptimize;
string coverageDir;
string[] reduceOnly, noRemoveStr, splitRules;
getopt(args,
"force", &force,
"reduceonly|reduce-only", &reduceOnly,
"noremove|no-remove", &noRemoveStr,
"strip-comments", &stripComments,
"coverage", &coverageDir,
"obfuscate", &obfuscate,
"keep-length", &keepLength,
"strategy", &strategy,
"split", &splitRules,
"dump", &dump,
"dump-html", &dumpHtml,
"times", &showTimes,
"noredirect|no-redirect", &noRedirect,
"cache", &globalCache, // for research
"trace", &trace, // for debugging
"nosave|no-save", &noSave, // for research
"nooptimize|no-optimize", &noOptimize, // for research
"h|help", &showHelp
);
if (showHelp || args.length == 1 || args.length>3)
{
stderr.writef(q"EOS
Usage: %s [OPTION]... PATH TESTER
PATH should be a directory containing a clean copy of the file-set to reduce.
A file path can also be specified. NAME.EXT will be treated like NAME/NAME.EXT.
TESTER should be a shell command which returns 0 for a correct reduction,
and anything else otherwise.
Supported options:
--force Force reduction of unusual files
--reduce-only MASK Only reduce paths glob-matching MASK
(may be used multiple times)
--no-remove REGEXP Do not reduce blocks containing REGEXP
(may be used multiple times)
--strip-comments Attempt to remove comments from source code.
--coverage DIR Load .lst files corresponding to source files from DIR
--obfuscate Instead of reducing, obfuscate the input by replacing
words with random substitutions
--keep-length Preserve word length when obfuscating
--split MASK:MODE Parse and reduce files specified by MASK using the given
splitter. Can be repeated. MODE must be one of:
%-(%s, %)
--no-redirect Don't redirect stdout/stderr streams of test command.
EOS", args[0], splitterNames);
if (!showHelp)
{
stderr.write(q"EOS
--help Show this message and some less interesting options
EOS");
}
else
{
stderr.write(q"EOS
--help Show this message
Less interesting options:
--strategy STRAT Set strategy (careful/lookback/pingpong/indepth/inbreadth)
--dump Dump parsed tree to DIR.dump file
--dump-html Dump parsed tree to DIR.html file
--times Display verbose spent time breakdown
--cache DIR Use DIR as persistent disk cache
(in addition to memory cache)
--trace Save all attempted reductions to DIR.trace
--no-save Disable saving in-progress results
--no-optimize Disable tree optimization step
(may be useful with --dump)
EOS");
}
stderr.write(q"EOS
Full documentation can be found on the GitHub wiki:
https://github.com/CyberShadow/DustMite/wiki
EOS");
return showHelp ? 0 : 64; // EX_USAGE
}
enforce(!(stripComments && coverageDir), "Sorry, --strip-comments is not compatible with --coverage");
dir = args[1];
if (isDirSeparator(dir[$-1]))
dir = dir[0..$-1];
if (args.length>=3)
tester = args[2];
bool isDotName(string fn) { return fn.startsWith(".") && !(fn=="." || fn==".."); }
if (!force && isDir(dir))
foreach (string path; dirEntries(dir, SpanMode.breadth))
if (isDotName(baseName(path)) || isDotName(baseName(dirName(path))) || extension(path)==".o" || extension(path)==".obj" || extension(path)==".exe")
{
stderr.writefln("Suspicious file found: %s\nYou should use a clean copy of the source tree.\nIf it was your intention to include this file in the file-set to be reduced,\nre-run dustmite with the --force option.", path);
return 1;
}
ParseRule parseSplitRule(string rule)
{
auto p = rule.lastIndexOf(':');
enforce(p > 0, "Invalid parse rule: " ~ rule);
auto pattern = rule[0..p];
auto splitterName = rule[p+1..$];
auto splitterIndex = splitterNames.countUntil(splitterName);
enforce(splitterIndex >= 0, "Unknown splitter: " ~ splitterName);
return ParseRule(pattern, cast(Splitter)splitterIndex);
}
ParseOptions parseOptions;
parseOptions.stripComments = stripComments;
parseOptions.mode = obfuscate ? ParseOptions.Mode.words : ParseOptions.Mode.source;
parseOptions.rules = splitRules.map!parseSplitRule().array();
measure!"load"({root = loadFiles(dir, parseOptions);});
enforce(root.children.length, "No files in specified directory");
applyNoRemoveMagic();
applyNoRemoveRegex(noRemoveStr, reduceOnly);
if (coverageDir)
loadCoverage(coverageDir);
if (!obfuscate && !noOptimize)
optimize(root);
maxBreadth = getMaxBreadth(root);
countDescendants(root);
resetProgress();
assignID(root);
if (dump)
dumpSet(dirSuffix("dump"));
if (dumpHtml)
dumpToHtml(dirSuffix("html"));
if (tester is null)
{
writeln("No tester specified, exiting");
return 0;
}
resultDir = dirSuffix("reduced");
enforce(!exists(resultDir), "Result directory already exists");
if (!test(nullReduction))
throw new Exception("Initial test fails");
foundAnything = false;
if (obfuscate)
.obfuscate(keepLength);
else
reduce();
auto duration = cast(Duration)times.total.peek();
duration = dur!"msecs"(duration.total!"msecs"); // truncate anything below ms, users aren't interested in that
if (foundAnything)
{
if (noSave)
measure!"resultSave"({safeSave(resultDir);});
writefln("Done in %s tests and %s; reduced version is in %s", tests, duration, resultDir);
}
else
writefln("Done in %s tests and %s; no reductions found", tests, duration);
if (showTimes)
foreach (i, t; times.tupleof)
writefln("%s: %s", times.tupleof[i].stringof, cast(Duration)times.tupleof[i].peek());
return 0;
}
size_t getMaxBreadth(Entity e)
{
size_t breadth = e.children.length;
foreach (child; e.children)
{
auto childBreadth = getMaxBreadth(child);
if (breadth < childBreadth)
breadth = childBreadth;
}
return breadth;
}
size_t countDescendants(Entity e)
{
size_t n = 1;
foreach (c; e.children)
n += countDescendants(c);
return e.descendants = n;
}
size_t checkDescendants(Entity e)
{
size_t n = 1;
foreach (c; e.children)
n += checkDescendants(c);
assert(e.descendants == n);
return n;
}
size_t countFiles(Entity e)
{
if (e.isFile)
return 1;
else
{
size_t n = 0;
foreach (c; e.children)
n += countFiles(c);
return n;
}
}
/// Try reductions at address. Edit set, save result and return true on successful reduction.
bool testAddress(size_t[] address)
{
auto e = entityAt(address);
if (tryReduction(Reduction(Reduction.Type.Remove, address, e)))
return true;
else
if (e.head.length && e.tail.length && tryReduction(Reduction(Reduction.Type.Unwrap, address, e)))
return true;
else
if (e.isFile && !concatPerformed && tryReduction(Reduction(Reduction.Type.Concat, address, e)))
return concatPerformed = true;
else
return false;
}
void resetProgress()
{
origDescendants = root.descendants;
}
void testLevel(int testDepth, out bool tested, out bool changed)
{
tested = changed = false;
resetProgress();
enum MAX_DEPTH = 1024;
size_t[MAX_DEPTH] address;
void scan(Entity e, int depth)
{
if (depth < testDepth)
{
// recurse
foreach_reverse (i, c; e.children)
{
address[depth] = i;
scan(c, depth+1);
}
}
else
if (e.noRemove)
{
// skip, but don't stop going deeper
tested = true;
}
else
{
// test
tested = true;
if (testAddress(address[0..depth]))
changed = true;
}
}
scan(root, 0);
//writefln("Scan results: tested=%s, changed=%s", tested, changed);
}
void startIteration(int iterCount)
{
writefln("############### ITERATION %d ################", iterCount);
resetProgress();
}
/// Keep going deeper until we find a successful reduction.
/// When found, finish tests at current depth and restart from top depth (new iteration).
/// If we reach the bottom (depth with no nodes on it), we're done.
void reduceCareful()
{
bool tested;
int iterCount;
do
{
startIteration(iterCount++);
bool changed;
int depth = 0;
do
{
writefln("============= Depth %d =============", depth);
testLevel(depth, tested, changed);
depth++;
} while (tested && !changed); // go deeper while we found something to test, but no results
} while (tested); // stop when we didn't find anything to test
}
/// Keep going deeper until we find a successful reduction.
/// When found, go up a depth level.
/// Keep going up while we find new reductions. Repeat topmost depth level as necessary.
/// Once no new reductions are found at higher depths, jump to the next unvisited depth in this iteration.
/// If we reach the bottom (depth with no nodes on it), start a new iteration.
/// If we finish an iteration without finding any reductions, we're done.
void reduceLookback()
{
bool iterationChanged;
int iterCount;
do
{
iterationChanged = false;
startIteration(iterCount++);
int depth = 0, maxDepth = 0;
bool depthTested;
do
{
writefln("============= Depth %d =============", depth);
bool depthChanged;
testLevel(depth, depthTested, depthChanged);
if (depthChanged)
{
iterationChanged = true;
depth--;
if (depth < 0)
depth = 0;
}
else
{
maxDepth++;
depth = maxDepth;
}
} while (depthTested); // keep going up/down while we found something to test
} while (iterationChanged); // stop when we couldn't reduce anything this iteration
}
/// Keep going deeper until we find a successful reduction.
/// When found, go up a depth level.
/// Keep going up while we find new reductions. Repeat topmost depth level as necessary.
/// Once no new reductions are found at higher depths, start going downwards again.
/// If we reach the bottom (depth with no nodes on it), start a new iteration.
/// If we finish an iteration without finding any reductions, we're done.
void reducePingPong()
{
bool iterationChanged;
int iterCount;
do
{
iterationChanged = false;
startIteration(iterCount++);
int depth = 0;
bool depthTested;
do
{
writefln("============= Depth %d =============", depth);
bool depthChanged;
testLevel(depth, depthTested, depthChanged);
if (depthChanged)
{
iterationChanged = true;
depth--;
if (depth < 0)
depth = 0;
}
else
depth++;
} while (depthTested); // keep going up/down while we found something to test
} while (iterationChanged); // stop when we couldn't reduce anything this iteration
}
/// Keep going deeper.
/// If we reach the bottom (depth with no nodes on it), start a new iteration.
/// If we finish an iteration without finding any reductions, we're done.
void reduceInBreadth()
{
bool iterationChanged;
int iterCount;
do
{
iterationChanged = false;
startIteration(iterCount++);
int depth = 0;
bool depthTested;
do
{
writefln("============= Depth %d =============", depth);
bool depthChanged;
testLevel(depth, depthTested, depthChanged);
if (depthChanged)
iterationChanged = true;
depth++;
} while (depthTested); // keep going down while we found something to test
} while (iterationChanged); // stop when we couldn't reduce anything this iteration
}
/// Look at every entity in the tree.
/// If we can reduce this entity, continue looking at its siblings.
/// Otherwise, recurse and look at its children.
/// End an iteration once we looked at an entire tree.
/// If we finish an iteration without finding any reductions, we're done.
void reduceInDepth()
{
bool changed;
int iterCount;
do
{
changed = false;
startIteration(iterCount++);
enum MAX_DEPTH = 1024;
size_t[MAX_DEPTH] address;
void scan(Entity e, int depth)
{
if (e.noRemove)
{
// skip, but don't stop going deeper
}
else
{
// test
if (testAddress(address[0..depth]))
{
changed = true;
return;
}
}
// recurse
foreach_reverse (i, c; e.children)
{
address[depth] = i;
scan(c, depth+1);
}
}
scan(root, 0);
} while (changed && root.children.length); // stop when we couldn't reduce anything this iteration
}
void reduce()
{
if (countFiles(root) < 2)
concatPerformed = true;
switch (strategy)
{
case "careful":
return reduceCareful();
case "lookback":
return reduceLookback();
case "pingpong":
return reducePingPong();
case "indepth":
return reduceInDepth();
case "inbreadth":
return reduceInBreadth();
default:
throw new Exception("Unknown strategy");
}
}
Mt19937 rng;
void obfuscate(bool keepLength)
{
bool[string] wordSet;
string[] words; // preserve file order
foreach (f; root.children)
{
foreach (entity; parseToWords(f.filename) ~ f.children)
if (entity.head.length && !isDigit(entity.head[0]))
if (entity.head !in wordSet)
{
wordSet[entity.head] = true;
words ~= entity.head;
}
}
string idgen(size_t length)
{
static const first = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // use caps to avoid collisions with reserved keywords
static const other = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_";
if (keepLength)
{
auto result = new char[length];
foreach (i, ref c; result)
c = (i==0 ? first : other)[uniform(0, $, rng)];
return assumeUnique(result);
}
else
{
static int n;
int index = n++;
string result;
result ~= first[index % $];
index /= first.length;
while (index)
result ~= other[index % $],
index /= other.length;
return result;
}
}
auto r = Reduction(Reduction.Type.ReplaceWord);
r.total = words.length;
foreach (i, word; words)
{
r.index = i;
r.from = word;
int tries = 0;
do
r.to = idgen(word.length);
while (r.to in wordSet && tries++ < 10);
wordSet[r.to] = true;
tryReduction(r);
}
}
bool skipEntity(Entity e)
{
if (e.removed)
return true;
foreach (dependency; e.dependencies)
if (skipEntity(dependency))
return true;
return false;
}
void dump(Entity root, ref Reduction reduction, void delegate(string) handleFile, void delegate(string) handleText)
{
void dumpEntity(Entity e)
{
if (reduction.type == Reduction.Type.ReplaceWord)
{
if (e.isFile)
{
assert(e.head.length==0 && e.tail.length==0);
handleFile(applyReductionToPath(e.filename, reduction));
foreach (c; e.children)
dumpEntity(c);
}
else
if (e.head || e.tail)
{
assert(e.children.length==0);
if (e.head)
{
if (e.head == reduction.from)
handleText(reduction.to);
else
handleText(e.head);
}
handleText(e.tail);
}
else
foreach (c; e.children)
dumpEntity(c);
}
else
if (e is reduction.target)
{
final switch (reduction.type)
{
case Reduction.Type.None:
case Reduction.Type.ReplaceWord:
assert(0);
case Reduction.Type.Remove: // skip this entity
return;
case Reduction.Type.Unwrap: // skip head/tail
foreach (c; e.children)
dumpEntity(c);
break;
case Reduction.Type.Concat: // write contents of all files to this one; leave other files empty
handleFile(e.filename);
void dumpFileContent(Entity e)
{
foreach (f; e.children)
if (f.isFile)
foreach (c; f.children)
dumpEntity(c);
else
dumpFileContent(f);
}
dumpFileContent(root);
break;
}
}
else
if (skipEntity(e))
return;
else
if (e.isFile)
{
handleFile(e.filename);
if (reduction.type == Reduction.Type.Concat) // not the target - writing an empty file
return;
foreach (c; e.children)
dumpEntity(c);
}
else
{
if (e.head.length) handleText(e.head);
foreach (c; e.children)
dumpEntity(c);
if (e.tail.length) handleText(e.tail);
}
}
debug verifyNotRemoved(root);
if (reduction.type == Reduction.Type.Remove)
markRemoved(reduction.target, true); // Needed for dependencies
dumpEntity(root);
if (reduction.type == Reduction.Type.Remove)
markRemoved(reduction.target, false);
debug verifyNotRemoved(root);
}
void save(Reduction reduction, string savedir)
{
safeMkdir(savedir);
File o;
void handleFile(string fn)
{
auto path = buildPath(savedir, fn);
if (!exists(dirName(path)))
safeMkdir(dirName(path));
if (o.isOpen)
o.close();
o.open(path, "wb");
}
dump(root, reduction, &handleFile, &o.write!string);
if (o.isOpen)
o.close();
}
Entity entityAt(size_t[] address)
{
Entity e = root;
foreach (a; address)
e = e.children[a];
return e;
}
/// Try specified reduction. If it succeeds, apply it permanently and save intermediate result.
bool tryReduction(Reduction r)
{
if (test(r))
{
foundAnything = true;
debug
auto hashBefore = hash(r);
applyReduction(r);
debug
{
auto hashAfter = hash(nullReduction);
assert(hashBefore == hashAfter, "Reduction preview/application mismatch");
}
saveResult();
return true;
}
return false;
}
void verifyNotRemoved(Entity e)
{
assert(!e.removed);
foreach (c; e.children)
verifyNotRemoved(c);
}
void markRemoved(Entity e, bool value)
{
assert(e.removed == !value);
e.removed = value;
foreach (c; e.children)
markRemoved(c, value);
}
/// Permanently apply specified reduction to set.
void applyReduction(ref Reduction r)
{
final switch (r.type)
{
case Reduction.Type.None:
return;
case Reduction.Type.ReplaceWord:
{
foreach (ref f; root.children)
{
f.filename = applyReductionToPath(f.filename, r);
foreach (ref entity; f.children)
if (entity.head == r.from)
entity.head = r.to;
}
return;
}
case Reduction.Type.Remove:
{
debug verifyNotRemoved(root);
markRemoved(entityAt(r.address), true);
if (r.address.length)
{
auto casualties = entityAt(r.address).descendants;
foreach (n; 0..r.address.length)
entityAt(r.address[0..n]).descendants -= casualties;
auto p = entityAt(r.address[0..$-1]);
p.children = remove(p.children, r.address[$-1]);
}
else
root = new Entity();
debug verifyNotRemoved(root);
debug checkDescendants(root);
return;
}
case Reduction.Type.Unwrap:
with (entityAt(r.address))
head = tail = null;
return;
case Reduction.Type.Concat:
{
Entity[] allData;
void scan(Entity e)
{
if (e.isFile)
{
allData ~= e.children;
e.children = null;
}
else
foreach (c; e.children)
scan(c);
}
scan(root);
r.target.children = allData;
optimize(r.target);
countDescendants(root);
return;
}
}
}
string applyReductionToPath(string path, Reduction reduction)
{
if (reduction.type == Reduction.Type.ReplaceWord)
{
Entity[] words = parseToWords(path);
string result;
foreach (i, word; words)
{
if (i > 0 && i == words.length-1 && words[i-1].tail.endsWith("."))
result ~= word.head; // skip extension
else
if (word.head == reduction.from)
result ~= reduction.to;
else
result ~= word.head;
result ~= word.tail;
}
return result;
}
return path;
}
void autoRetry(void delegate() fun, string operation)
{
while (true)
try
{
fun();
return;
}
catch (Exception e)
{
writeln("Error while attempting to " ~ operation ~ ": " ~ e.msg);
import core.thread;
Thread.sleep(dur!"seconds"(1));
writeln("Retrying...");
}
}
/// Alternative way to check for file existence
/// Files marked for deletion act as inexistant, but still prevent creation and appear in directory listings
bool exists2(string path)
{
return array(dirEntries(dirName(path), baseName(path), SpanMode.shallow)).length > 0;
}
void deleteAny(string path)
{
if (exists(path))
{
if (isDir(path))
rmdirRecurse(path);
else
remove(path);
}
enforce(!exists(path) && !exists2(path), "Path still exists"); // Windows only marks locked directories for deletion
}
void safeDelete(string path) { autoRetry({deleteAny(path);}, "delete " ~ path); }
void safeRename(string src, string dst) { autoRetry({rename(src, dst);}, "rename " ~ src ~ " to " ~ dst); }
void safeMkdir(string path) { autoRetry({mkdirRecurse(path);}, "mkdir " ~ path); }
void safeReplace(string path, void delegate(string path) creator)
{
auto tmpPath = path ~ ".inprogress";
if (exists(tmpPath)) safeDelete(tmpPath);
auto oldPath = path ~ ".old";
if (exists(oldPath)) safeDelete(oldPath);
{
scope(failure) safeDelete(tmpPath);
creator(tmpPath);
}
if (exists(path)) safeRename(path, oldPath);
safeRename(tmpPath, path);
if (exists(oldPath)) safeDelete(oldPath);
}
void safeSave(string savedir) { safeReplace(savedir, path => save(nullReduction, path)); }
void saveResult()
{
if (!noSave)
measure!"resultSave"({safeSave(resultDir);});
}
version(HAVE_AE)
{
// Use faster murmurhash from http://github.com/CyberShadow/ae
// when compiled with -version=HAVE_AE
import ae.utils.digest;
import ae.utils.textout;
alias MH3Digest128 HASH;
HASH hash(Reduction reduction)
{
static StringBuffer sb;
sb.clear();
auto writer = &sb.put!string;
dump(root, reduction, writer, writer);
return murmurHash3_128(sb.get());
}
alias digestToStringMH3 formatHash;
}
else
{
import std.digest.md;
alias ubyte[16] HASH;
HASH hash(Reduction reduction)
{
ubyte[16] digest;
MD5 context;
context.start();
auto writer = cast(void delegate(string))&context.put;
dump(root, reduction, writer, writer);