-
Notifications
You must be signed in to change notification settings - Fork 82
/
Rdutil.cc
558 lines (495 loc) · 14.4 KB
/
Rdutil.cc
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
/*
copyright 2006-2017 Paul Dreik (earlier Paul Sundvall)
Distributed under GPL v 2.0 or later, at your option.
See LICENSE for further details.
*/
// pick up project config incl. assert control.
#include "config.h"
// std
#include <algorithm>
#include <cassert>
#include <chrono>
#include <cstring>
#include <fstream> //for file writing
#include <iostream> //for std::cerr
#include <ostream> //for output
#include <string> //for easier passing of string arguments
#include <thread> //sleep
// project
#include "Fileinfo.hh" //file container
#include "RdfindDebug.hh"
// class declaration
#include "Rdutil.hh"
int
Rdutil::printtofile(const std::string& filename) const
{
// open a file to print to
std::ofstream f1;
f1.open(filename.c_str(), std::ios_base::out);
if (!f1.is_open()) {
std::cerr << "could not open file \"" << filename << "\"\n";
return -1;
}
// exchange f1 for cout to write to terminal instead of file
std::ostream& output(f1);
// This uses "priority" instead of "cmdlineindex". Change this the day
// a change in output format is allowed (for backwards compatibility).
output << "# Automatically generated\n";
output << "# duptype id depth size device inode priority name\n";
std::vector<Fileinfo>::iterator it;
for (it = m_list.begin(); it != m_list.end(); ++it) {
output << Fileinfo::getduptypestring(*it) << " " << it->getidentity() << " "
<< it->depth() << " " << it->size() << " " << it->device() << " "
<< it->inode() << " " << it->get_cmdline_index() << " " << it->name()
<< '\n';
}
output << "# end of file\n";
f1.close();
return 0;
}
// applies int f(duplicate,const original) on every duplicate.
// if f returns nonzero, something is wrong.
// returns how many times the function was invoked.
template<typename Function>
std::size_t
applyactiononfile(std::vector<Fileinfo>& m_list, Function f)
{
const auto first = m_list.begin();
const auto last = m_list.end();
auto original = last;
std::size_t ntimesapplied = 0;
// loop over files
for (auto it = first; it != last; ++it) {
switch (it->getduptype()) {
case Fileinfo::duptype::DUPTYPE_FIRST_OCCURRENCE: {
original = it;
assert(original->getidentity() >= 0 &&
"original file should have positive identity");
} break;
case Fileinfo::duptype::DUPTYPE_OUTSIDE_TREE:
// intentional fallthrough
case Fileinfo::duptype::DUPTYPE_WITHIN_SAME_TREE: {
assert(original != last);
// double check that "it" shall be ~linked to "src"
assert(it->getidentity() == -original->getidentity() &&
"it must be connected to src");
// everything is in order. we may now hardlink/symlink/remove it.
if (f(*it, *original)) {
RDDEBUG(__FILE__ ": Failed to apply function f on it.\n");
} else {
++ntimesapplied;
}
} break;
default:
assert("file with bad duptype at this stage. Programming error!" ==
nullptr);
}
}
return ntimesapplied;
}
// helper for dryruns
namespace {
template<bool outputBname>
class dryrun_helper
{
public:
/// @param m1 may not be null
/// @param m2 may be null
explicit dryrun_helper(const char* m1, const char* m2 = nullptr)
: m_m1(m1)
, m_m2(m2)
{}
const char* const m_m1;
const char* const m_m2;
/// Mimic the return value of makeHardlinks etc. - pretend success
int operator()(const Fileinfo& A, const Fileinfo& B) const
{
std::cout << "(DRYRUN MODE) " << m_m1 << A.name();
if (m_m2) {
std::cout << m_m2;
}
if (outputBname) {
std::cout << B.name();
}
std::cout << '\n';
return 0;
}
}; // class
} // namespace
std::size_t
Rdutil::deleteduplicates(bool dryrun) const
{
if (dryrun) {
const bool outputBname = false;
dryrun_helper<outputBname> obj("delete ");
auto ret = applyactiononfile(m_list, obj);
std::cout.flush();
return ret;
} else {
return applyactiononfile(m_list, &Fileinfo::static_deletefile);
}
}
std::size_t
Rdutil::makesymlinks(bool dryrun) const
{
if (dryrun) {
const bool outputBname = true;
dryrun_helper<outputBname> obj("symlink ", " to ");
auto ret = applyactiononfile(m_list, obj);
std::cout.flush();
return ret;
} else {
return applyactiononfile(m_list, &Fileinfo::static_makesymlink);
}
}
std::size_t
Rdutil::makehardlinks(bool dryrun) const
{
if (dryrun) {
const bool outputBname = true;
dryrun_helper<outputBname> obj("hardlink ", " to ");
const auto ret = applyactiononfile(m_list, obj);
std::cout.flush();
return ret;
} else {
return applyactiononfile(m_list, &Fileinfo::static_makehardlink);
}
}
// mark files with a unique number
void
Rdutil::markitems()
{
std::int64_t fileno = 1;
for (auto& file : m_list) {
file.setidentity(fileno++);
}
}
namespace {
bool
cmpDeviceInode(const Fileinfo& a, const Fileinfo& b)
{
return std::make_tuple(a.device(), a.inode()) <
std::make_tuple(b.device(), b.inode());
}
// compares rank as described in RANKING on man page.
bool
cmpRank(const Fileinfo& a, const Fileinfo& b)
{
return std::make_tuple(a.get_cmdline_index(), a.depth(), a.getidentity()) <
std::make_tuple(b.get_cmdline_index(), b.depth(), b.getidentity());
}
bool
cmpDepthName(const Fileinfo& a, const Fileinfo& b)
{
// inefficient, make it a reference.
return std::make_tuple(a.depth(), a.name()) <
std::make_tuple(b.depth(), b.name());
}
// compares buffers
bool
cmpBuffers(const Fileinfo& a, const Fileinfo& b)
{
return std::memcmp(a.getbyteptr(), b.getbyteptr(), a.getbuffersize()) < 0;
}
#if !defined(NDEBUG)
bool
hasEqualBuffers(const Fileinfo& a, const Fileinfo& b)
{
return std::memcmp(a.getbyteptr(), b.getbyteptr(), a.getbuffersize()) == 0;
}
#endif
// compares file size
bool
cmpSize(const Fileinfo& a, const Fileinfo& b)
{
return a.size() < b.size();
}
bool
cmpSizeThenBuffer(const Fileinfo& a, const Fileinfo& b)
{
return (a.size() < b.size()) || (a.size() == b.size() && cmpBuffers(a, b));
}
/**
* goes through first to last, finds ranges of equal elements (determined by
* cmp) and invokes callback on each subrange.
* @param first
* @param last
* @param cmp
* @param callback invoked as callback(subrangefirst,subrangelast)
*/
template<class Iterator, class Cmp, class Callback>
void
apply_on_range(Iterator first, Iterator last, Cmp cmp, Callback callback)
{
assert(std::is_sorted(first, last, cmp));
// switch between linear search and logarithmic. the linear should be good
// because most of the time, we search very few adjacent elements.
// the difference seem to be within measurement noise.
const bool linearsearch = false;
if (linearsearch) {
while (first != last) {
auto sublast = first + 1;
while (sublast != last && !cmp(*first, *sublast)) {
++sublast;
}
// a duplicate range with respect to cmp
callback(first, sublast);
// keep searching.
first = sublast;
}
} else {
while (first != last) {
auto p = std::equal_range(first, last, *first, cmp);
// p.first will point to first. p.second will point to first+1 if no
// duplicate is found
assert(p.first == first);
// a duplicate range with respect to cmp
callback(p.first, p.second);
// keep searching.
first = p.second;
}
}
}
} // namespace
int
Rdutil::sortOnDeviceAndInode()
{
std::sort(m_list.begin(), m_list.end(), cmpDeviceInode);
return 0;
}
void
Rdutil::sort_on_depth_and_name(std::size_t index_of_first)
{
assert(index_of_first <= m_list.size());
auto it = std::begin(m_list) + static_cast<std::ptrdiff_t>(index_of_first);
std::sort(it, std::end(m_list), cmpDepthName);
}
std::size_t
Rdutil::removeIdenticalInodes()
{
// sort list on device and inode.
auto cmp = cmpDeviceInode;
std::sort(m_list.begin(), m_list.end(), cmp);
// loop over ranges of adjacent elements
using Iterator = decltype(m_list.begin());
apply_on_range(
m_list.begin(), m_list.end(), cmp, [](Iterator first, Iterator last) {
// let the highest-ranking element not be deleted. do this in order, to be
// cache friendly.
auto best = std::min_element(first, last, cmpRank);
std::for_each(first, best, [](Fileinfo& f) { f.setdeleteflag(true); });
best->setdeleteflag(false);
std::for_each(best + 1, last, [](Fileinfo& f) { f.setdeleteflag(true); });
});
return cleanup();
}
std::size_t
Rdutil::removeUniqueSizes()
{
// sort list on size
auto cmp = cmpSize;
std::sort(m_list.begin(), m_list.end(), cmp);
// loop over ranges of adjacent elements
using Iterator = decltype(m_list.begin());
apply_on_range(
m_list.begin(), m_list.end(), cmp, [](Iterator first, Iterator last) {
if (first + 1 == last) {
// single element. remove it!
first->setdeleteflag(true);
} else {
// multiple elements. keep them!
std::for_each(first, last, [](Fileinfo& f) { f.setdeleteflag(false); });
}
});
return cleanup();
}
std::size_t
Rdutil::removeUniqSizeAndBuffer()
{
// sort list on size
const auto cmp = cmpSize;
std::sort(m_list.begin(), m_list.end(), cmp);
const auto bufcmp = cmpBuffers;
// loop over ranges of adjacent elements
using Iterator = decltype(m_list.begin());
apply_on_range(
m_list.begin(), m_list.end(), cmp, [&](Iterator first, Iterator last) {
// all sizes are equal in [first,last) - sort on buffer content.
std::sort(first, last, bufcmp);
// on this set of buffers, find those which are unique
apply_on_range(
first, last, bufcmp, [](Iterator firstbuf, Iterator lastbuf) {
if (firstbuf + 1 == lastbuf) {
// we have a unique buffer!
firstbuf->setdeleteflag(true);
} else {
std::for_each(
firstbuf, lastbuf, [](Fileinfo& f) { f.setdeleteflag(false); });
}
});
});
return cleanup();
}
void
Rdutil::markduplicates()
{
const auto cmp = cmpSizeThenBuffer;
assert(std::is_sorted(m_list.begin(), m_list.end(), cmp));
// loop over ranges of adjacent elements
using Iterator = decltype(m_list.begin());
apply_on_range(
m_list.begin(),
m_list.end(),
cmp,
[](const Iterator first, const Iterator last) {
// size and buffer are equal in [first,last) - all are duplicates!
assert(std::distance(first, last) >= 2);
// the one with the lowest rank is the original
auto orig = std::min_element(first, last, cmpRank);
assert(orig != last);
// place it first, so later stages will find the original first.
std::iter_swap(first, orig);
orig = first;
// make sure they are all duplicates
assert(last == find_if_not(first, last, [orig](const Fileinfo& a) {
return orig->size() == a.size() && hasEqualBuffers(*orig, a);
}));
// mark the files with the appropriate tag.
auto marker = [orig](Fileinfo& elem) {
elem.setidentity(-orig->getidentity());
if (elem.get_cmdline_index() == orig->get_cmdline_index()) {
elem.setduptype(Fileinfo::duptype::DUPTYPE_WITHIN_SAME_TREE);
} else {
elem.setduptype(Fileinfo::duptype::DUPTYPE_OUTSIDE_TREE);
}
};
orig->setduptype(Fileinfo::duptype::DUPTYPE_FIRST_OCCURRENCE);
std::for_each(first + 1, last, marker);
assert(first->getduptype() ==
Fileinfo::duptype::DUPTYPE_FIRST_OCCURRENCE);
});
}
std::size_t
Rdutil::cleanup()
{
const auto size_before = m_list.size();
auto it = std::remove_if(m_list.begin(), m_list.end(), [](const Fileinfo& A) {
return A.deleteflag();
});
m_list.erase(it, m_list.end());
const auto size_after = m_list.size();
return size_before - size_after;
}
#if 0
std::size_t
Rdutil::remove_small_files(Fileinfo::filesizetype minsize)
{
const auto size_before = m_list.size();
const auto begin = m_list.begin();
const auto end = m_list.end();
decltype(m_list.begin()) it;
if (minsize == 0) {
it =
std::remove_if(begin, end, [](const Fileinfo& A) { return A.isempty(); });
} else {
it = std::remove_if(begin, end, [=](const Fileinfo& A) {
return A.is_smaller_than(minsize);
});
}
m_list.erase(it, end);
return size_before - m_list.size();
}
#endif
Fileinfo::filesizetype
Rdutil::totalsizeinbytes(int opmode) const
{
assert(opmode == 0 || opmode == 1);
Fileinfo::filesizetype totalsize = 0;
if (opmode == 0) {
for (const auto& elem : m_list) {
totalsize += elem.size();
}
} else if (opmode == 1) {
for (const auto& elem : m_list) {
if (elem.getduptype() == Fileinfo::duptype::DUPTYPE_FIRST_OCCURRENCE) {
totalsize += elem.size();
}
}
}
return totalsize;
}
namespace littlehelper {
// helper to make "size" into a more readable form.
int
calcrange(Fileinfo::filesizetype& size)
{
int range = 0;
Fileinfo::filesizetype tmp = 0;
while (size > 1024) {
tmp = size >> 9;
size = (tmp >> 1);
++range;
}
// round up if necessary
if (tmp & 0x1) {
++size;
}
return range;
}
// source of capitalization rules etc:
// https://en.wikipedia.org/wiki/Binary_prefix
std::string
byteprefix(int range)
{
switch (range) {
case 0:
return "B";
case 1:
return "KiB";
case 2:
return "MiB";
case 3:
return "GiB";
case 4:
return "TiB"; // Tebibyte
case 5:
return "PiB"; // Pebibyte
case 6:
return "EiB"; // Exbibyte
default:
return "!way too much!";
}
}
} // namespace littlehelper
std::ostream&
Rdutil::totalsize(std::ostream& out, int opmode) const
{
auto size = totalsizeinbytes(opmode);
const int range = littlehelper::calcrange(size);
out << size << " " << littlehelper::byteprefix(range);
return out;
}
std::ostream&
Rdutil::saveablespace(std::ostream& out) const
{
auto size = totalsizeinbytes(0) - totalsizeinbytes(1);
int range = littlehelper::calcrange(size);
out << size << " " << littlehelper::byteprefix(range);
return out;
}
int
Rdutil::fillwithbytes(enum Fileinfo::readtobuffermode type,
enum Fileinfo::readtobuffermode lasttype,
const long nsecsleep)
{
// first sort on inode (to read efficiently from the hard drive)
sortOnDeviceAndInode();
const auto duration = std::chrono::nanoseconds{ nsecsleep };
for (auto& elem : m_list) {
elem.fillwithbytes(type, lasttype);
if (nsecsleep > 0) {
std::this_thread::sleep_for(duration);
}
}
return 0;
}