UNPKG

mecano

Version:

Common functions for system deployment.

101 lines (94 loc) 2.71 kB
// Generated by CoffeeScript 1.9.1 var diff, execute, 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) { if (typeof options.log === "function") { options.log("Using user " + options.user + " [DEBUG]"); } crontab = "crontab -u " + options.user; } else { if (typeof options.log === "function") { options.log('Using default user [DEBUG]'); } 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(".* " + 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; } if (typeof options.log === "function") { options.log("`mecano chron_add`: entry has changed [WARN]"); } diff(job, new_job, options); job = new_job; modified = true; } results.push(job); } return results; })(); if (added) { jobs.push(new_job); if (typeof options.log === "function") { options.log("Job not found in crontab. Adding [WARN]"); } } if (!(added || modified)) { return jobs = null; } }).then(function(err) { if (err) { return callback(err); } if (!jobs) { return callback(); } return this.execute({ cmd: options.user != null ? "su -l " + options.user + " -c '" + options.cmd + "'" : options.cmd, "if": options.exec }).execute({ cmd: crontab + " - <<EOF\n" + (jobs.join('\n')) + "\nEOF" }).then(callback); }); }; util = require('util'); execute = require('./execute'); diff = require('./misc/diff'); string = require('./misc/string'); wrap = require('./misc/wrap');