Added an "add" command.
[ctodo.git] / todo.c
blob5919ddc97e86c519fceb19d5596d8a2b587e66d3
1 #include <commands.h>
2 #include <myarray.h>
3 #include <sqlite3.h>
4 #include <stdio.h>
5 #include <readline/history.h>
6 #include <readline/readline.h>
7 #include <stdlib.h>
8 #include <string.h>
10 MArray tokenize(char *string, char *delimiter) {
11 MArray tokens = myarray_new(5, 5, sizeof(char *));
13 char *temp;
14 char *substring;
15 while ((temp = strstr(string, delimiter)) != NULL) {
16 substring = malloc((temp - string + 1) * sizeof(char));
17 strncpy(substring, string, temp-string);
18 substring[temp-string] = '\0';
19 myarray_append(tokens, substring);
20 string = temp + strlen(delimiter);
23 if (strlen(string)) {
24 substring = malloc((strlen(string) + 1) * sizeof(char));
25 strcpy(substring, string);
26 myarray_append(tokens, substring);
29 return tokens;
32 void free_tokens(MArray tokens) {
33 int i;
34 for (i = 0; i < tokens->len; i++) {
35 free(myarray_get(tokens, char *, i));
38 myarray_free(tokens);
41 int command_prompt(sqlite3 *db) {
42 int retVal = 0;
43 char *line;
44 char *token;
46 line = readline("todo> ");
47 add_history(line);
49 if (!line || !strlen(line)) {
50 printf("\n");
51 return 1;
54 MArray tokens = tokenize(line, " ");
55 token = myarray_get(tokens, char *, 0);
57 if (!strcmp(token, "quit")) {
58 retVal = quit(db, tokens);
59 } else if (!strcmp(token, "list")) {
60 retVal = list(db, tokens);
61 } else if (!strcmp(token, "help")) {
62 retVal = help(db, tokens);
63 } else if (!strcmp(token, "show")) {
64 retVal = show(db, tokens);
65 } else if (!strcmp(token, "del")) {
66 retVal = del(db, tokens);
67 } else if (!strcmp(token, "add")) {
68 retVal = add(db, tokens);
69 } else {
70 printf("Unknown command %s\n", token);
71 remove_history(where_history());
74 free(line);
75 free_tokens(tokens);
77 return retVal;
80 int main(int argc, char **argv) {
81 int retVal;
82 sqlite3 *db;
83 char *errmsg;
85 sqlite3_initialize();
87 retVal = sqlite3_open_v2("todo.db", &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
89 if (retVal != SQLITE_OK) {
90 printf("Couldn't open the database file: %s\n", sqlite3_errmsg(db));
93 retVal = sqlite3_exec(db,
94 "CREATE TABLE IF NOT EXISTS todo \
95 (key INTEGER PRIMARY KEY ASC ON CONFLICT ABORT AUTOINCREMENT,\
96 description STRING,\
97 createdDate INTEGER,\
98 dueDate INTEGER DEFAULT NULL,\
99 done INTEGER,\
100 parent INTEGER REFERENCES todo (key));"
101 , NULL, NULL, &errmsg);
103 if (retVal != SQLITE_OK) {
104 printf("Couldn't create the table for this application: %s\n", errmsg);
107 sqlite3_free(errmsg);
109 while (!command_prompt(db)) {};
111 sqlite3_close(db);
112 sqlite3_shutdown();
114 return 0;