Blob


1 /*
2 * Copyright (c) 2022 Omar Polo <op@omarpolo.com>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include <err.h>
18 #include <fcntl.h>
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <string.h>
22 #include <unistd.h>
24 #include "db.h"
25 #include "dictionary.h"
27 #include "mkftsidx.h"
29 enum {
30 MODE_FILES,
31 MODE_SQLPORTS,
32 MODE_WIKI,
33 };
35 char *
36 xstrdup(const char *s)
37 {
38 char *t;
40 if (s == NULL)
41 return NULL;
43 if ((t = strdup(s)) == NULL)
44 err(1, "strdup");
45 return t;
46 }
48 __dead void
49 usage(void)
50 {
51 fprintf(stderr, "usage: %s [-o dbpath] [-m f|p|w] [file ...]\n",
52 getprogname());
53 exit(1);
54 }
56 int
57 main(int argc, char **argv)
58 {
59 struct dictionary dict;
60 struct db_entry *entries = NULL;
61 const char *dbpath = NULL;
62 FILE *fp;
63 size_t i, len = 0;
64 int ch, r = 0, mode = MODE_SQLPORTS;
66 #ifndef PROFILE
67 /* sqlite needs flock */
68 if (pledge("stdio rpath wpath cpath flock", NULL) == -1)
69 err(1, "pledge");
70 #endif
72 while ((ch = getopt(argc, argv, "m:o:")) != -1) {
73 switch (ch) {
74 case 'm':
75 switch (*optarg) {
76 case 'f':
77 mode = MODE_FILES;
78 break;
79 case 'p':
80 mode = MODE_SQLPORTS;
81 break;
82 case 'w':
83 mode = MODE_WIKI;
84 break;
85 default:
86 usage();
87 }
88 break;
89 case 'o':
90 dbpath = optarg;
91 break;
92 default:
93 usage();
94 }
95 }
96 argc -= optind;
97 argv += optind;
99 if (dbpath == NULL)
100 dbpath = "db";
102 if (!dictionary_init(&dict))
103 err(1, "dictionary_init");
105 if (mode == MODE_FILES)
106 r = idx_files(&dict, &entries, &len, argc, argv);
107 else if (mode == MODE_SQLPORTS)
108 r = idx_ports(&dict, &entries, &len, argc, argv);
109 else
110 r = idx_wiki(&dict, &entries, &len, argc, argv);
112 if (r == 0) {
113 if ((fp = fopen(dbpath, "w+")) == NULL)
114 err(1, "can't open %s", dbpath);
115 if (db_create(fp, &dict, entries, len) == -1) {
116 warn("db_create");
117 unlink(dbpath);
118 r = 1;
120 fclose(fp);
123 for (i = 0; i < len; ++i) {
124 free(entries[i].name);
125 free(entries[i].descr);
127 free(entries);
128 dictionary_free(&dict);
130 return r;