aboutsummaryrefslogtreecommitdiff
path: root/src/main.c
blob: 2f85c4410dfc163deab058aa545c82f6be3ba3d1 (plain)
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
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <sqlite3.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/sendfile.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>

#define DATABASE_PATH (FTAG_ROOT "/ftag.sqlite3")

struct ftag_command {
	const char *name;
	void (*func)(int argc, char **argv);
};

/* Parse arguments using an array of available commands. ARGV[0] has to match
 * the "name" field of an entry of COMMANDS. */
static void parse_args(int argc,
		       char ** argv,
		       const struct ftag_command *commands,
		       int command_count);

static void __sqlite3_check(int rc, sqlite3 *db, const char *file, int line, const char *func)
{
	if (rc == SQLITE_OK)
		return;

	fprintf(stderr, "%s:%d: %s: %s\n", file, line, func, sqlite3_errmsg(db));
	sqlite3_close(db);
	exit(EXIT_FAILURE);
}

#define sqlite3_check(RC, DB) __sqlite3_check(RC, DB, __FILE__, __LINE__, __func__)

static int file_exists(const char *path)
{
	struct stat statbuf __attribute__((unused));
	int rc = stat(path, &statbuf);
	if (rc == 0)
		return 1;
	else
		return 0;
}

static void assert_db_exists(void)
{
	errno = 0;
	if (file_exists(DATABASE_PATH) && (errno == 0))
		return;

	if (errno == ENOENT) {
		fprintf(stderr,
			"ftag: database not found at \"%s\", "
			"have you run \"ftag init\"?\n",
			DATABASE_PATH);
	}
	else {
		perror(DATABASE_PATH);
	}
	exit(EXIT_FAILURE);
}

/* Make sure STR contains no single quote, not to break SQL queries. */
static void assert_no_single_quote(const char *str)
{
	assert(strchr(str, '\'') == NULL);
	assert(strchr(str, ';') == NULL);
}

static int table_next_id_callback(void *_id, int, char **cols, char **)
{
	int *id = _id;
	if (cols[0])
		*id = atoi(cols[0]);
	else
		*id = 0;
	return 0;
}

static int table_next_id(sqlite3 *db, const char *table)
{
	int last_id = -1;
	int rc;
	char sql[128];
	memset(sql, 0, sizeof(sql));
	snprintf(sql, sizeof(sql)-1, "SELECT MAX(id) FROM %s;", table);
	rc = sqlite3_exec(db, sql, table_next_id_callback, &last_id, NULL);
	sqlite3_check(rc, db);
	assert(last_id >= 0);
	printf("%s: debug: last if for table \"%s\" is %d\n", __func__, table, last_id);
	return last_id + 1;
}

static void ftag_init(int, char **)
{
	int rc = mkdir(FTAG_ROOT "/files", 0755);
	if (rc == -1) {
		perror(FTAG_ROOT "/files");
		exit(EXIT_FAILURE);
	}
	char cmd[1024];
	memset(cmd, 0, sizeof(cmd));
	snprintf(cmd, sizeof(cmd)-1,
		 "sqlite3 %s < %s", DATABASE_PATH, FTAG_ROOT "/sql/init.sql");
	execl("/usr/bin/sh", "/usr/bin/sh", "-c", cmd, NULL);
	perror("exec");
	exit(EXIT_FAILURE);
}

static int ftag_print(void *, int, char **cols, char **)
{
	assert(cols[0]);
	printf("%s\n", cols[0]);
	return 0;
}

static void ftag_list_table(const char *table, const char *col)
{
	char sql[64];
	sqlite3 *db = NULL;
	int rc;
	rc = sqlite3_open(DATABASE_PATH, &db);
	sqlite3_check(rc, db);
	memset(sql, 0, sizeof(sql));
	snprintf(sql, sizeof(sql)-1, "SELECT %s FROM %s;", col, table);
	rc = sqlite3_exec(db, sql, ftag_print, NULL, NULL);
	sqlite3_check(rc, db);
	sqlite3_close(db);
}

/* Write to OUT a version of IN that does not contain any blank or uppercase
 * letter. */
static void canonicalize(char *out, const char *in)
{
	int i;
	for (i = 0; i < strlen(in); i++) {
		if (in[i] >= 'A' && in[i] <= 'Z')
			out[i] = in[i] - 'A' + 'a';
		else if (in[i] == ' ')
			out[i] = '_';
		else
			out[i] = in[i];
	}
	out[i] = '\0';
}

static void ftag_add_one_file(sqlite3 *db,
			      int *next_id,
			      const char *file)
{
	char sql[2048];
	int rc;
	char *full_name = NULL;
	char *canonical_name = NULL;
	char *description =  NULL;
	char *date = NULL;
	size_t line_len = 0;
	ssize_t read_len;

	if (!file_exists(file)) {
		perror(file);
		exit(EXIT_FAILURE);
	}

	printf("ftag file add: adding file \"%s\" to database\n", file);
	
	printf("Enter the full name, a version of the name that\n"
	       "may contain blanks and every type of character.\n");
	read_len = getline(&full_name, &line_len, stdin);
	if (read_len == -1) {
		perror("getline");
		exit(EXIT_FAILURE);
	}
	assert_no_single_quote(full_name);
	full_name[read_len-1] = '\0';

	line_len = read_len+1;
	canonical_name = malloc(line_len);
	canonicalize(canonical_name, full_name);

	printf("Enter the canonical name, a version of the name that\n"
	       "ideally contains no blank and, if possible, no upper\n"
	       "case letters and no symbols. If no input is given,\n"
	       "canonical name will be \"%s\".\n", canonical_name);
	read_len = getline(&canonical_name, &line_len, stdin);
	if (read_len == -1) {
		perror("getline");
		exit(EXIT_FAILURE);
	}
	if (canonical_name[0] == '\n')
		canonicalize(canonical_name, full_name);
	else
		canonical_name[read_len-1] = '\0';
	assert_no_single_quote(canonical_name);

	printf("Enter the description.\n");
	line_len = 0;
	read_len = getline(&description, &line_len, stdin);
	if (read_len == -1) {
		perror("getline");
		exit(EXIT_FAILURE);
	}
	if (!description)
		description = strdup("");
	else
		description[read_len-1] = '\0';
	assert_no_single_quote(description);

	line_len = 32;
	date = malloc(line_len);
	time_t now = time(NULL);
	struct tm *now_tm = localtime(&now);
	strftime(date, line_len-1, "%Y-%m-%d", now_tm);
	printf("Enter the date in the format YYYY-MM-DD. If no input is\n"
	       "given, date will be \"%s\".\n", date);
	read_len = getline(&date, &line_len, stdin);
	if (read_len == -1) {
		perror("getline");
		exit(EXIT_FAILURE);
	}
	if (date[0] == '\n')
		strftime(date, line_len-1, "%Y-%m-%d", now_tm);
	else
		date[read_len-1] = '\0';

	memset(sql, 0, sizeof(sql));
	snprintf(sql, sizeof(sql)-1,
		 "INSERT INTO files VALUES(%d, '%s', '%s', '%s', '%s')",
		 *next_id, canonical_name, full_name, description, date);
	rc = sqlite3_exec(db, sql, NULL, NULL, NULL);
	sqlite3_check(rc, db);
	(*next_id)++;

	char new_path[512];
	memset(new_path, 0, sizeof(new_path));
	snprintf(new_path, sizeof(new_path)-1,
		 "%s/files/%s", FTAG_ROOT, canonical_name);
	int out_fd = open(new_path, O_WRONLY | O_CREAT, 0644);

	if (out_fd == -1) {
		perror("open");
		exit(EXIT_FAILURE);
	}

	int in_fd = open(file, O_RDONLY);

	if (in_fd == -1) {
		perror("open");
		exit(EXIT_FAILURE);
	}

	ssize_t written_bytes;
	while ((written_bytes = sendfile(out_fd, in_fd, NULL, 4096)) == 4096)
		;

	if (written_bytes == -1) {
		perror("sendfile");
		exit(EXIT_FAILURE);
	}

	close(in_fd);
	close(out_fd);
	free(full_name);
	free(canonical_name);
	free(description);
}

/* Add new files to the database. */
static void ftag_file_add(int argc, char **argv)
{
	if (argc == 0) {
		fprintf(stderr, "ftag file add: must supply file names\n");
		exit(EXIT_FAILURE);
	}
	sqlite3 *db = NULL;
	int rc;
	rc = sqlite3_open(DATABASE_PATH, &db);
	sqlite3_check(rc, db);
	int next_id = table_next_id(db, "files");
	for (int i = 0; i < argc; i++)
		ftag_add_one_file(db, &next_id, argv[i]);
	sqlite3_close(db);
}

static void ftag_file_list(int argc, char **argv)
{
	ftag_list_table("files", "full_name");
}

static int get_id_by_col_callback(void *_id, int, char **cols, char **)
{
	int *id = _id;
	if (cols[0]) {
		*id = atoi(cols[0]);
		return 0;
	}
	else {
		return 1;
	}
}

static int get_id_by_col(sqlite3 *db,
			 const char *table,
			 const char *col,
			 const char *val)
{
	int id = -1;
	char sql[128];
	memset(sql, 0, sizeof(sql));
	snprintf(sql, sizeof(sql)-1,
		 "SELECT id FROM %s WHERE %s = '%s';", table, col, val);
	int rc = sqlite3_exec(db, sql, get_id_by_col_callback, &id, NULL);
	sqlite3_check(rc, db);
	assert(id >= 0);
	return id;
}

static void ftag_file_tag(int argc, char **argv)
{
	if (argc < 2) {
		fprintf(stderr,
			"ftag file tag: must supply a file name and tags\n");
		exit(EXIT_FAILURE);
	}
	const char *file = argv[0];
	char sql[64];
	sqlite3 *db;
	int rc = sqlite3_open(DATABASE_PATH, &db);
	sqlite3_check(rc, db);
	int file_id = get_id_by_col(db, "files", "canonical_name", file);
	printf("%s: debug: file id is %d\n", __func__, file_id);
	for (int i = 1; i < argc; i++) {
		int tag_id = get_id_by_col(db, "tags", "name", argv[i]);
		printf("%s: debug: tag id is %d\n", __func__, tag_id);
		memset(sql, 0, sizeof(sql));
		snprintf(sql, sizeof(sql)-1,
			 "INSERT INTO file_tags values(%d, %d);",
			 file_id, tag_id);
		rc = sqlite3_exec(db, sql, NULL, NULL, NULL);
		sqlite3_check(rc, db);
	}
	sqlite3_close(db);
}

static void ftag_file(int argc, char **argv)
{
	assert_db_exists();
	const struct ftag_command file_commands[] = {
		{.name = "add", .func = ftag_file_add},
		{.name = "list", .func = ftag_file_list},
		{.name = "tag", .func = ftag_file_tag}
	};
	const int file_command_count = sizeof(file_commands)/ sizeof(struct ftag_command);
	parse_args(argc, argv, file_commands, file_command_count);
}

static void ftag_help(int, char **)
{
	printf("Usage: ftag COMMAND [COMMAND-ARG]...\n");
	printf("Available values for COMMAND:\n");
	printf("  init    initialize the database\n");
	printf("  file    manage files");
	printf("  help    print this message\n");
	printf("  tag     manage tags\n");
	printf("Configuration:\n");
	printf("  database path    %s\n", DATABASE_PATH);
	printf("  ftag root        %s\n", FTAG_ROOT);
}

static void ftag_query_usage(void)
{
	fprintf(stderr, "usage: ftag query [-a DATE] [-b DATE] [-t TAG]...\n");
}

static int print_all_callback(void *_print_header, int count, char **cols, char **col_names)
{
	int *print_header = _print_header;
	if (*print_header) {
		for (int i = 0; i < count; i++) {
			printf("%s\t", col_names[i]);
		}
		printf("\n");
		*print_header = 0;
	}
	for (int i = 0; i < count; i++) {
		printf("%s\t", cols[i]);
	}
	printf("\n");
	return 0;
}

/* Build the "join" part of the SQL query for the "ftag query" command. */
static void ftag_query_join(sqlite3 *db, char *sql, int max_len,
			    char **tags, int tag_count)
{
	assert(tag_count >= 0);
	if (tag_count == 0) {
		strncat(sql, "\t(SELECT id,canonical_name,full_name FROM files)\n",
			max_len - strlen(sql));
		assert(strlen(sql) <= max_len);
		return;
	}
	char *prefix = "\t(SELECT id,canonical_name,full_name FROM file_tags JOIN\n";
	strncat(sql, prefix, max_len - strlen(sql));
	assert(strlen(sql) <= max_len);
	ftag_query_join(db, sql, max_len, tags, tag_count-1);
	char suffix[128];
	memset(suffix, 0, sizeof(suffix));
	snprintf(suffix, sizeof(suffix)-1,
		 "\t\tON id = file\n\t\tWHERE tag = %d)\n", tag_count-1);
	strncat(sql, suffix, max_len - strlen(sql));
	assert(strlen(sql) <= max_len);
}

static void ftag_query(int argc, char **argv)
{
	if (argc == 0) {
		ftag_query_usage();
		exit(EXIT_FAILURE);
	}
	char *after_date;
	char *before_date;
	char **tags;
	int tag_count = 0;
	while (argc > 0) {
		if (strcmp(argv[0], "-a") == 0) {
			assert(argc >= 2);
			after_date = argv[1];
		}
		else if (strcmp(argv[0], "-b") == 0) {
			assert(argc >= 2);
			before_date = argv[1];
		}
		else if (strcmp(argv[0], "-t") == 0) {
			assert(argc >= 2);
			tag_count++;
			tags = realloc(tags, tag_count*sizeof(*tags));
			tags[tag_count-1] = argv[1];
		}
		else {
			fprintf(stderr, "ftag query: bad option \"%s\"\n", argv[0]);
			ftag_query_usage();
			exit(EXIT_FAILURE);
		}
		argc -= 2;
		argv += 2;
	}
	char sql[4096];
	sqlite3 *db;
	int rc;
	rc = sqlite3_open(DATABASE_PATH, &db);
	sqlite3_check(rc, db);
	char sql_join[2048];
	memset(sql_join, 0, sizeof(sql_join));
	ftag_query_join(db, sql_join, sizeof(sql_join)-1, tags, tag_count);
	memset(sql, 0, sizeof(sql));
	snprintf(sql, sizeof(sql)-1,
		 "SELECT id,canonical_name,full_name FROM (\n%s);\n", sql_join);
	printf("%s: debug: SQL query is:\n%s", __func__, sql);
	int print_header = 1;
	rc = sqlite3_exec(db, sql, print_all_callback, &print_header, NULL);
	sqlite3_check(rc, db);
	sqlite3_close(db);
}

/* Check that the tag we are trying to create does not exist yet. If this
 * callback is ever called, then it already exist, this is a fatal error. */
static int ftag_tag_check(void *, int, char **cols, char **)
{
	assert(cols[0]);
	assert(cols[1]);
	fprintf(stderr,
		"ftag tag add: error: tag \"%s\" already exists, its description is:\n",
		cols[0]);
	fprintf(stderr, "%s\n", cols[1]);
	return 1;
}

static void ftag_tag_add(int argc, char **argv)
{
	if (argc != 2) {
		fprintf(stderr,
			"ftag tag add: error: must supply two arguments, "
			"the tag name and its description\n");
		exit(EXIT_FAILURE);
	}
	const char *new_tag_name = argv[0];
	assert(strlen(new_tag_name) <= 255);
	assert_no_single_quote(new_tag_name);

	char sql[1024];
	sqlite3 *db = NULL;
	int rc;

	rc = sqlite3_open(DATABASE_PATH, &db);
	sqlite3_check(rc, db);

	memset(sql, 0, sizeof(sql));
	snprintf(sql, sizeof(sql)-1,
		 "SELECT name, description FROM tags WHERE name = '%s';", new_tag_name);
	rc = sqlite3_exec(db, sql, ftag_tag_check, NULL, NULL);
	sqlite3_check(rc, db);

	int next_id = table_next_id(db, "tags");
	const char *new_tag_desc = argv[1];
	assert(strlen(new_tag_desc) <= 600);
	assert_no_single_quote(new_tag_desc);
	memset(sql, 0, sizeof(sql));
	snprintf(sql, sizeof(sql)-1,
		 "INSERT INTO tags VALUES(%d, '%s', '%s');",
		 next_id, new_tag_name, new_tag_desc);
	rc = sqlite3_exec(db, sql, NULL, NULL, NULL);
	sqlite3_check(rc, db);
	sqlite3_close(db);
}

static void ftag_tag_list(int argc, char **argv)
{
	ftag_list_table("tags", "name");
}

static void ftag_tag(int argc, char **argv)
{
	assert_db_exists();
	const struct ftag_command tag_commands[] = {
		{.name = "add",  .func = ftag_tag_add},
		{.name = "list", .func = ftag_tag_list}
	};
	int tag_command_count = sizeof(tag_commands) / sizeof(struct ftag_command);
	parse_args(argc, argv, tag_commands, tag_command_count);
}

static void parse_args(int argc,
		       char **argv,
		       const struct ftag_command *commands,
		       int command_count)
{
	assert(argc > 0);
	assert(command_count > 0);
	for (int i = 0; i < command_count; i++) {
		if (strcmp(argv[0], commands[i].name) == 0) {
			commands[i].func(argc-1, argv+1);
			return;
		}
	}

	fprintf(stderr, "ftag: command \"%s\" unknown\n", argv[0]);
	exit(EXIT_FAILURE);
}

int main(int argc, char *argv[])
{
	if (argc == 1) {
		ftag_help(0, NULL);
		exit(EXIT_FAILURE);
	}

	const struct ftag_command toplevel_commands[] = {
		{.name = "init",  .func = ftag_init},
		{.name = "file",  .func = ftag_file},
		{.name = "help",  .func = ftag_help},
		{.name = "query", .func = ftag_query},
		{.name = "tag",   .func = ftag_tag}
	};
	const int toplevel_command_count = sizeof(toplevel_commands) / sizeof(struct ftag_command);
	parse_args(argc-1, argv+1, toplevel_commands, toplevel_command_count);
	return EXIT_SUCCESS;
}