Since every command now has its own help, I decided to point the user to
[ctodo.git] / todo.c
blob042a45793960db835af41f032ca40fffc2a2c176
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;
45 MArray tokens;
47 line = readline("todo> ");
48 add_history(line);
50 if (!line || !strlen(line)) {
51 printf("\n");
52 return 1;
55 tokens = tokenize(line, " ");
56 token = myarray_get(tokens, char *, 0);
58 if (!strcmp(token, "quit")) {
59 retVal = quit(db, tokens);
60 } else if (!strcmp(token, "list")) {
61 retVal = list(db, tokens);
62 } else if (!strcmp(token, "help")) {
63 retVal = help(db, tokens);
64 } else if (!strcmp(token, "show")) {
65 retVal = show(db, tokens);
66 } else if (!strcmp(token, "del")) {
67 retVal = del(db, tokens);
68 } else if (!strcmp(token, "add")) {
69 retVal = add(db, tokens);
70 } else if (!strcmp(token, "mark")) {
71 retVal = mark(db, tokens);
72 } else {
73 printf("Unknown command %s\n", token);
74 remove_history(where_history());
77 free(line);
78 free_tokens(tokens);
80 return retVal;
83 int main(int argc, char **argv) {
84 int retVal;
85 sqlite3 *db;
86 char *errmsg;
88 sqlite3_initialize();
90 retVal = sqlite3_open_v2("todo.db", &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
92 if (retVal != SQLITE_OK) {
93 printf("Couldn't open the database file: %s\n", sqlite3_errmsg(db));
96 retVal = sqlite3_exec(db,
97 "CREATE TABLE IF NOT EXISTS todo \
98 (key INTEGER PRIMARY KEY ASC ON CONFLICT ABORT AUTOINCREMENT,\
99 description STRING,\
100 createdDate INTEGER,\
101 dueDate INTEGER DEFAULT NULL,\
102 done INTEGER,\
103 parent INTEGER REFERENCES todo (key) CHECK (key != parent));"
104 , NULL, NULL, &errmsg);
106 if (retVal != SQLITE_OK) {
107 printf("Couldn't create the table for this application: %s\n", errmsg);
108 sqlite3_free(errmsg);
109 sqlite3_close(db);
110 sqlite3_shutdown();
111 return 1;
114 sqlite3_free(errmsg);
116 while (!command_prompt(db)) {};
118 sqlite3_close(db);
119 sqlite3_shutdown();
121 return 0;