]> git.sesse.net Git - plocate/blob - plocate-build.cpp
Encapsulate some database-building logic into a class.
[plocate] / plocate-build.cpp
1 #include "db.h"
2 #include "dprintf.h"
3 #include "turbopfor-encode.h"
4
5 #include <algorithm>
6 #include <assert.h>
7 #include <chrono>
8 #include <getopt.h>
9 #include <iosfwd>
10 #include <math.h>
11 #include <memory>
12 #include <random>
13 #include <stdint.h>
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <string.h>
17 #include <string>
18 #include <string_view>
19 #include <sys/stat.h>
20 #include <utility>
21 #include <vector>
22 #include <zdict.h>
23 #include <zstd.h>
24
25 #define P4NENC_BOUND(n) ((n + 127) / 128 + (n + 32) * sizeof(uint32_t))
26
27 #define NUM_TRIGRAMS 16777216
28
29 using namespace std;
30 using namespace std::chrono;
31
32 string zstd_compress(const string &src, ZSTD_CDict *cdict, string *tempbuf);
33
34 constexpr unsigned num_overflow_slots = 16;
35 bool use_debug = false;
36
37 static inline uint32_t read_unigram(const string_view s, size_t idx)
38 {
39         if (idx < s.size()) {
40                 return (unsigned char)s[idx];
41         } else {
42                 return 0;
43         }
44 }
45
46 static inline uint32_t read_trigram(const string_view s, size_t start)
47 {
48         return read_unigram(s, start) |
49                 (read_unigram(s, start + 1) << 8) |
50                 (read_unigram(s, start + 2) << 16);
51 }
52
53 enum {
54         DBE_NORMAL = 0, /* A non-directory file */
55         DBE_DIRECTORY = 1, /* A directory */
56         DBE_END = 2 /* End of directory contents; contains no name */
57 };
58
59 // From mlocate.
60 struct db_header {
61         uint8_t magic[8];
62         uint32_t conf_size;
63         uint8_t version;
64         uint8_t check_visibility;
65         uint8_t pad[2];
66 };
67
68 // From mlocate.
69 struct db_directory {
70         uint64_t time_sec;
71         uint32_t time_nsec;
72         uint8_t pad[4];
73 };
74
75 class PostingListBuilder {
76 public:
77         inline void add_docid(uint32_t docid);
78         void finish();
79
80         string encoded;
81         size_t num_docids = 0;
82
83 private:
84         void write_header(uint32_t docid);
85         void append_block();
86
87         vector<uint32_t> pending_deltas;
88
89         uint32_t last_block_end, last_docid = -1;
90 };
91
92 void PostingListBuilder::add_docid(uint32_t docid)
93 {
94         // Deduplicate against the last inserted value, if any.
95         if (docid == last_docid) {
96                 return;
97         }
98
99         if (num_docids == 0) {
100                 // Very first docid.
101                 write_header(docid);
102                 ++num_docids;
103                 last_block_end = last_docid = docid;
104                 return;
105         }
106
107         pending_deltas.push_back(docid - last_docid - 1);
108         last_docid = docid;
109         if (pending_deltas.size() == 128) {
110                 append_block();
111                 pending_deltas.clear();
112                 last_block_end = docid;
113         }
114         ++num_docids;
115 }
116
117 void PostingListBuilder::finish()
118 {
119         if (pending_deltas.empty()) {
120                 return;
121         }
122
123         assert(!encoded.empty());  // write_header() should already have run.
124
125         // No interleaving for partial blocks.
126         unsigned char buf[P4NENC_BOUND(128)];
127         unsigned char *end = encode_pfor_single_block<128>(pending_deltas.data(), pending_deltas.size(), /*interleaved=*/false, buf);
128         encoded.append(reinterpret_cast<char *>(buf), reinterpret_cast<char *>(end));
129 }
130
131 void PostingListBuilder::append_block()
132 {
133         unsigned char buf[P4NENC_BOUND(128)];
134         assert(pending_deltas.size() == 128);
135         unsigned char *end = encode_pfor_single_block<128>(pending_deltas.data(), 128, /*interleaved=*/true, buf);
136         encoded.append(reinterpret_cast<char *>(buf), reinterpret_cast<char *>(end));
137 }
138
139 void PostingListBuilder::write_header(uint32_t docid)
140 {
141         unsigned char buf[P4NENC_BOUND(1)];
142         unsigned char *end = write_baseval(docid, buf);
143         encoded.append(reinterpret_cast<char *>(buf), end - buf);
144 }
145
146 class DatabaseReceiver {
147 public:
148         virtual ~DatabaseReceiver() = default;
149         virtual void add_file(string filename) = 0;
150         virtual void flush_block() = 0;
151 };
152
153 class DictionaryBuilder : public DatabaseReceiver {
154 public:
155         DictionaryBuilder(size_t blocks_to_keep, size_t block_size)
156                 : blocks_to_keep(blocks_to_keep), block_size(block_size) {}
157         void add_file(string filename) override;
158         void flush_block() override;
159         string train(size_t buf_size);
160
161 private:
162         const size_t blocks_to_keep, block_size;
163         string current_block;
164         uint64_t block_num = 0;
165         size_t num_files_in_block = 0;
166
167         std::mt19937 reservoir_rand{ 1234 };  // Fixed seed for reproducibility.
168         bool keep_current_block = true;
169         int64_t slot_for_current_block = -1;
170
171         vector<string> sampled_blocks;
172         vector<size_t> lengths;
173 };
174
175 void DictionaryBuilder::add_file(string filename)
176 {
177         if (keep_current_block) {  // Only bother saving the filenames if we're actually keeping the block.
178                 if (!current_block.empty()) {
179                         current_block.push_back('\0');
180                 }
181                 current_block += filename;
182         }
183         if (++num_files_in_block == block_size) {
184                 flush_block();
185         }
186 }
187
188 void DictionaryBuilder::flush_block()
189 {
190         if (keep_current_block) {
191                 if (slot_for_current_block == -1) {
192                         lengths.push_back(current_block.size());
193                         sampled_blocks.push_back(move(current_block));
194                 } else {
195                         lengths[slot_for_current_block] = current_block.size();
196                         sampled_blocks[slot_for_current_block] = move(current_block);
197                 }
198         }
199         current_block.clear();
200         num_files_in_block = 0;
201         ++block_num;
202
203         if (block_num < blocks_to_keep) {
204                 keep_current_block = true;
205                 slot_for_current_block = -1;
206         } else {
207                 // Keep every block with equal probability (reservoir sampling).
208                 uint64_t idx = uniform_int_distribution<uint64_t>(0, block_num)(reservoir_rand);
209                 keep_current_block = (idx < blocks_to_keep);
210                 slot_for_current_block = idx;
211         }
212 }
213
214 string DictionaryBuilder::train(size_t buf_size)
215 {
216         string dictionary_buf;
217         sort(sampled_blocks.begin(), sampled_blocks.end());  // Seemingly important for decompression speed.
218         for (const string &block : sampled_blocks) {
219                 dictionary_buf += block;
220         }
221
222         string buf;
223         buf.resize(buf_size);
224         size_t ret = ZDICT_trainFromBuffer(&buf[0], buf_size, dictionary_buf.data(), lengths.data(), lengths.size());
225         if (ret == size_t(-1)) {
226                 return "";
227         }
228         dprintf("Sampled %zu bytes in %zu blocks, built a dictionary of size %zu\n", dictionary_buf.size(), lengths.size(), ret);
229         buf.resize(ret);
230
231         sampled_blocks.clear();
232         lengths.clear();
233
234         return buf;
235 }
236
237 class Corpus : public DatabaseReceiver {
238 public:
239         Corpus(FILE *outfp, size_t block_size, ZSTD_CDict *cdict)
240                 : invindex(new PostingListBuilder *[NUM_TRIGRAMS]), outfp(outfp), block_size(block_size), cdict(cdict)
241         {
242                 fill(invindex.get(), invindex.get() + NUM_TRIGRAMS, nullptr);
243         }
244         ~Corpus() override
245         {
246                 for (unsigned i = 0; i < NUM_TRIGRAMS; ++i) {
247                         delete invindex[i];
248                 }
249         }
250
251         void add_file(string filename) override;
252         void flush_block() override;
253
254         vector<uint64_t> filename_blocks;
255         size_t num_files = 0, num_files_in_block = 0, num_blocks = 0;
256         bool seen_trigram(uint32_t trgm)
257         {
258                 return invindex[trgm] != nullptr;
259         }
260         PostingListBuilder &get_pl_builder(uint32_t trgm)
261         {
262                 if (invindex[trgm] == nullptr) {
263                         invindex[trgm] = new PostingListBuilder;
264                 }
265                 return *invindex[trgm];
266         }
267         size_t num_trigrams() const;
268
269 private:
270         unique_ptr<PostingListBuilder *[]> invindex;
271         FILE *outfp;
272         string current_block;
273         string tempbuf;
274         const size_t block_size;
275         ZSTD_CDict *cdict;
276 };
277
278 void Corpus::add_file(string filename)
279 {
280         ++num_files;
281         if (!current_block.empty()) {
282                 current_block.push_back('\0');
283         }
284         current_block += filename;
285         if (++num_files_in_block == block_size) {
286                 flush_block();
287         }
288 }
289
290 void Corpus::flush_block()
291 {
292         if (current_block.empty()) {
293                 return;
294         }
295
296         uint32_t docid = num_blocks;
297
298         // Create trigrams.
299         const char *ptr = current_block.c_str();
300         while (ptr < current_block.c_str() + current_block.size()) {
301                 string_view s(ptr);
302                 if (s.size() >= 3) {
303                         for (size_t j = 0; j < s.size() - 2; ++j) {
304                                 uint32_t trgm = read_trigram(s, j);
305                                 get_pl_builder(trgm).add_docid(docid);
306                         }
307                 }
308                 ptr += s.size() + 1;
309         }
310
311         // Compress and add the filename block.
312         filename_blocks.push_back(ftell(outfp));
313         string compressed = zstd_compress(current_block, cdict, &tempbuf);
314         if (fwrite(compressed.data(), compressed.size(), 1, outfp) != 1) {
315                 perror("fwrite()");
316                 exit(1);
317         }
318
319         current_block.clear();
320         num_files_in_block = 0;
321         ++num_blocks;
322 }
323
324 size_t Corpus::num_trigrams() const
325 {
326         size_t num = 0;
327         for (unsigned trgm = 0; trgm < NUM_TRIGRAMS; ++trgm) {
328                 if (invindex[trgm] != nullptr) {
329                         ++num;
330                 }
331         }
332         return num;
333 }
334
335 string read_cstr(FILE *fp)
336 {
337         string ret;
338         for (;;) {
339                 int ch = getc(fp);
340                 if (ch == -1) {
341                         perror("getc");
342                         exit(1);
343                 }
344                 if (ch == 0) {
345                         return ret;
346                 }
347                 ret.push_back(ch);
348         }
349 }
350
351 void handle_directory(FILE *fp, DatabaseReceiver *receiver)
352 {
353         db_directory dummy;
354         if (fread(&dummy, sizeof(dummy), 1, fp) != 1) {
355                 if (feof(fp)) {
356                         return;
357                 } else {
358                         perror("fread");
359                 }
360         }
361
362         string dir_path = read_cstr(fp);
363         if (dir_path == "/") {
364                 dir_path = "";
365         }
366
367         for (;;) {
368                 int type = getc(fp);
369                 if (type == DBE_NORMAL) {
370                         string filename = read_cstr(fp);
371                         receiver->add_file(dir_path + "/" + filename);
372                 } else if (type == DBE_DIRECTORY) {
373                         string dirname = read_cstr(fp);
374                         receiver->add_file(dir_path + "/" + dirname);
375                 } else {
376                         return;  // Probably end.
377                 }
378         }
379 }
380
381 void read_plaintext(FILE *fp, DatabaseReceiver *receiver)
382 {
383         if (fseek(fp, 0, SEEK_SET) != 0) {
384                 perror("fseek");
385                 exit(1);
386         }
387
388         while (!feof(fp)) {
389                 char buf[1024];
390                 if (fgets(buf, sizeof(buf), fp) == nullptr) {
391                         break;
392                 }
393                 string s(buf);
394                 assert(!s.empty());
395                 while (s.back() != '\n' && !feof(fp)) {
396                         // The string was longer than the buffer, so read again.
397                         if (fgets(buf, sizeof(buf), fp) == nullptr) {
398                                 break;
399                         }
400                         s += buf;
401                 }
402                 if (!s.empty() && s.back() == '\n')
403                         s.pop_back();
404                 receiver->add_file(move(s));
405         }
406 }
407
408 void read_mlocate(FILE *fp, DatabaseReceiver *receiver)
409 {
410         if (fseek(fp, 0, SEEK_SET) != 0) {
411                 perror("fseek");
412                 exit(1);
413         }
414
415         db_header hdr;
416         if (fread(&hdr, sizeof(hdr), 1, fp) != 1) {
417                 perror("short read");
418                 exit(1);
419         }
420
421         // TODO: Care about the base path.
422         string path = read_cstr(fp);
423         while (!feof(fp)) {
424                 handle_directory(fp, receiver);
425         }
426 }
427
428 string zstd_compress(const string &src, ZSTD_CDict *cdict, string *tempbuf)
429 {
430         static ZSTD_CCtx *ctx = nullptr;
431         if (ctx == nullptr) {
432                 ctx = ZSTD_createCCtx();
433         }
434
435         size_t max_size = ZSTD_compressBound(src.size());
436         if (tempbuf->size() < max_size) {
437                 tempbuf->resize(max_size);
438         }
439         size_t size;
440         if (cdict == nullptr) {
441                 size = ZSTD_compressCCtx(ctx, &(*tempbuf)[0], max_size, src.data(), src.size(), /*level=*/6);
442         } else {
443                 size = ZSTD_compress_usingCDict(ctx, &(*tempbuf)[0], max_size, src.data(), src.size(), cdict);
444         }
445         return string(tempbuf->data(), size);
446 }
447
448 bool is_prime(uint32_t x)
449 {
450         if ((x % 2) == 0 || (x % 3) == 0) {
451                 return false;
452         }
453         uint32_t limit = ceil(sqrt(x));
454         for (uint32_t factor = 5; factor <= limit; ++factor) {
455                 if ((x % factor) == 0) {
456                         return false;
457                 }
458         }
459         return true;
460 }
461
462 uint32_t next_prime(uint32_t x)
463 {
464         if ((x % 2) == 0) {
465                 ++x;
466         }
467         while (!is_prime(x)) {
468                 x += 2;
469         }
470         return x;
471 }
472
473 unique_ptr<Trigram[]> create_hashtable(Corpus &corpus, const vector<uint32_t> &all_trigrams, uint32_t ht_size, uint32_t num_overflow_slots)
474 {
475         unique_ptr<Trigram[]> ht(new Trigram[ht_size + num_overflow_slots + 1]);  // 1 for the sentinel element at the end.
476         for (unsigned i = 0; i < ht_size + num_overflow_slots + 1; ++i) {
477                 ht[i].trgm = uint32_t(-1);
478                 ht[i].num_docids = 0;
479                 ht[i].offset = 0;
480         }
481         for (uint32_t trgm : all_trigrams) {
482                 // We don't know offset yet, so set it to zero.
483                 Trigram to_insert{ trgm, uint32_t(corpus.get_pl_builder(trgm).num_docids), 0 };
484
485                 uint32_t bucket = hash_trigram(trgm, ht_size);
486                 unsigned distance = 0;
487                 while (ht[bucket].num_docids != 0) {
488                         // Robin Hood hashing; reduces the longest distance by a lot.
489                         unsigned other_distance = bucket - hash_trigram(ht[bucket].trgm, ht_size);
490                         if (distance > other_distance) {
491                                 swap(to_insert, ht[bucket]);
492                                 distance = other_distance;
493                         }
494
495                         ++bucket, ++distance;
496                         if (distance > num_overflow_slots) {
497                                 return nullptr;
498                         }
499                 }
500                 ht[bucket] = to_insert;
501         }
502         return ht;
503 }
504
505 class DatabaseBuilder {
506 public:
507         DatabaseBuilder(const char *outfile, int block_size, string dictionary);
508         Corpus *start_corpus();
509         void finish_corpus();
510
511 private:
512         FILE *outfp;
513         Header hdr;
514         const int block_size;
515         steady_clock::time_point corpus_start;
516         Corpus *corpus = nullptr;
517         ZSTD_CDict *cdict = nullptr;
518 };
519
520 DatabaseBuilder::DatabaseBuilder(const char *outfile, int block_size, string dictionary)
521         : block_size(block_size)
522 {
523         umask(0027);
524         outfp = fopen(outfile, "wb");
525         if (outfp == nullptr) {
526                 perror(outfile);
527                 exit(1);
528         }
529
530         // Write the header.
531         memcpy(hdr.magic, "\0plocate", 8);
532         hdr.version = -1;  // Mark as broken.
533         hdr.hashtable_size = 0;  // Not known yet.
534         hdr.extra_ht_slots = num_overflow_slots;
535         hdr.num_docids = 0;
536         hdr.hash_table_offset_bytes = -1;  // We don't know these offsets yet.
537         hdr.max_version = 1;
538         hdr.filename_index_offset_bytes = -1;
539         hdr.zstd_dictionary_length_bytes = -1;
540         fwrite(&hdr, sizeof(hdr), 1, outfp);
541
542         if (dictionary.empty()) {
543                 hdr.zstd_dictionary_offset_bytes = 0;
544                 hdr.zstd_dictionary_length_bytes = 0;
545         } else {
546                 hdr.zstd_dictionary_offset_bytes = ftell(outfp);
547                 fwrite(dictionary.data(), dictionary.size(), 1, outfp);
548                 hdr.zstd_dictionary_length_bytes = dictionary.size();
549                 cdict = ZSTD_createCDict(dictionary.data(), dictionary.size(), /*level=*/6);
550         }
551 }
552
553 Corpus *DatabaseBuilder::start_corpus()
554 {
555         corpus_start = steady_clock::now();
556         corpus = new Corpus(outfp, block_size, cdict);
557         return corpus;
558 }
559
560 void DatabaseBuilder::finish_corpus()
561 {
562         corpus->flush_block();
563         hdr.num_docids = corpus->filename_blocks.size();
564
565         // Stick an empty block at the end as sentinel.
566         corpus->filename_blocks.push_back(ftell(outfp));
567         const size_t bytes_for_filenames = corpus->filename_blocks.back() - corpus->filename_blocks.front();
568
569         // Write the offsets to the filenames.
570         hdr.filename_index_offset_bytes = ftell(outfp);
571         const size_t bytes_for_filename_index = corpus->filename_blocks.size() * sizeof(uint64_t);
572         fwrite(corpus->filename_blocks.data(), corpus->filename_blocks.size(), sizeof(uint64_t), outfp);
573         corpus->filename_blocks.clear();
574         corpus->filename_blocks.shrink_to_fit();
575
576         // Finish up encoding the posting lists.
577         size_t trigrams = 0, longest_posting_list = 0;
578         size_t bytes_for_posting_lists = 0;
579         for (unsigned trgm = 0; trgm < NUM_TRIGRAMS; ++trgm) {
580                 if (!corpus->seen_trigram(trgm))
581                         continue;
582                 PostingListBuilder &pl_builder = corpus->get_pl_builder(trgm);
583                 pl_builder.finish();
584                 longest_posting_list = max(longest_posting_list, pl_builder.num_docids);
585                 trigrams += pl_builder.num_docids;
586                 bytes_for_posting_lists += pl_builder.encoded.size();
587         }
588         size_t num_trigrams = corpus->num_trigrams();
589         dprintf("%zu files, %zu different trigrams, %zu entries, avg len %.2f, longest %zu\n",
590                 corpus->num_files, num_trigrams, trigrams, double(trigrams) / num_trigrams, longest_posting_list);
591         dprintf("%zu bytes used for posting lists (%.2f bits/entry)\n", bytes_for_posting_lists, 8 * bytes_for_posting_lists / double(trigrams));
592
593         dprintf("Building posting lists took %.1f ms.\n\n", 1e3 * duration<float>(steady_clock::now() - corpus_start).count());
594
595         // Find the used trigrams.
596         vector<uint32_t> all_trigrams;
597         for (unsigned trgm = 0; trgm < NUM_TRIGRAMS; ++trgm) {
598                 if (corpus->seen_trigram(trgm)) {
599                         all_trigrams.push_back(trgm);
600                 }
601         }
602
603         // Create the hash table.
604         unique_ptr<Trigram[]> hashtable;
605         uint32_t ht_size = next_prime(all_trigrams.size());
606         for (;;) {
607                 hashtable = create_hashtable(*corpus, all_trigrams, ht_size, num_overflow_slots);
608                 if (hashtable == nullptr) {
609                         dprintf("Failed creating hash table of size %u, increasing by 5%% and trying again.\n", ht_size);
610                         ht_size = next_prime(ht_size * 1.05);
611                 } else {
612                         dprintf("Created hash table of size %u.\n\n", ht_size);
613                         break;
614                 }
615         }
616
617         // Find the offsets for each posting list.
618         size_t bytes_for_hashtable = (ht_size + num_overflow_slots + 1) * sizeof(Trigram);
619         uint64_t offset = ftell(outfp) + bytes_for_hashtable;
620         for (unsigned i = 0; i < ht_size + num_overflow_slots + 1; ++i) {
621                 hashtable[i].offset = offset;  // Needs to be there even for empty slots.
622                 if (hashtable[i].num_docids == 0) {
623                         continue;
624                 }
625
626                 const string &encoded = corpus->get_pl_builder(hashtable[i].trgm).encoded;
627                 offset += encoded.size();
628         }
629
630         // Write the hash table.
631         hdr.hash_table_offset_bytes = ftell(outfp);
632         hdr.hashtable_size = ht_size;
633         fwrite(hashtable.get(), ht_size + num_overflow_slots + 1, sizeof(Trigram), outfp);
634
635         // Write the actual posting lists.
636         for (unsigned i = 0; i < ht_size + num_overflow_slots + 1; ++i) {
637                 if (hashtable[i].num_docids == 0) {
638                         continue;
639                 }
640                 const string &encoded = corpus->get_pl_builder(hashtable[i].trgm).encoded;
641                 fwrite(encoded.data(), encoded.size(), 1, outfp);
642         }
643
644         // Rewind, and write the updated header.
645         hdr.version = 1;
646         fseek(outfp, 0, SEEK_SET);
647         fwrite(&hdr, sizeof(hdr), 1, outfp);
648         fclose(outfp);
649
650         size_t total_bytes = (bytes_for_hashtable + bytes_for_posting_lists + bytes_for_filename_index + bytes_for_filenames);
651
652         dprintf("Block size:     %7d files\n", block_size);
653         dprintf("Dictionary:     %'7.1f MB\n", hdr.zstd_dictionary_length_bytes / 1048576.0);
654         dprintf("Hash table:     %'7.1f MB\n", bytes_for_hashtable / 1048576.0);
655         dprintf("Posting lists:  %'7.1f MB\n", bytes_for_posting_lists / 1048576.0);
656         dprintf("Filename index: %'7.1f MB\n", bytes_for_filename_index / 1048576.0);
657         dprintf("Filenames:      %'7.1f MB\n", bytes_for_filenames / 1048576.0);
658         dprintf("Total:          %'7.1f MB\n", total_bytes / 1048576.0);
659         dprintf("\n");
660 }
661
662 void do_build(const char *infile, const char *outfile, int block_size, bool plaintext)
663 {
664         FILE *infp = fopen(infile, "rb");
665         if (infp == nullptr) {
666                 perror(infile);
667                 exit(1);
668         }
669
670         // Train the dictionary by sampling real blocks.
671         // The documentation for ZDICT_trainFromBuffer() claims that a reasonable
672         // dictionary size is ~100 kB, but 1 kB seems to actually compress better for us,
673         // and decompress just as fast.
674         DictionaryBuilder builder(/*blocks_to_keep=*/1000, block_size);
675         if (plaintext) {
676                 read_plaintext(infp, &builder);
677         } else {
678                 read_mlocate(infp, &builder);
679         }
680         string dictionary = builder.train(1024);
681
682         DatabaseBuilder db(outfile, block_size, dictionary);
683         Corpus *corpus = db.start_corpus();
684         if (plaintext) {
685                 read_plaintext(infp, corpus);
686         } else {
687                 read_mlocate(infp, corpus);
688         }
689         fclose(infp);
690
691         dprintf("Read %zu files from %s\n", corpus->num_files, infile);
692         db.finish_corpus();
693 }
694
695 void usage()
696 {
697         printf(
698                 "Usage: plocate-build MLOCATE_DB PLOCATE_DB\n"
699                 "\n"
700                 "Generate plocate index from mlocate.db, typically /var/lib/mlocate/mlocate.db.\n"
701                 "Normally, the destination should be /var/lib/mlocate/plocate.db.\n"
702                 "\n"
703                 "  -b, --block-size SIZE  number of filenames to store in each block (default 32)\n"
704                 "  -p, --plaintext        input is a plaintext file, not an mlocate database\n"
705                 "      --help             print this help\n"
706                 "      --version          print version information\n");
707 }
708
709 void version()
710 {
711         printf("plocate-build %s\n", PLOCATE_VERSION);
712         printf("Copyright 2020 Steinar H. Gunderson\n");
713         printf("License GPLv2+: GNU GPL version 2 or later <https://gnu.org/licenses/gpl.html>.\n");
714         printf("This is free software: you are free to change and redistribute it.\n");
715         printf("There is NO WARRANTY, to the extent permitted by law.\n");
716 }
717
718 int main(int argc, char **argv)
719 {
720         static const struct option long_options[] = {
721                 { "block-size", required_argument, 0, 'b' },
722                 { "plaintext", no_argument, 0, 'p' },
723                 { "help", no_argument, 0, 'h' },
724                 { "version", no_argument, 0, 'V' },
725                 { "debug", no_argument, 0, 'D' },  // Not documented.
726                 { 0, 0, 0, 0 }
727         };
728
729         int block_size = 32;
730         bool plaintext = false;
731
732         setlocale(LC_ALL, "");
733         for (;;) {
734                 int option_index = 0;
735                 int c = getopt_long(argc, argv, "b:hpVD", long_options, &option_index);
736                 if (c == -1) {
737                         break;
738                 }
739                 switch (c) {
740                 case 'b':
741                         block_size = atoi(optarg);
742                         break;
743                 case 'p':
744                         plaintext = true;
745                         break;
746                 case 'h':
747                         usage();
748                         exit(0);
749                 case 'V':
750                         version();
751                         exit(0);
752                 case 'D':
753                         use_debug = true;
754                         break;
755                 default:
756                         exit(1);
757                 }
758         }
759
760         if (argc - optind != 2) {
761                 usage();
762                 exit(1);
763         }
764
765         do_build(argv[optind], argv[optind + 1], block_size, plaintext);
766         exit(EXIT_SUCCESS);
767 }