-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtasklib.c
526 lines (479 loc) · 13.9 KB
/
tasklib.c
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
/* Using strdup, strndup & strcasecmp, need POSIX 2008 */
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <unistd.h>
#include <pwd.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/stat.h>
#include <errno.h>
#include <dirent.h>
#include "tasklib.h"
#include "tasklist.h"
/*
* Private helper functions
*/
/**
* Returns whether the path ends with a slash.
*
* @param path The path to check
* @return 0 if there is no trailing slash
*/
static int has_trailing_slash(const char *path) {
// Iterate over string until we find the end
while (*path != '\0') ++path;
// Compare last character (before terminator) with slash
return *(path - 1) == '/';
}
/**
* Converts a position string to long, handling all possible errors.
*
* @param posarg The string position to convert
* @return The position as a long or -1 on error
*/
static long strtopos(const char *posarg) {
// Reset errno to use it for strtol error checking
errno = 0;
// Will point to first character that is not a digit
char *endptr;
long position = strtol(posarg, &endptr, 10);
// Handle conversion error
if (errno || *endptr != '\0') {
return -1;
}
return position;
}
/**
* Returns the name of a task list based on its filename.
*
* It works by simply returning a copy without the extension.
* Because a new string needs to be allocated, the user must free it.
*
* @param path The list's filename
* @return The list name (freed by user)
*/
static char *filename_to_name(const char *filename) {
// Find the last dot
const char *name_end = strrchr(filename, '.');
// Get number of characters in the name
int length = name_end - filename;
// Get a copy of the substring containing the list name
char *name = strndup(filename, length);
return name;
}
/**
* Compares two strings, ignoring case.
*
* This is a comparison function to be passed into qsort().
*
* @param s1 The first string
* @param s2 The second string
* @return Integer greater than, equal to or less than 0 depending on how
* s1 compares to s2.
*/
static int cmpstringp(const void *s1, const void *s2) {
// Cast & dereference to turn pointer to pointer to char
// into pointer to char
return strcasecmp(* (char * const *) s1, * (char * const *) s2);
}
/*
* Public helper functions
*/
char *get_dir(const char *dir) {
/*
* Use default value if dir has not been set
*/
// Pointer where we will build our copy of dir
char *dir_cpy;
// Find the user home by checking $HOME and falling back to getpwuid
if (!dir) {
if ((dir = getenv("HOME")) == NULL) {
dir = getpwuid(getuid())->pw_dir;
}
// Prepare format to append the .tasuke directory to the path
const char *dir_format =
has_trailing_slash(dir) ? "%s.tasuke" : "%s/.tasuke";
// Allocate memory to copy in dir & the default .tasuke
dir_cpy = malloc((strlen(dir) + 9) * sizeof(char));
// Build the new directory path
sprintf(dir_cpy, dir_format, dir);
} else {
// Since the user supplied a directory, make a plain copy of this
dir_cpy = strdup(dir);
}
/*
* Check if the directory still exists and try to create it if not
*/
struct stat buffer;
// Does directory exist?
if (stat(dir_cpy, &buffer) == -1 || S_ISDIR(buffer.st_mode) == 0) {
// If not, create it
if (mkdir(dir_cpy, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == -1) {
// There was an error, free memory and return
free(dir_cpy);
return NULL;
}
}
return dir_cpy;
}
char *get_file(const char *dir, const char *list) {
/*
* Use default values if dir or list have not been set
*/
// Get the directory and create it if it doesn't exist yet
char *dir_cpy = get_dir(dir);
// Abort on error
if (dir_cpy == NULL) {
return NULL;
}
// If no list name was set, use the default
if (!list) {
list = "todo";
}
/*
* Build full path to file
*/
// Allocate memory for full path (freed by user)
char *file = malloc((strlen(dir_cpy) + strlen(list) + 6) * sizeof(char));
// Choose format based on whether there is a trailing slash already
const char *path_format =
has_trailing_slash(dir_cpy) ? "%s%s.txt" : "%s/%s.txt";
// Build the full path
sprintf(file, path_format, dir_cpy, list);
// Free the dir string we no longer need
free(dir_cpy);
return file;
}
char **get_files(const char *dir, char **lists) {
// Get number of lists by iterating over array until NULL terminator found
int i;
for (i = 0; lists[i]; ++i);
// Build path array
char **files;
if (i == 0) {
// No lists given, allocate memory for default list + terminator
files = malloc(2 * sizeof(char *));
// Build path to default list
if ((files[0] = get_file(dir, NULL)) == NULL) {
// Free the empty array
free(files);
return NULL;
}
// Add terminator
files[1] = NULL;
} else {
// Some lists were given, allocate memory for them + terminator
files = malloc((i + 1) * sizeof(char *));
// Iterate over lists, building paths
for (int y = 0; y < i; ++y) {
if ((files[y] = get_file(dir, lists[y])) == NULL) {
// Free paths we've already acquired at this point
for (--y; y >= 0; --y) {
free(files[y]);
}
// Free the empty array
free(files);
return NULL;
}
}
// Add terminator
files[i] = NULL;
}
return files;
}
/*
* Commands
*/
const char *tasklib_add(const char *file, char **tasks, int verbose) {
// Open file in append mode
FILE *fp;
if ((fp = fopen(file, "a")) == NULL) {
return "Unable to open list\n";
}
// Write all tasks to file
for ( ; *tasks; ++tasks) {
if (fprintf(fp, "%s\n", *tasks) < 0) {
fclose(fp);
return "Unable to write to list\n";
}
}
// Close file
if (fclose(fp) == EOF) {
return "Unable to close list\n";
}
// Show new list
if (verbose) {
// Initialize TaskList ADT
TaskList list = tasklist_init(file);
// Attempt reading the list
const char *error = tasklist_read(list);
if (error) {
tasklist_destroy(list);
return error;
}
// If there was no problem, print it
tasklist_print(list);
// Cleanup
tasklist_destroy(list);
}
return NULL;
}
const char *tasklib_prepend(const char *file, char **tasks, int verbose) {
// Build TaskList ADT
TaskList list = tasklist_init(file);
// Try reading the list
const char *error = tasklist_read(list);
if (error) {
tasklist_destroy(list);
return error;
}
// Try inserting all tasks
for (int ipos = 1; *tasks; ++tasks) {
error = tasklist_insert(list, ipos++, *tasks);
if (error) {
tasklist_destroy(list);
return error;
}
}
// Try writing the updated list to file
error = tasklist_write(list);
if (error) {
tasklist_destroy(list);
return error;
}
// Show the modified list
if (verbose) {
tasklist_print(list);
}
tasklist_destroy(list);
return NULL;
}
const char *tasklib_insert(
const char *file, char **position_task, int verbose) {
/*
* Extract position and task argument, checking for sanity
*/
long position = -1;
const char *task = NULL;
for (int i = 0; *position_task; ++position_task, ++i) {
if (i == 0) {
// Extract position
position = strtopos(*position_task);
// Handle conversion error
if (position == -1) {
return "Position not a number\n";
}
} else if (i == 1) {
// Extract task text
task = *position_task;
} else {
// There is an additional invalid argument
return "Too many arguments\n";
}
}
// Abort if we don't have all required arguments
if (position == -1 || task == NULL) {
return "Not enough arguments\n";
}
/*
* Use TaskList to handle the insertion
*/
// Build TaskList ADT
TaskList list = tasklist_init(file);
// Try reading the list
const char *error = tasklist_read(list);
if (error) {
tasklist_destroy(list);
return error;
}
// Try inserting the task
error = tasklist_insert(list, position, task);
if (error) {
tasklist_destroy(list);
return error;
}
// Try writing the updated list to file
error = tasklist_write(list);
if (error) {
tasklist_destroy(list);
return error;
}
// Show the modified list
if (verbose) {
tasklist_print(list);
}
tasklist_destroy(list);
return NULL;
}
const char *tasklib_done(const char *file, char **posargs, int verbose) {
// Determine number of positional arguments
int length;
for (length = 0; posargs[length]; ++length);
// Create array to store converted positions
long positions[length + 1];
// Set terminator element
positions[length] = -1;
// Iterate over all positional arguments, building array of positions
for (int i = 0; i < length; ++i) {
long position = strtopos(posargs[i]);
// Handle conversion error
if (position == -1) {
return "Position not a number\n";
}
positions[i] = position;
}
// Build TaskList ADT
TaskList list = tasklist_init(file);
// Try reading the list
const char *error = tasklist_read(list);
if (error) {
tasklist_destroy(list);
return error;
}
// Try deleting tasks
error = tasklist_done(list, positions);
if (error) {
tasklist_destroy(list);
return error;
}
// Try writing the updated list to file
error = tasklist_write(list);
if (error) {
tasklist_destroy(list);
return error;
}
// Show the modified list
if (verbose) {
tasklist_print(list);
}
tasklist_destroy(list);
return NULL;
}
const char *tasklib_names(const char *dir) {
DIR *dp;
struct dirent *ep;
// Attempt opening the directory stream
if ((dp = opendir(dir)) == NULL) {
return "Unable to open directory\n";
}
// Read dir entries into array
char **names = malloc(8 * sizeof(char *));
int size = 8;
int i = 0;
while ((ep = readdir (dp))) {
if (strcmp(ep->d_name, ".") != 0 && strcmp(ep->d_name, "..") != 0) {
// Increase array size if necessary
if (i == size) {
names = realloc(names, 2 * size * sizeof(char *));
size *= 2;
}
// Insert name into array
names[i++] = filename_to_name(ep->d_name);
}
}
// Sort array alphabetically
qsort(names, i, sizeof(char *), cmpstringp);
// Print list names
for (int y = 0; y < i; ++y) {
printf("%s\n", names[y]);
}
// Cleanup
closedir(dp);
for (i -= 1; i >= 0; --i) {
free(names[i]);
}
free(names);
return NULL;
}
const char *tasklib_list(char **files) {
// Iterate over path array until terminator is encountered
for ( ; *files; ++files) {
// Initialize TaskList ADT
TaskList list = tasklist_init(*files);
// Attempt reading current list
const char *error = tasklist_read(list);
if (error) {
tasklist_destroy(list);
return error;
}
// If there was no problem, print it
tasklist_print(list);
// Cleanup
tasklist_destroy(list);
// Print empty line if there is yet another list
if (*(files + 1)) {
printf("\n");
}
}
return NULL;
}
const char *tasklib_move(const char *file, char **from_to, int verbose) {
/*
* Extract position arguments, checking for sanity
*/
long from_pos = -1, to_pos = -1;
for (int i = 0; *from_to; ++from_to, ++i) {
if (i == 0) {
// Extract from position
from_pos = strtopos(*from_to);
// Handle conversion error
if (from_pos == -1) {
return "Position not a number\n";
}
} else if (i == 1) {
// Extract to position
to_pos = strtopos(*from_to);
// Handle conversion error
if (to_pos == -1) {
return "Position not a number\n";
}
} else {
// There is an additional invalid argument
return "Too many arguments\n";
}
}
// Abort if we don't have all required arguments
if (from_pos == -1 || to_pos == -1) {
return "Not enough arguments\n";
}
/*
* Use TaskList to handle the insertion
*/
// Build TaskList ADT
TaskList list = tasklist_init(file);
// Try reading the list
const char *error = tasklist_read(list);
if (error) {
tasklist_destroy(list);
return error;
}
// Try inserting the task
error = tasklist_move(list, from_pos, to_pos);
if (error) {
tasklist_destroy(list);
return error;
}
// Try writing the updated list to file
error = tasklist_write(list);
if (error) {
tasklist_destroy(list);
return error;
}
// Show the modified list
if (verbose) {
tasklist_print(list);
}
tasklist_destroy(list);
return NULL;
}
const char *tasklib_remove(char **files) {
// Iterate over path array until terminator is encountered
for ( ; *files; ++files) {
// Attempt unlinking
if (unlink(*files) != 0) {
return "Unable to delete list\n";
}
}
return NULL;
}