-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupdate
executable file
·294 lines (247 loc) · 9.18 KB
/
update
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
#!/usr/bin/env node
// Database interface
var dbi = require('./lib/dbi');
// Master Controller
// Parses command line options and sets up batch
(function(root) {
var options = {},
commandLine = process.argv.slice(2);
// Option creator
var addOption = function(name, help, setup) {
if (!options.hasOwnProperty(name)) {
options[name] = { help: help, // Two element array: [params, text]
setup: setup }; // Array of strings -> callback with err & job / array of jobs
}
};
// Options help
var helpOption = function(which) {
var toExplain = (which && options.hasOwnProperty(which)) ? [which] : Object.keys(options),
maxLength = toExplain.reduce(function(longest, current) {
return Math.max(longest, current.length);
}, 0),
termWrap = require('wordwrap')(maxLength + 5, 80);
console.log('Usage: update [OPTION] RECORD');
toExplain.forEach(function(opt) {
// Option name and its parameters
console.log('\n -' + opt +
require('wordwrap')(2 + maxLength - opt.length, 80)(options[opt].help[0]) + '\n');
// Help text; indented and wrapped
console.log(termWrap(options[opt].help[1]) + '\n');
});
};
//////////////////////////////////////////////////////////////////////
var cache = {}; // This is for the sake of the JSON import
// Record validation
var validateRecord = function(data, spec, callback) {
var validator, err;
/* The parameter specification is a simplified regular expression
with a limited alphabet, which represents expected types:
Date Time Station String Boolean
-------- ----------- -------- ------------ ----------
DATE SCHEDULE FROM EXCUSE CANCELLED
START ARRIVE (*) TO DESCRIPTION
FINISH DEPART ORIGIN
STATION
CODE (*) Can be datetime
I should probably write a proper FSM to parse this, but life is
short and I can just get away with converting things into a
humongous RegExp... */
if (cache.hasOwnProperty(spec)) {
validator = cache[spec];
} else {
var types = {
date: { re: '\\d{4}-\\d{2}-\\d{2}', // YYYY-MM-DD
tokens: ['DATE', 'START', 'FINISH'] },
time: { re: '\\d{2}:\\d{2}(:\\d{2})?', // HH:MM(:SS)?
tokens: ['SCHEDULE', 'DEPART'] },
datetime: { tokens: ['ARRIVE'] },
station: { re: '[a-zA-Z]{3}',
tokens: ['FROM', 'TO', 'ORIGIN', 'STATION', 'CODE'] },
string: { re: '.*', // TODO This is wrong!
tokens: ['EXCUSE', 'DESCRIPTION'] },
bool: { re: '0|1',
tokens: ['CANCELLED'] }
};
types.datetime.re = '(' + types.date.re + ' )?' + types.time.re;
// We need to tweak the spec slightly to correct for whitespace
// before optional components or capture groups
var reValidate = '^' + spec.replace(/ (\w+)\?/g, '( $1)?').replace(/ \(/g, '( ') + '$';
for (var t in types) {
var re = types[t].re;
types[t].tokens.forEach(function(token) {
var reToken = new RegExp('\\b' + token + '\\b', 'g');
reValidate = reValidate.replace(reToken, '(' + re + ')');
});
};
validator = cache[spec] = new RegExp(reValidate);
}
if (!validator.test(data.join(' '))) {
err = 'Invalid record format';
}
// Note that we have only validated the text format, there are no
// validations on things like correct date, etc. This is left unto
// SQLite and the constraints put on the database.
callback(err, data);
};
// Generic setup: Validates single record and converts to database
// interface job and respective parameters
var genericSetup = function(job, handler) {
return function(record, callback) {
validateRecord(record, this.help[0], function(err, data) {
var args;
if (!err) { args = handler(data); }
callback(err, { job: job, data: args });
});
};
};
//////////////////////////////////////////////////////////////////////
// Setup options and record handlers
addOption(
'log',
[
'DATE FROM SCHEDULE TO ARRIVE (EXCUSE CANCELLED?)?',
'Append a journey log entry:\n\n' +
'DATE Journey date (YYYY-MM-DD)\n' +
'FROM Origin station code\n' +
'SCHEDULE Scheduled departure time (HH:MM)\n' +
'TO Destination station code\n' +
'ARRIVE Actual arrival time (HH:MM)\n' +
'EXCUSE Guard\'s excuse for the service, if any\n' +
'CANCELLED 0 = No (Default); 1 = Yes\n\n' +
'If the ARRIVE time is after midnight, you must also specify a ' +
'date component (YYYY-MM-DD HH:MM).\n\n' +
'Note that, as the most common use-case, \'-log\' can be omitted.'
],
genericSetup(dbi.log, function(data) {
return {
$from: data[1].toUpperCase(),
$depart: data[0] + ' ' + data[2],
$to: data[3].toUpperCase(),
$arrive: data[4].length >= 16 ? data[4] : data[0] + ' ' + data[4],
$excuse: data.length > 5 ? data[5] : null,
$cancelled: data.length == 7 ? data[6] : 0
};
})
);
addOption(
'route',
[
'ORIGIN DEPART (STATION ARRIVE)+',
'Create a new route from the ORIGIN station code, at the ' +
'scheduled DEPART time, to each of the following STATION codes ' +
'and advertised ARRIVE time tuples. There must be at least one ' +
'destination tuple; arrival times must be greater than the ' +
'departure time, but destinations needn\'t be in order. The ' +
'route will be attached to the most recent origin; if one ' +
'can\'t be found, you will be prompted to supply its validity ' +
'dates and it will be added. Station codes must, however, exist.\n\n' +
'e.g., WAT 08:00 WIM 08:10 KNG 08:30\n' +
'The 8am from Waterloo, arriving in Wimbledon at 8:10 and ' +
'Kingston-upon-Thames at 8:30.\n\n'+
'If the arrival time is after midnight, you must also specify ' +
'a date component, the day after the Unix epoch:\n\n' +
'e.g., WAT 23:56 CLJ "1970-01-02 00:12"'
],
genericSetup(dbi.route, function(data) {
var args = {
$origin: data[0].toUpperCase(),
$depart: '1970-01-01 ' + data[1],
waypoints: []
};
for (var i = 2; i < data.length; i += 2) {
args.waypoints.push({
$station: data[i].toUpperCase(),
$arrive: data[i + 1].length >= 16 ? data[i + 1] : '1970-01-01 ' + data[i + 1]
});
}
return args;
})
);
addOption(
'station',
[
'CODE DESCRIPTION',
'Add a station to the database. Official codes (dft.gov.uk/naptan) ' +
'needn\'t be used, providing you\'re consistent and stick to the ' +
'three character format.'
],
genericSetup(dbi.station, function(data) {
return {
$code: data[0].toUpperCase(),
$name: data[1]
};
})
);
addOption(
'origin',
[
'ORIGIN DEPART START FINISH?',
'Adjust a route\'s ORIGIN station code and scheduled DEPART ' +
'time\'s validity period: from midnight on START, to midnight on ' +
'FINISH (which may be omitted if this information isn\'t available).'
],
genericSetup(dbi.origin, function(data) {
return {
$origin: data[0].toUpperCase(),
$depart: data[1],
$validFrom: data[2],
$validTo: data.length == 4 ? data[3] : null
};
})
);
addOption(
'json',
[
'FILENAME+',
'Import data from a JSON file(s). See the project wiki on GitHub ' +
'for the schema: https://github.com/Xophmeister/stupidTrains/wiki'
],
function(filenames, callback) {
// TODO
callback('Not yet implemented', null);
}
);
//////////////////////////////////////////////////////////////////////
root.justDoIt = function(callback) {
var task = {},
err, batch;
if (commandLine.length) {
if (commandLine[0].charAt(0) == '-') {
task.mode = commandLine[0].substr(1);
task.data = commandLine.slice(1);
} else {
task.mode = 'log';
task.data = commandLine;
}
// Create batch
if (options.hasOwnProperty(task.mode)) {
options[task.mode].setup(task.data, function(e, jobs) {
if (e) {
helpOption(task.mode);
err = e;
} else {
batch = Array.isArray(jobs) ? jobs : [jobs];
}
});
} else {
helpOption();
err = 'Invalid options specified';
}
} else {
helpOption();
err = 'No options specified';
}
callback(err, batch);
};
})(global);
// Let's do this!
justDoIt(function(err, batch) {
if (err) {
console.error('Error: ' + err);
process.exit(1);
}
batch.forEach(function(task) {
task.job(task.data, console.log);
});
});
// vim: ft=javascript