Added necessary myarray.{c,h} files.
[ctodo.git] / todo.c
blob4b854121b8df26b391127a8c6fa26b4b23089cd6
1 #include <myarray.h>
2 #include <sqlite3.h>
3 #include <stdio.h>
4 #include <readline/readline.h>
5 #include <readline/history.h>
6 #include <stdlib.h>
7 #include <string.h>
9 MArray tokenize(char *string, char *delimiter) {
10 MArray tokens = myarray_new(5, 5, sizeof(char *));
12 char *temp;
13 char *substring;
14 while ((temp = strstr(string, delimiter)) != NULL) {
15 substring = malloc((temp - string + 1) * sizeof(char));
16 strncpy(substring, string, temp-string);
17 substring[temp-string] = '\0';
18 myarray_append(tokens, substring);
19 string = temp + strlen(delimiter);
22 if (strlen(string)) {
23 substring = malloc((strlen(string) + 1) * sizeof(char));
24 strcpy(substring, string);
25 myarray_append(tokens, substring);
28 return tokens;
31 void free_tokens(MArray tokens) {
32 int i;
33 for (i = 0; i < tokens->len; i++) {
34 free(myarray_get(tokens, char *, i));
37 myarray_free(tokens);
40 int command_prompt(sqlite3 *db) {
41 int retVal = 0;
42 char *line;
43 char *token;
45 line = readline("todo> ");
46 add_history(line);
48 if (!line || !strlen(line)) {
49 printf("\n");
50 return 1;
53 MArray tokens = tokenize(line, " ");
54 token = myarray_get(tokens, char *, 0);
56 if (!strcmp(token, "quit")) {
57 retVal = quit(db, tokens);
58 } else if (!strcmp(token, "list")) {
59 retVal = list(db, tokens);
60 } else if (!strcmp(token, "help")) {
61 retVal = help(db, tokens);
62 } else if (!strcmp(token, "show")) {
63 retVal = show(db, tokens);
64 } else {
65 printf("Unknown command %s\n", token);
66 remove_history(where_history());
69 free(line);
70 free_tokens(tokens);
72 return retVal;
75 int main(int argc, char **argv) {
76 int retVal;
77 sqlite3 *db;
78 char *errmsg;
80 retVal = sqlite3_open("todo.db", &db);
82 if (retVal != SQLITE_OK) {
83 printf("Couldn't open the database file: %s\n", sqlite3_errmsg(db));
86 retVal = sqlite3_exec(db,
87 "CREATE TABLE IF NOT EXISTS todo \
88 (key INTEGER PRIMARY KEY ASC ON CONFLICT ABORT AUTOINCREMENT,\
89 description STRING,\
90 createdDate INTEGER,\
91 dueDate INTEGER,\
92 parent INTEGER REFERENCES todo (key));"
93 , NULL, NULL, &errmsg);
95 if (retVal != SQLITE_OK) {
96 printf("Couldn't create the table for this application: %s\n", errmsg);
99 sqlite3_free(errmsg);
101 while (!command_prompt(db)) {};
103 return 0;