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_SQLPORTS,
31 MODE_WIKI,
32 };
34 char *
35 xstrdup(const char *s)
36 {
37 char *t;
39 if (s == NULL)
40 return NULL;
42 if ((t = strdup(s)) == NULL)
43 err(1, "strdup");
44 return t;
45 }
47 __dead void
48 usage(void)
49 {
50 fprintf(stderr, "usage: %s [-o dbpath] [-m p|w] [path]\n",
51 getprogname());
52 exit(1);
53 }
55 int
56 main(int argc, char **argv)
57 {
58 struct dictionary dict;
59 struct db_entry *entries = NULL;
60 const char *dbpath = NULL;
61 FILE *fp;
62 size_t i, len = 0;
63 int ch, r = 0, mode = MODE_SQLPORTS;
65 #ifndef PROFILE
66 /* sqlite needs flock */
67 if (pledge("stdio rpath wpath cpath flock", NULL) == -1)
68 err(1, "pledge");
69 #endif
71 while ((ch = getopt(argc, argv, "m:o:")) != -1) {
72 switch (ch) {
73 case 'm':
74 switch (*optarg) {
75 case 'p':
76 mode = MODE_SQLPORTS;
77 break;
78 case 'w':
79 mode = MODE_WIKI;
80 break;
81 default:
82 usage();
83 }
84 break;
85 case 'o':
86 dbpath = optarg;
87 break;
88 default:
89 usage();
90 }
91 }
92 argc -= optind;
93 argv += optind;
95 if (dbpath == NULL)
96 dbpath = "db";
98 if (!dictionary_init(&dict))
99 err(1, "dictionary_init");
101 if (mode == MODE_SQLPORTS)
102 r = idx_ports(&dict, &entries, &len, argc, argv);
103 else
104 r = idx_wiki(&dict, &entries, &len, argc, argv);
106 if (r == 0) {
107 if ((fp = fopen(dbpath, "w+")) == NULL)
108 err(1, "can't open %s", dbpath);
109 if (db_create(fp, &dict, entries, len) == -1) {
110 warn("db_create");
111 unlink(dbpath);
112 r = 1;
114 fclose(fp);
117 for (i = 0; i < len; ++i) {
118 free(entries[i].name);
119 free(entries[i].descr);
121 free(entries);
122 dictionary_free(&dict);
124 return r;