UNPKG

mecano

Version:

Common functions for system deployment.

110 lines (103 loc) 2.8 kB
// Generated by CoffeeScript 1.11.1 var diff, regexp, string, util, wrap; module.exports = function(options, callback) { var crontab, jobs; if (!options.when) { return callback(new Error('valid when is required')); } if (!options.cmd) { return callback(new Error('valid cmd is required')); } if (options.user != null) { options.log({ message: "Using user " + options.user, level: 'DEBUG', module: 'mecano/cron/add' }); crontab = "crontab -u " + options.user; } else { options.log({ message: "Using default user", level: 'DEBUG', module: 'mecano/cron/add' }); crontab = "crontab"; } jobs = null; return this.execute({ cmd: crontab + " -l", code: [0, 1] }, function(err, _, stdout, stderr) { var added, i, job, modified, new_job, regex; if (err && !/^no crontab for/.test(stderr)) { throw err; } new_job = options.when + " " + options.cmd; regex = (function() { if (!options.match) { return new RegExp(".* " + (regexp.escape(options.cmd))); } else if (typeof options.match === 'string') { return new RegExp(options.match); } else if (util.isRegExp(options.match)) { return options.match; } else { throw Error("Invalid option 'match'"); } })(); added = true; jobs = (function() { var j, len, ref, results; ref = string.lines(stdout.trim()); results = []; for (i = j = 0, len = ref.length; j < len; i = ++j) { job = ref[i]; if (regex.test(job)) { added = false; if (job === new_job) { break; } options.log({ message: "Entry has changed", level: 'WARN', module: 'mecano/cron/add' }); diff(job, new_job, options); job = new_job; modified = true; } results.push(job); } return results; })(); if (added) { jobs.push(new_job); options.log({ message: "Job not found in crontab, adding", level: 'WARN', module: 'mecano/cron/add' }); } if (!(added || modified)) { return jobs = null; } }).then(function(err) { if (err) { return callback(err); } if (!jobs) { return callback(); } this.execute({ cmd: options.user != null ? "su -l " + options.user + " -c '" + options.cmd + "'" : options.cmd, "if": options.exec }); return this.execute({ cmd: crontab + " - <<EOF\n" + (jobs.join('\n')) + "\nEOF" }).then(callback); }); }; util = require('util'); regexp = require('../misc').regexp; diff = require('../misc/diff'); string = require('../misc/string'); wrap = require('../misc/wrap');