-
Notifications
You must be signed in to change notification settings - Fork 0
/
options.c
136 lines (122 loc) · 2.89 KB
/
options.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
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <time.h>
#include "date_format.h"
#include "options.h"
#ifndef VERSION
#define VERSION "devel"
#endif
void usage(int argc, char **argv) {
fprintf(
stderr,
"Usage:\n"
"\t%s [-e <editor>] [-p <prefix>] [-r <root>] [-s <suffix>] [-d|t|i]\n"
"\n"
"\t\t-d\tuse current date\n"
"\t\t-t\tuse current time\n"
"\t\t-i\t(default) use current iso-8601 time\n"
"\n"
"\tother flags\n"
"\n"
"\t\t-h\tprint this help\n"
"\t\t-v\tprint version\n"
"\t\t-n\tdry run; just print file path\n"
"",
argv[0]);
}
options_t parse_args(int argc, char **argv) {
// initialize
options_t opts;
opts.editor = getenv("EDITOR");
opts.prefix = getenv("JOT_PREFIX");
opts.suffix = getenv("JOT_SUFFIX");
opts.root = getenv("JOT_ROOT");
opts.as_of = time(0);
opts.date_format = format_date;
opts.dry_run = false;
// parse cmdline
char opt = 0;
char **next = 0;
for (int i = 0; i < argc; i++) {
if (0 == strncmp(argv[i], "-", 1)) {
if (next != 0) {
fprintf(stderr, "error: expecting value for option -%c\n", opt);
usage(argc, argv);
exit(-1);
}
int j = 1;
while (argv[i][j++] != 0) {
char tok = argv[i][j - 1];
switch (tok) {
case 'h':
usage(argc, argv);
exit(0);
case 'e':
opt = tok;
next = &opts.editor;
break;
case 'p':
opt = tok;
next = &opts.prefix;
break;
case 'r':
opt = tok;
next = &opts.root;
break;
case 's':
opt = tok;
next = &opts.suffix;
break;
case 'd':
opts.date_format = format_date;
break;
case 't':
opts.date_format = format_time;
break;
case 'i':
opts.date_format = format_time_iso8601;
break;
case 'v':
fprintf(stdout, "version: %s\n", VERSION);
exit(0);
case 'n':
opts.dry_run = true;
break;
default:
fprintf(stderr, "OPTION -%c unknown\n", tok);
break;
}
}
} else {
if (next != 0) {
*next = argv[i];
next = 0;
opt = 0;
}
// TODO: consider inserting any extra strings into the file
}
}
if (next != 0) {
fprintf(stderr, "error: expecting value for option -%c\n", opt);
usage(argc, argv);
exit(-1);
}
// failsafe cleanup
if (opts.suffix != NULL && opts.suffix[0] == '.') {
opts.suffix = opts.suffix + 1;
}
if (opts.editor == NULL || opts.editor[0] == 0) {
opts.editor = "vi";
}
if (opts.prefix == NULL) {
opts.prefix = "";
}
if (opts.suffix == NULL) {
opts.suffix = "md";
}
if (opts.root == NULL) {
opts.root = "";
}
return opts;
}