This repository has been archived by the owner on Aug 4, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathstn.js
562 lines (516 loc) · 14.2 KB
/
stn.js
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
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
//
// stn.js - a JavaScript module for processing plain text in
// Simple Timesheet Notation
//
// @author: R. S. Doiel, <[email protected]>
// copyright (c) 2011 all rights reserved
//
// Released under the Simplified BSD License.
// See: http://opensource.org/licenses/bsd-license.php
//
/*jslint devel: true, node: true, maxerr: 50, indent: 4, vars: true, sloppy: true */
(function (global, exports) {
// Format a date as YYYY-MM-DD
// @param Date object
// @return string in YYYY-MM-DD format
var YYYYMMDD = function (d, use_UTC) {
if (typeof d === "string") {
if (d.match(/[0-9][0-9][0-9][0-9][\s]*-[0-1][0-9]-[\s]*[0-3][0-9]/)) {
return d.replace(/\s+/, "");
}
d = new Date(d);
} else if (typeof d === "number") {
d = new Date(d);
} else if (typeof d !== "object" &&
typeof d.getFullYear !== "function") {
throw "Expecting type: " + String(d) + " --> " + typeof d;
}
if (!use_UTC) {
return [
d.getFullYear(),
String("0" + (d.getMonth() + 1)).substr(-2),
String("0" + d.getDate()).substr(-2)
].join("-");
}
return [
d.getUTCFullYear(),
String("0" + (d.getUTCMonth() + 1)).substr(-2),
String("0" + d.getUTCDate()).substr(-2)
].join("-");
};
// Fromat time as HH:MM
// @param Date object
// @return string in HH:MM format
var HHMM = function (t, use_UTC) {
if (!use_UTC) {
return [
String("0" + t.getHours()).substr(-2),
String("0" + t.getMinutes()).substr(-2)
].join(":");
}
return [
String("0" + t.getUTCHours()).substr(-2),
String("0" + t.getUTCMinutes()).substr(-2)
].join(":");
};
// reset - clear the parse tree
// sets save_parse to true,
// sets normalize_date to true
// sets tags to true
// sets map ot false
// @param options - a set of options to override the defaults with
// on reset.
var reset = function (options) {
var ky,
default_keys = [
"normalize_date",
"hours",
"save_parse",
"tags",
"map"
],
defaults = {},
map = {};
default_keys.forEach(function (ky) {
defaults[ky] = true;
});
this.defaults = defaults;
this.map = false;
this.parse_tree = {};
this.msgs = [];
if (options !== undefined) {
for (ky in options) {
if (options.hasOwnProperty(ky)) {
if (default_keys.indexOf(ky) >= 0) {
this.defaults[ky] = options[ky];
} else {
map[ky] = options[ky];
}
}
}
if (Object.keys(map).length > 0) {
this.map = map;
}
}
};
var Stn = function (parse_tree, options) {
var day,
dy;
// Initialize this with reset().
this.reset(options);
day = new Date();
dy = YYYYMMDD(day);
this.working_date = dy;
this.parse_tree = parse_tree;
return this;
};
/**
* error - collect parse errors into the msgs array.
* @param msg - the message to the collection of messages.
* @return true on successful add, false otherwise
*/
var error = function (msg) {
var i = this.msgs.length;
this.msgs.push('ERROR: ' + msg);
if ((i + 1) !== this.msgs.length) {
return false;
}
return true;
};
/**
* errorCount - number of error messages collected.
* @return number of error messages.
*/
var errorCount = function () {
if (this.msgs === undefined) {
return 0;
}
return this.msgs.length;
};
/**
* messages - return the msgs array as a single string delimited
* by new lines.
* @param no_clear (optional, defaults to false)
* @return string representing in messages
*/
var messages = function (no_clear) {
var result;
if (this.msgs === undefined) {
this.msgs = [];
}
result = this.msgs.join("\n");
// set optional default i needed
if (no_clear !== undefined) {
no_clear = false;
}
if (no_clear === true) {
return result;
}
// Clear the messages
this.msgs = [];
return result;
};
/**
* parse - parse a block of plain text and
* pass the results to the callback method
* based on any options supplied.
* @param: text - the plain text to parse
* @param: callback - (optional) the function to call when complete
* @param: options - (optional) an object with option properties to use
* for determining the data argument handed to the callback or
* returned by parse
* @returns a object representing the parsed data or false if
* errors were found.
*/
var parse = function (text, callback, options) {
var self = this,
lines,
ky,
data = {},
dy = this.working_date,
reParseDirective,
reDateEntry,
reTimeEntry,
reTime,
reDateNormalized;
if (typeof this.defaults === "undefined" ||
typeof this.msgs === "undefined" ||
typeof this.parse_tree === "undefined") {
this.reset();
}
if (typeof options === "undefined") {
options = this.defaults;
} else {
for (ky in this.defaults) {
if (this.defaults.hasOwnProperty(ky)) {
if (typeof options[ky] === "undefined") {
options[ky] = this.defaults[ky];
}
}
}
}
if (typeof callback === 'object') {
// options arg was folded over callback
Object.keys(callback).forEach(function (ky) {
options[ky] = callback[ky];
});
}
// If we're doing an incremental parse using the existing tree.
if (options.save_parse === true) {
data = this.parse_tree;
}
lines = String(text).replace(/\r/g, '').split("\n");
reParseDirective = /(|\s+)\@\w+/;
reDateEntry = /([0-1][0-9]\/[0-3][0-9]\/[0-9][0-9][0-9][0-9]|[0-9][0-9][0-9][0-9][\s]*-[0-1][0-9]-[\s]*[0-3][0-9])$/;
reDateNormalized = /[0-9][0-9][0-9][0-9][\s]*-[0-1][0-9]-[\s]*[0-3][0-9]/;
reTimeEntry = /^[0-9]+:[0-5][0-9][\s]*\-([\s]*[0-9]+:[0-5][0-9]|now)[:,;\,\ ]*/;
reTime = /[0-9]+:[0-5][0-9]/;
// Read through the text line, by line and create a new JSON
// blob
lines.forEach(function (line, i) {
var day, hrs, tmp, tm, tag, project, task, client, cur, clip;
line = line.trim();
if (reParseDirective.exec(line)) {
options.tags = true;
options.save_parse = true;
options.map = true;
self.save_parse = true;
if (typeof self.map !== "object") {
self.map = {};
}
// Setup the tag
cur = line.indexOf(" ");
clip = line.indexOf(";") - cur;
if (clip > -1) {
project = "untitled";
task = "misc";
client = "unknown";
tag = line.substr(cur, clip).trim();
cur += clip + 1;
clip = line.substr(cur).indexOf(";");
// Set project name
if (clip > -1) {
project = line.substr(cur, clip).trim();
cur += clip + 1;
clip = line.substr(cur).indexOf(";");
// Set task
if (clip > -1) {
task = line.substr(cur, clip).trim();
cur += clip + 1;
}
// If we had an empty task then bump past ; if needed.
if (line.substr(cur, 1) === ";") {
cur += 1;
}
// Set client _name
if (cur < line.length) {
client = line.substr(cur).trim();
}
}
self.map[tag] = {project_name: project, task: task, client_name: client};
}
} else if (reDateEntry.exec(line)) {
if (options.normalize_date === true) {
if (reDateNormalized.exec(line.trim())) {
dy = line.trim();
} else {
day = new Date(line.trim());
dy = YYYYMMDD(day);
}
} else {
dy = line.trim();
}
// Keep track of the last date working.
if (typeof data[dy] === "undefined") {
data[dy] = {};
}
this.working_date = dy;
} else if (reTimeEntry.exec(line)) {
tm = (reTimeEntry.exec(line))[0].trim();
line = line.substr(tm.length).trim();
if (tm.substr(-1) === ':' || tm.substr(-1) === ';' || tm.substr(-1) === ',') {
tm = tm.slice(0, tm.length - 1).trim();
}
if (options.tags || options.hours || options.map) {
if (typeof data[dy] === "undefined") {
data[dy] = {};
}
data[dy][tm] = {};
data[dy][tm].map = false;
tmp = line.split(';');
data[dy][tm].notes = line.substr(tmp[0].length + 1).trim();
if (options.tags) {
data[dy][tm].tags = (tmp[0]).split(',');
}
// FIXME: I'm only assigning map using all tags as a single key,
// Need to loop through keys in that are found in options.tags
if (options.map !== undefined && options.map !== false &&
data[dy][tm].tags !== undefined) {
data[dy][tm].tags.forEach(function (tag) {
if (self.map[tag] !== undefined) {
data[dy][tm].map = self.map[tag];
}
});
}
hrs = tm.split(' - ');
hrs.forEach(function (val, i, times) {
var hr = val.split(':');
times[i] = Number(hr[0]) + Number(hr[1] / 60);
});
if (hrs[0] < hrs[1]) {
data[dy][tm].hours = (hrs[1] - hrs[0]).toString();
} else {
data[dy][tm].hours = (hrs[1] + (12 - hrs[0])).toString();
}
} else {
data[dy][tm] = line.trim();
}
}
});
// If options.hours, options.notes true then processing
// into a more complex object tree.
// Finished parse, return the results
if (callback !== undefined && typeof callback === 'function') {
if (errorCount() === 0) {
callback(null, data, options);
} else {
callback(this.messages(), data, options);
}
}
if (errorCount() > 0) {
return false;
}
this.working_date = dy;
return data;
};
// Return the current parse tree state.
var valueOf = function () {
return this.parse_tree;
};
// toJSON - render the current parse tree to JSON format.
var toJSON = function () {
return JSON.stringify(this.parse_tree);
};
// Render parse tree as string.
var toString = function () {
var self = this,
dates = Object.keys(this.parse_tree),
lines = [];
dates.sort();
dates.forEach(function (dy, i) {
var times = Object.keys(self.parse_tree[dy]);
lines.push(dy);
times.sort();
times.forEach(function (tm) {
var tags = "", maps = "", notes = "", rec;
rec = self.parse_tree[dy][tm];
if (typeof rec === "string") {
notes = rec;
} else {
if (typeof rec.map !== "undefined" &&
rec.map !== false) {
maps = [
rec.map.project_name,
rec.map.task
].join(", ") + "; ";
}
if (typeof rec.tags !== "undefined" &&
rec.tags !== false) {
tags = rec.tags.join(", ") + "; ";
}
if (typeof rec.notes !== "undefined") {
notes = rec.notes;
}
}
lines.push([
tm,
"; ",
tags,
maps,
notes
].join(""));
});
});
return lines.join("\n\n");
};
// addEntry - a new entry to the existing parse tree
// e.g. {date: "2012-11-03", start: "09:00:00", end: "11:45:00",
// notes: "This is a demo", tags:["demo"]}
// @param entry - an object with properties of date, start, end, notes and tags
// or a string to run through the parser.
//
var addEntry = function (entry, callback, options) {
var result, day, dy, tm, time_range;
day = new Date();
dy = YYYYMMDD(day);
tm = HHMM(day);
this.defaults.save_parse = true;
if (typeof entry === "string") {
if (entry.trim().match(/([0-1][0-9]\/[0-3][0-9]\/[0-9][0-9][0-9][0-9]|[0-9][0-9][0-9][0-9][\s]*-[0-1][0-9]-[\s]*[0-3][0-9])$/)) {
this.working_date = YYYYMMDD(entry.trim());
} else {
result = this.parse(entry, callback, options);
}
} else if (typeof entry === "object") {
// Make sure we have all the fields.
switch (typeof entry.date) {
case 'object':
if (typeof entry.date === "object" &&
typeof entry.date.getFullYear === "function") {
day = entry.date;
entry.date = YYYYMMDD(day);
this.working_date = entry.date;
}
break;
case 'number':
day = new Date(entry.date);
entry.date = YYYYMMDD(day);
break;
case 'undefined':
entry.date = dy;
break;
}
switch (typeof entry.start) {
case 'object':
if (typeof entry.start === "object" &&
typeof entry.start.getHours === "function") {
day = entry.start;
entry.start = HHMM(day);
}
break;
case 'number':
day = new Date(entry.start);
entry.start = HHMM(day);
break;
case 'undefined':
entry.start = tm;
break;
}
switch (typeof entry.end) {
case 'object':
if (typeof entry.end === "object" &&
typeof entry.end.getHours === "function") {
day = entry.end;
entry.end = [
String("0" + day.getHours()).substr(-2),
String("0" + day.getMinutes()).substr(-2)
].join(":");
}
break;
case 'number':
day = new Date(entry.end);
entry.end = [
String("0" + day.getHours()).substr(-2),
String("0" + day.getMinutes()).substr(-2)
].join(":");
break;
case 'undefined':
entry.end = tm;
break;
}
if (typeof entry.notes === "undefined") {
entry.notes = "";
}
if (typeof entry.map === "undefined") {
entry.map = false;
}
if (typeof entry.tags === "undefined") {
entry.tags = [];
}
if (typeof this.parse_tree[entry.date] === "undefined") {
this.parse_tree[entry.date] = {};
}
time_range = [
entry.start,
entry.end
].join(" - ");
if (typeof this.parse_tree[entry.date][time_range] ===
"undefined") {
this.parse_tree[entry.date][time_range] = {};
}
this.parse_tree[entry.date][time_range].map = entry.map;
this.parse_tree[entry.date][time_range].notes = entry.notes;
this.parse_tree[entry.date][time_range].tags = entry.tags;
result = this.parse_tree[entry.date][time_range];
} else {
throw "Don't know how to process type: " + typeof entry;
}
return result;
};
Stn.prototype.valueOf = valueOf;
Stn.prototype.toString = toString;
Stn.prototype.toJSON = toJSON;
Stn.prototype.YYYYMMDD = YYYYMMDD;
Stn.prototype.HHMM = HHMM;
Stn.prototype.reset = reset;
Stn.prototype.parse = parse;
Stn.prototype.error = error;
Stn.prototype.errorCount = errorCount;
Stn.prototype.messages = messages;
Stn.prototype.addEntry = addEntry;
global.Stn = Stn;
global.Stn = Stn;
global.toString = toString;
global.toJSON = toJSON;
global.YYYYMMDD = YYYYMMDD;
global.HHMM = HHMM;
global.reset = reset;
global.parse = parse;
global.error = error;
global.errorCount = errorCount;
global.messages = messages;
global.addEntry = addEntry;
if (exports !== undefined) {
exports.Stn = Stn;
exports.toString = toString;
exports.toJSON = toJSON;
exports.YYYYMMDD = YYYYMMDD;
exports.HHMM = HHMM;
exports.reset = reset;
exports.parse = parse;
exports.error = error;
exports.errorCount = errorCount;
exports.messages = messages;
exports.addEntry = addEntry;
}
}(this, exports));