UNPKG

2.32 kBJavaScriptView Raw
1'use strict';
2
3var CronExpression = require('./expression');
4
5function CronParser() {}
6
7/**
8 * Parse crontab entry
9 *
10 * @private
11 * @param {String} entry Crontab file entry/line
12 */
13CronParser._parseEntry = function _parseEntry (entry) {
14 var atoms = entry.split(' ');
15
16 if (atoms.length === 6) {
17 return {
18 interval: CronExpression.parse(entry)
19 };
20 } else if (atoms.length > 6) {
21 return {
22 interval: CronExpression.parse(
23 atoms.slice(0, 6).join(' ')
24 ),
25 command: atoms.slice(6, atoms.length)
26 };
27 } else {
28 throw new Error('Invalid entry: ' + entry);
29 }
30};
31
32/**
33 * Wrapper for CronExpression.parser method
34 *
35 * @public
36 * @param {String} expression Input expression
37 * @param {Object} [options] Parsing options
38 * @return {Object}
39 */
40CronParser.parseExpression = function parseExpression (expression, options, callback) {
41 return CronExpression.parse(expression, options, callback);
42};
43
44/**
45 * Parse content string
46 *
47 * @public
48 * @param {String} data Crontab content
49 * @return {Object}
50 */
51CronParser.parseString = function parseString (data) {
52 var self = this;
53 var blocks = data.split('\n');
54
55 var response = {
56 variables: {},
57 expressions: [],
58 errors: {}
59 };
60
61 for (var i = 0, c = blocks.length; i < c; i++) {
62 var block = blocks[i];
63 var matches = null;
64 var entry = block.replace(/^\s+|\s+$/g, ''); // Remove surrounding spaces
65
66 if (entry.length > 0) {
67 if (entry.match(/^#/)) { // Comment
68 continue;
69 } else if ((matches = entry.match(/^(.*)=(.*)$/))) { // Variable
70 response.variables[matches[1]] = matches[2];
71 } else { // Expression?
72 var result = null;
73
74 try {
75 result = self._parseEntry('0 ' + entry);
76 response.expressions.push(result.interval);
77 } catch (err) {
78 response.errors[entry] = err;
79 }
80 }
81 }
82 }
83
84 return response;
85};
86
87/**
88 * Parse crontab file
89 *
90 * @public
91 * @param {String} filePath Path to file
92 * @param {Function} callback
93 */
94CronParser.parseFile = function parseFile (filePath, callback) {
95 require('fs').readFile(filePath, function(err, data) {
96 if (err) {
97 callback(err);
98 return;
99 }
100
101 return callback(null, CronParser.parseString(data.toString()));
102 });
103};
104
105module.exports = CronParser;