Compare commits

..

1 Commits

Author SHA1 Message Date
Javan Makhmali
4fc6a10dad bundling in http://github.com/AaronH/chronic for ruby 1.9.2 compatibility 2010-09-09 22:58:35 -04:00
32 changed files with 529 additions and 940 deletions

1
.gitignore vendored
View File

@ -2,4 +2,3 @@
pkg pkg
doc doc
.*.sw[a-z] .*.sw[a-z]
Gemfile.lock

3
.gitmodules vendored Normal file
View File

@ -0,0 +1,3 @@
[submodule "lib/whenever/vendor/gems/chronic"]
path = lib/whenever/vendor/gems/chronic
url = git://github.com/AaronH/chronic.git

View File

@ -1,7 +0,0 @@
rvm:
- 1.8.7
- 1.9.2
- ree
- rbx
- rbx-2.0
- jruby

View File

@ -1,77 +1,4 @@
### 0.6.9 / June 8th, 2011 == 0.5.0 / June 28th, 2010
* Use mojombo's chronic, it's active again. [Javan Makhmali]
### 0.6.8 / May 24th, 2011
* Convert most shortcuts to seconds. every :day -> every 1.day. #129 [Javan Makhmali]
* Allow commas in raw cron syntax. #130 [Marco Bergantin, Javan Makhmali]
* Output no update message as comments. #135 [Javan Makhmali]
* require 'thread' to support Rubygems >= 1.6.0. #132 [Javan Makhmali]
### 0.6.7 / March 23rd, 2011
* Fix issue with comment block being corrupted during subsequent insertion of duplicate entries to the crontab. #123 [Jeremy (@lingmann)]
* Removed -i from default job template. #118 [Javan Makhmali]
### 0.6.6 / March 8th, 2011
* Fix unclosed identifier bug. #119 [Javan Makhmali]
### 0.6.5 / March 8th, 2011
* Preserve whitespace at the end of crontab file. #95 [Rich Meyers]
* Setting nil or blank environment variables now properly formats output. [T.J. VanSlyke]
* Allow raw cron sytax, added -i to bash job template, general cleanup. [Javan Makhmali]
### 0.6.2 / October 26th, 2010
* --clear-crontab option completely removes entries. #63 [Javan Makhmali]
* Set default :environment and :path earlier in the new setup.rb (formerly job_types/default.rb). [Javan Makhmali]
* Converted README and CHANGELOG to markdown. [Javan Makhmali]
### 0.6.1 / October 20th, 2010
* Detect script/rails file and change runner to Rails 3 style if found. [Javan Makhmali]
* Created a new :job_template system that can be applied to all commands. Wraps all in bash -l -c 'command..' by default now for better RVM support. Stopped automatically setting the PATH too. [Javan Makhmali]
* Added a built-in Capistrano recipe. [Javan Makhmali]
### 0.5.3 / September 24th, 2010
* Better regexes for replacing Whenever blocks in the crontab. #45 [Javan Makhmali]
* Preserving backslashes when updating existing crontab. #82 [Javan Makhmali]
### 0.5.2 / September 15th, 2010
* Quotes automatically escaped in jobs. [Jay Adkisson]
* Added --cut option to the command line to allow pruning of the crontab. [Peer Allan]
* Switched to aaronh-chronic which is ruby 1.9.2 compatible. [Aaron Hurley, Javan Makhmali]
* Lots of internal reorganizing; tests broken into unit and functional. [Javan Makhmali]
### 0.5.0 / June 28th, 2010
* New job_type API for writing custom jobs. Internals use this to define command, runner, and rake. [Javan Makhmali - inspired by idlefingers (Damien)] * New job_type API for writing custom jobs. Internals use this to define command, runner, and rake. [Javan Makhmali - inspired by idlefingers (Damien)]
@ -80,7 +7,7 @@
* --clear option to remove crontab entries for a specific [identifier]. [mraidel (Michael Raidel)] * --clear option to remove crontab entries for a specific [identifier]. [mraidel (Michael Raidel)]
### 0.4.2 / April 26th, 2010 == 0.4.2 / April 26th, 2010
* runners now cd into the app's directory and then execute. [Michael Guterl] * runners now cd into the app's directory and then execute. [Michael Guterl]
@ -91,49 +18,49 @@
* bugfix: comparison Time with 0 failed. #32 [Dan Hixon] * bugfix: comparison Time with 0 failed. #32 [Dan Hixon]
### 0.4.1 / November 30th, 2009 == 0.4.1 / November 30th, 2009
* exit(0) instead of just exit to make JRuby happy. [Elan Meng] * exit(0) instead of just exit to make JRuby happy. [Elan Meng]
* Fixed activesupport deprecation warning by requiring active_support. #37 [Andrew Nesbitt] * Fixed activesupport deprecation warning by requiring active_support. #37 [Andrew Nesbitt]
### 0.4.0 / October 20th, 2009 == 0.4.0 / October 20th, 2009
* New output option replaces the old cron_log option for output redirection and is much more flexible. #31 [Peer Allan] * New output option replaces the old cron_log option for output redirection and is much more flexible. #31 [Peer Allan]
* Reorganized the lib files (http://weblog.rubyonrails.org/2009/9/1/gem-packaging-best-practices) and switched to Jeweler from Echoe. * Reorganized the lib files (http://weblog.rubyonrails.org/2009/9/1/gem-packaging-best-practices) and switched to Jeweler from Echoe.
### 0.3.7 / September 4th, 2009 == 0.3.7 / September 4th, 2009
* No longer tries (and fails) to combine @shortcut jobs. #20 [Javan Makhmali] * No longer tries (and fails) to combine @shortcut jobs. #20 [Javan Makhmali]
### 0.3.6 / June 15th, 2009 == 0.3.6 / June 15th, 2009
* Setting a PATH in the crontab automatically based on the user's PATH. [Javan Makhmali] * Setting a PATH in the crontab automatically based on the user's PATH. [Javan Makhmali]
### 0.3.5 / June 13th, 2009 == 0.3.5 / June 13th, 2009
* Added ability to accept lists of every's and at's and intelligently group them. (ex: every 'monday, wednesday', :at => ['3pm', '6am']). [Sam Ruby] * Added ability to accept lists of every's and at's and intelligently group them. (ex: every 'monday, wednesday', :at => ['3pm', '6am']). [Sam Ruby]
* Fixed issue with new lines. #18 [Javan Makhmali] * Fixed issue with new lines. #18 [Javan Makhmali]
### 0.3.1 / June 25th, 2009 == 0.3.1 / June 25th, 2009
* Removed activesupport gem dependency. #1 [Javan Makhmali] * Removed activesupport gem dependency. #1 [Javan Makhmali]
* Switched to numeric days of the week for Solaris support (and probably others). #8 [Roger Ertesvåg] * Switched to numeric days of the week for Solaris support (and probably others). #8 [Roger Ertesvåg]
### 0.3.0 / June 2nd, 2009 == 0.3.0 / June 2nd, 2009
* Added ability to set variables on the fly from the command line (ex: whenever --set environment=staging). [Javan Makhmali] * Added ability to set variables on the fly from the command line (ex: whenever --set environment=staging). [Javan Makhmali]
### 0.2.2 / April 30th, 2009 == 0.2.2 / April 30th, 2009
* Days of week jobs can now accept an :at directive (ex: every :monday, :at => '5pm'). [David Eisinger] * Days of week jobs can now accept an :at directive (ex: every :monday, :at => '5pm'). [David Eisinger]
@ -142,22 +69,22 @@
* Raising an exception if someone tries to specify an :at with a cron shortcut (:day, :reboot, etc) so there are no false hopes. [Javan Makhmali] * Raising an exception if someone tries to specify an :at with a cron shortcut (:day, :reboot, etc) so there are no false hopes. [Javan Makhmali]
### 0.1.7 / March 5th, 2009 == 0.1.7 / March 5th, 2009
* Added ability to update the crontab file non-destuctively instead of only overwriting it. [Javan Makhmali -- Inspired by code submitted individually from: Tien Dung (tiendung), Tom Lea (cwninja), Kyle Maxwell (fizx), and Andrew Timberlake (andrewtimberlake) on github] * Added ability to update the crontab file non-destuctively instead of only overwriting it. [Javan Makhmali -- Inspired by code submitted individually from: Tien Dung (tiendung), Tom Lea (cwninja), Kyle Maxwell (fizx), and Andrew Timberlake (andrewtimberlake) on github]
### 0.1.5 / February 19th, 2009 == 0.1.5 / February 19th, 2009
* Fixed load path so Whenever's files don't conflict with anything in Rails. Thanks Ryan Koopmans. [Javan Makhmali] * Fixed load path so Whenever's files don't conflict with anything in Rails. Thanks Ryan Koopmans. [Javan Makhmali]
### 0.1.4 / February 17th, 2009 == 0.1.4 / February 17th, 2009
* Added --load-file and --user opts to whenever binary. [Javan Makhmali] * Added --load-file and --user opts to whenever binary. [Javan Makhmali]
### 0.1.3 / February 16th, 2009 == 0.1.3 / February 16th, 2009
* Added 'rake' helper for defining scheduled rake tasks. [Javan Makhmali] * Added 'rake' helper for defining scheduled rake tasks. [Javan Makhmali]
@ -170,6 +97,6 @@
* Requiring specific gem versions: Chronic >=0.2.3 and activesupport >= 1.3.0 [Javan Makhmali] * Requiring specific gem versions: Chronic >=0.2.3 and activesupport >= 1.3.0 [Javan Makhmali]
### 0.1.0 / February 15th, 2009 == 0.1.0 / February 15th, 2009
* Initial release [Javan Makhmali] * Initial release [Javan Makhmali]

View File

@ -1,4 +0,0 @@
source "http://rubygems.org"
# Specify your gem's dependencies in newever.gemspec
gemspec

22
LICENSE
View File

@ -1,22 +0,0 @@
Copyright (c) 2011 Javan Makhmali
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

163
README.md
View File

@ -1,163 +0,0 @@
### Introduction
Whenever is a Ruby gem that provides a clear syntax for writing and deploying cron jobs.
### Installation
```sh
$ gem install whenever
```
Or with Bundler in your Gemfile.
```ruby
gem 'whenever', :require => false
```
### Getting started
```sh
$ cd /apps/my-great-project
$ wheneverize .
```
This will create an initial `config/schedule.rb` file you.
### Example schedule.rb file
```ruby
every 3.hours do
runner "MyModel.some_process"
rake "my:rake:task"
command "/usr/bin/my_great_command"
end
every 1.day, :at => '4:30 am' do
runner "MyModel.task_to_run_at_four_thirty_in_the_morning"
end
every :hour do # Many shortcuts available: :hour, :day, :month, :year, :reboot
runner "SomeModel.ladeeda"
end
every :sunday, :at => '12pm' do # Use any day of the week or :weekend, :weekday
runner "Task.do_something_great"
end
every '0 0 27-31 * *' do
command "echo 'you can use raw cron syntax too'"
end
```
### Define your own job types
Whenever ships with three pre-defined job types: command, runner, and rake. You can define your own with `job_type`.
For example:
```ruby
job_type :awesome, '/usr/local/bin/awesome :task :fun_level'
every 2.hours do
awesome "party", :fun_level => "extreme"
end
```
Would run `/usr/local/bin/awesome party extreme` every two hours. `:task` is always replaced with the first argument, and any additional `:whatevers` are replaced with the options passed in or by variables that have been defined with `set`.
The default job types that ship with Whenever are defined like so:
```ruby
job_type :command, ":task :output"
job_type :rake, "cd :path && RAILS_ENV=:environment rake :task :output"
job_type :runner, "cd :path && script/runner -e :environment ':task' :output"
```
If a `script/rails` file is detected (like in a Rails 3 app), runner will be defined to fit:
```ruby
job_type :runner, "cd :path && script/rails runner -e :environment ':task' :output"
```
If a `:path` is not set it will default to the directory in which `whenever` was executed. `:environment` will default to 'production'. `:output` will be replaced with your output redirection settings which you can read more about here: <http://github.com/javan/whenever/wiki/Output-redirection-aka-logging-your-cron-jobs>
All jobs are by default run with `bash -l -c 'command...'`. Among other things, this allows your cron jobs to play nice with RVM by loading the entire environment instead of cron's somewhat limited environment. Read more: <http://blog.scoutapp.com/articles/2010/09/07/rvm-and-cron-in-production>
You can change this by setting your own `:job_template`.
```ruby
set :job_template, "bash -l -c ':job'"
```
Or set the job_template to nil to have your jobs execute normally.
```ruby
set :job_template, nil
```
### Capistrano integration
Use the built-in Capistrano recipe for easy crontab updates with deploys.
In your "config/deploy.rb" file:
```ruby
require "whenever/capistrano"
```
Take a look at the recipe for options you can set. <http://github.com/javan/whenever/blob/master/lib/whenever/capistrano.rb>
For example, if you're using bundler do this:
```ruby
set :whenever_command, "bundle exec whenever"
require "whenever/capistrano"
```
If you are using different environments (such as staging, production), then you may want to do this:
```ruby
set :whenever_environment, defer { stage }
require "whenever/capistrano"
```
The capistrano variable `:stage` should be the one holding your environment name. This will make the correct `:environment` available in your `schedule.rb`.
### RVM Integration
If your production environment uses RVM (Ruby Version Manager) you will run into a gotcha that causes your cron jobs to hang. This is not directly related to Whenever, and can be tricky to debug. Your .rvmrc files must be trusted or else the cron jobs will hang waiting for the file to be trusted. A solution is to disable the prompt by adding this line to your user rvm file in `~/.rvmrc`
`rvm_trust_rvmrcs_flag=1`
This tells rvm to trust all rvmrc files, which is documented here: http://wayneeseguin.beginrescueend.com/2010/08/22/ruby-environment-version-manager-rvm-1-0-0/
### The `whenever` command
```sh
$ cd /apps/my-great-project
$ whenever
```
This will simply show you your `schedule.rb` file converted to cron syntax. It does not read or write your crontab file. Run `whenever --help` for a complete list of options.
### Credit
Whenever was created for use at Inkling (<http://inklingmarkets.com>). Their take on it: <http://blog.inklingmarkets.com/2009/02/whenever-easy-way-to-do-cron-jobs-from.html>
Thanks to all the contributors who have made it even better: <http://github.com/javan/whenever/contributors>
### Discussion / Feedback / Issues / Bugs
For general discussion and questions, please use the google group: <http://groups.google.com/group/whenever-gem>
If you've found a genuine bug or issue, please use the Issues section on github: <http://github.com/javan/whenever/issues>
Ryan Bates created a great Railscast about Whenever: <http://railscasts.com/episodes/164-cron-in-ruby>
It's a little bit dated now, but remains a good introduction.
----
Compatible with Ruby 1.8.7-1.9.2, JRuby, and Rubinius. [![Build Status](https://secure.travis-ci.org/javan/whenever.png)](http://travis-ci.org/javan/whenever)
----
Copyright &copy; 2011 Javan Makhmali

127
README.rdoc Normal file
View File

@ -0,0 +1,127 @@
== Introduction
Whenever is a Ruby gem that provides a clear syntax for defining cron jobs. It outputs valid cron syntax and can even write your crontab file for you. It is designed to work well with Rails applications and can be deployed with Capistrano. Whenever works fine independently as well.
Ryan Bates created a great Railscast about Whenever: http://railscasts.com/episodes/164-cron-in-ruby
Discussion: http://groups.google.com/group/whenever-gem
== Installation
$ sudo gem install whenever
== Getting started
$ cd /my/rails/app
$ wheneverize .
This will create an initial "config/schedule.rb" file you.
== Example schedule.rb file
every 3.hours do
runner "MyModel.some_process"
rake "my:rake:task"
command "/usr/bin/my_great_command"
end
every 1.day, :at => '4:30 am' do
runner "MyModel.task_to_run_at_four_thirty_in_the_morning"
end
every :hour do # Many shortcuts available: :hour, :day, :month, :year, :reboot
runner "SomeModel.ladeeda"
end
every :sunday, :at => '12pm' do # Use any day of the week or :weekend, :weekday
runner "Task.do_something_great"
end
More examples on the wiki: http://wiki.github.com/javan/whenever/instructions-and-examples
== Define your own job types
Whenever ships with three pre-defined job types: command, runner, and rake. You can define your own with <code>job_type</code>.
For example:
job_type :awesome, '/usr/local/bin/awesome :task :fun_level'
every 2.hours do
awesome "party", :fun_level => "extreme"
end
Would run <code>/usr/local/bin/awesome party extreme</code> every two hours. <code>:task</code> is always replaced with the first argument, and any additional <code>:whatevers</code> are replaced with the options passed in or by variables that have been defined with <code>set</code>.
The default job types that ship with Whenever are defined like so:
job_type :command, ':task'
job_type :runner, 'cd :path && script/runner -e :environment ":task"'
job_type :rake, 'cd :path && RAILS_ENV=:environment /usr/bin/env rake :task'
If a <code>:path</code> is not set it will default to the directory in which <code>whenever</code> was executed. <code>:environment</code> will default to 'production'.
== Cron output
$ cd /my/rails/app
$ whenever
And you'll see your schedule.rb converted to cron sytax. Note: running `whenever' with no options does not display your current crontab file, it simply shows you the output of converting your schedule.rb file.
== Capistrano integration
In your "config/deploy.rb" file do something like:
after "deploy:symlink", "deploy:update_crontab"
namespace :deploy do
desc "Update the crontab file"
task :update_crontab, :roles => :db do
run "cd #{release_path} && whenever --update-crontab #{application}"
end
end
This will update your crontab file, leaving any existing entries unharmed. When using the <code>--update-crontab</code> option, Whenever will only update the entries in your crontab file related to the current schedule.rb file. You can replace the <code>#{application}</code> with any identifying string you'd like. You can have any number of apps deploy to the same crontab file peacefully given they each use a different identifier.
If you wish to simply overwrite your crontab file each time you deploy, use the <code>--write-crontab</code> option. This is ideal if you are only working with one app and every crontab entry is contained in a single schedule.rb file.
By mixing and matching the <code>--load-file</code> and <code>--user</code> options with your various :roles in Capistrano it is entirely possible to deploy different crontab schedules under different users to all your various servers. Get creative!
If you want to override a variable (like your environment) at the time of deployment you can do so with the <code>--set</code> option: http://wiki.github.com/javan/whenever/setting-variables-on-the-fly
== Credit
Whenever was created for use at Inkling (http://inklingmarkets.com) where I work. Their take on it: http://blog.inklingmarkets.com/2009/02/whenever-easy-way-to-do-cron-jobs-from.html
While building Whenever, I learned a lot by digging through the source code of Capistrano - http://github.com/jamis/capistrano
== Discussion / Feedback / Issues / Bugs
For general discussion and questions, please use the google group: http://groups.google.com/group/whenever-gem
If you've found a genuine bug or issue, please use the Issues section on github: http://github.com/javan/whenever/issues
== License
Copyright (c) 2009+ Javan Makhmali
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

View File

@ -1,11 +1,34 @@
require 'bundler' require 'rubygems'
Bundler::GemHelper.install_tasks require 'rake'
require File.expand_path(File.dirname(__FILE__) + "/lib/whenever/version")
begin
require 'jeweler'
Jeweler::Tasks.new do |gemspec|
gemspec.name = "whenever"
gemspec.version = Whenever::VERSION
gemspec.summary = "Clean ruby syntax for defining and deploying messy cron jobs."
gemspec.description = "Clean ruby syntax for defining and deploying messy cron jobs."
gemspec.email = "javan@javan.us"
gemspec.homepage = "http://github.com/javan/whenever"
gemspec.authors = ["Javan Makhmali"]
gemspec.add_dependency 'activesupport', '>= 2.3.4'
gemspec.add_development_dependency 'shoulda', '>= 2.1.1'
gemspec.add_development_dependency 'mocha', '>= 0.9.5'
end
Jeweler::GemcutterTasks.new
rescue LoadError
puts "Jeweler not available. Install it with: sudo gem install jeweler -s http://gemcutter.org"
end
require 'rake/testtask' require 'rake/testtask'
Rake::TestTask.new(:test) do |test| Rake::TestTask.new(:test) do |test|
test.libs << 'lib' << 'test' test.libs << 'lib' << 'test'
test.pattern = 'test/{functional,unit}/**/*_test.rb' test.pattern = 'test/{functional,unit}/**/*_test.rb'
test.verbose = true test.verbose = true
end end
task :test => :check_dependencies
task :default => :test task :default => :test

20
bin/whenever Executable file → Normal file
View File

@ -3,37 +3,33 @@
require 'rubygems' require 'rubygems'
require 'optparse' require 'optparse'
require 'whenever' require 'whenever'
require 'whenever/version'
options = {} options = Hash.new
OptionParser.new do |opts| OptionParser.new do |opts|
opts.banner = "Usage: whenever [options]" opts.banner = "Usage: whenever [options]"
opts.on('-v', '--version') { puts "Whenever v#{Whenever::VERSION}"; exit(0) }
opts.on('-w', '--write-crontab') { options[:write] = true }
opts.on('-c', '--cut [lines]', 'Cut lines from the top of the cronfile') do |lines|
options[:cut] = lines.to_i if lines
end
opts.on('-i', '--update-crontab [identifier]', 'Default: full path to schedule.rb file') do |identifier| opts.on('-i', '--update-crontab [identifier]', 'Default: full path to schedule.rb file') do |identifier|
options[:update] = true options[:update] = true
options[:identifier] = identifier if identifier options[:identifier] = identifier if identifier
end end
opts.on('-w', '--write-crontab [identifier]', 'Default: full path to schedule.rb file') do |identifier|
options[:write] = true
options[:identifier] = identifier if identifier
end
opts.on('-c', '--clear-crontab [identifier]') do |identifier| opts.on('-c', '--clear-crontab [identifier]') do |identifier|
options[:clear] = true options[:clear] = true
options[:identifier] = identifier if identifier options[:identifier] = identifier if identifier
end end
opts.on('-s', '--set [variables]', 'Example: --set \'environment=staging&path=/my/sweet/path\'') do |set|
options[:set] = set if set
end
opts.on('-f', '--load-file [schedule file]', 'Default: config/schedule.rb') do |file| opts.on('-f', '--load-file [schedule file]', 'Default: config/schedule.rb') do |file|
options[:file] = file if file options[:file] = file if file
end end
opts.on('-u', '--user [user]', 'Default: current user') do |user| opts.on('-u', '--user [user]', 'Default: current user') do |user|
options[:user] = user if user options[:user] = user if user
end end
opts.on('-k', '--cut [lines]', 'Cut lines from the top of the cronfile') do |lines| opts.on('-s', '--set [variables]', 'Example: --set environment=staging&path=/my/sweet/path') do |set|
options[:cut] = lines.to_i if lines options[:set] = set if set
end end
opts.on('-v', '--version') { puts "Whenever v#{Whenever::VERSION}"; exit(0) }
end.parse! end.parse!
Whenever::CommandLine.execute(options) Whenever::CommandLine.execute(options)

19
bin/wheneverize Executable file → Normal file
View File

@ -17,16 +17,17 @@ OptionParser.new do |opts|
end end
end end
unless ARGV.empty? if ARGV.empty?
if !File.exists?(ARGV.first) abort "Please specify the directory to wheneverize, e.g. `#{File.basename($0)} .'"
abort "`#{ARGV.first}' does not exist." elsif !File.exists?(ARGV.first)
elsif !File.directory?(ARGV.first) abort "`#{ARGV.first}' does not exist."
abort "`#{ARGV.first}' is not a directory." elsif !File.directory?(ARGV.first)
elsif ARGV.length > 1 abort "`#{ARGV.first}' is not a directory."
abort "Too many arguments; please specify only the directory to wheneverize." elsif ARGV.length > 1
end abort "Too many arguments; please specify only the directory to wheneverize."
end end
content = <<-FILE content = <<-FILE
# Use this file to easily define all of your cron jobs. # Use this file to easily define all of your cron jobs.
# #
@ -51,7 +52,7 @@ content = <<-FILE
FILE FILE
file = 'config/schedule.rb' file = 'config/schedule.rb'
base = ARGV.empty? ? '.' : ARGV.shift base = ARGV.shift
file = File.join(base, file) file = File.join(base, file)
if File.exists?(file) if File.exists?(file)

View File

@ -1,30 +1,14 @@
require 'chronic'
require 'active_support/all' require 'active_support/all'
require 'thread'
module Whenever # Bundling in http://github.com/AaronH/chronic because
autoload :JobList, 'whenever/job_list' # it's compatible with Ruby 1.9.2 and the official
autoload :Job, 'whenever/job' # gem isn't. I hope to remove this eventually.
autoload :CommandLine, 'whenever/command_line' require 'whenever/vendor/gems/chronic/lib/chronic'
module Output
autoload :Cron, 'whenever/cron'
autoload :Redirection, 'whenever/output_redirection'
end
def self.cron(options)
Whenever::JobList.new(options).generate_cron_output
end
def self.path
Dir.pwd
end
def self.rails3? require 'whenever/base'
File.exists?(File.join(path, 'script', 'rails')) require 'whenever/job_list'
end require 'whenever/job'
require 'whenever/cron'
def self.bundler? require 'whenever/output_redirection'
File.exists?(File.join(path, 'Gemfile')) require 'whenever/command_line'
end require 'whenever/version'
end

11
lib/whenever/base.rb Normal file
View File

@ -0,0 +1,11 @@
module Whenever
def self.cron(options)
Whenever::JobList.new(options).generate_cron_output
end
def self.path
Dir.pwd
end
end

View File

@ -1,62 +0,0 @@
Capistrano::Configuration.instance(:must_exist).load do
_cset(:whenever_roles) { :db }
_cset(:whenever_command) { "whenever" }
_cset(:whenever_identifier) { fetch :application }
_cset(:whenever_environment) { fetch :rails_env, "production" }
_cset(:whenever_update_flags) { "--update-crontab #{fetch :whenever_identifier} --set environment=#{fetch :whenever_environment}" }
_cset(:whenever_clear_flags) { "--clear-crontab #{fetch :whenever_identifier}" }
# Disable cron jobs at the begining of a deploy.
after "deploy:update_code", "whenever:clear_crontab"
# Write the new cron jobs near the end.
after "deploy:symlink", "whenever:update_crontab"
# If anything goes wrong, undo.
after "deploy:rollback", "whenever:update_crontab"
namespace :whenever do
desc <<-DESC
Update application's crontab entries using Whenever. You can configure \
the command used to invoke Whenever by setting the :whenever_command \
variable, which can be used with Bundler to set the command to \
"bundle exec whenever". You can configure the identifier used by setting \
the :whenever_identifier variable, which defaults to the same value configured \
for the :application variable. You can configure the environment by setting \
the :whenever_environment variable, which defaults to the same value \
configured for the :rails_env variable which itself defaults to "production". \
Finally, you can completely override all arguments to the Whenever command \
by setting the :whenever_update_flags variable. Additionally you can configure \
which servers the crontab is updated on by setting the :whenever_roles variable.
DESC
task :update_crontab do
options = { :roles => fetch(:whenever_roles) }
if find_servers(options).any?
on_rollback do
if fetch :previous_release
run "cd #{fetch :previous_release} && #{fetch :whenever_command} #{fetch :whenever_update_flags}", options
else
run "cd #{fetch :release_path} && #{fetch :whenever_command} #{fetch :whenever_clear_flags}", options
end
end
run "cd #{fetch :current_path} && #{fetch :whenever_command} #{fetch :whenever_update_flags}", options
end
end
desc <<-DESC
Clear application's crontab entries using Whenever. You can configure \
the command used to invoke Whenever by setting the :whenever_command \
variable, which can be used with Bundler to set the command to \
"bundle exec whenever". You can configure the identifier used by setting \
the :whenever_identifier variable, which defaults to the same value configured \
for the :application variable. Finally, you can completely override all \
arguments to the Whenever command by setting the :whenever_clear_flags variable. \
Additionally you can configure which servers the crontab is cleared on by setting \
the :whenever_roles variable.
DESC
task :clear_crontab do
options = { :roles => whenever_roles }
run "cd #{fetch :release_path} && #{fetch :whenever_command} #{fetch :whenever_clear_flags}", options if find_servers(options).any?
end
end
end

View File

@ -3,6 +3,7 @@ require 'tempfile'
module Whenever module Whenever
class CommandLine class CommandLine
def self.execute(options={}) def self.execute(options={})
new(options).run new(options).run
end end
@ -29,6 +30,7 @@ module Whenever
exit(1) exit(1)
end end
@options[:cut] = @options[:cut].to_i @options[:cut] = @options[:cut].to_i
end end
def run def run
@ -38,8 +40,6 @@ module Whenever
write_crontab(whenever_cron) write_crontab(whenever_cron)
else else
puts Whenever.cron(@options) puts Whenever.cron(@options)
puts "## [message] Above is your schedule file converted to cron syntax; your crontab file was not updated."
puts "## [message] Run `whenever --help' for more options."
exit(0) exit(0)
end end
end end
@ -51,90 +51,61 @@ module Whenever
end end
def whenever_cron def whenever_cron
return '' if @options[:clear] @whenever_cron ||= [comment_open, (Whenever.cron(@options) unless @options[:clear]), comment_close].compact.join("\n") + "\n"
@whenever_cron ||= [comment_open, Whenever.cron(@options), comment_close].compact.join("\n") + "\n"
end end
def read_crontab def read_crontab
return @current_crontab if @current_crontab return @current_crontab if @current_crontab
command_results = ( command = ['crontab -l']
if !stdin.tty? command << "-u #{@options[:user]}" if @options[:user]
stdin.read
else command_results = %x[#{command.join(' ')} 2> /dev/null]
command = ['crontab -l'] @current_crontab = $?.exitstatus.zero? ? prepare(command_results) : ''
command << "-u #{@options[:user]}" if @options[:user]
result = %x[#{command.join(' ')} 2> /dev/null]
$?.exitstatus.zero? ? result : ''
end
)
@current_crontab = prepare(command_results)
end end
def write_crontab(contents) def write_crontab(contents)
target_fh = ( tmp_cron_file = Tempfile.new('whenever_tmp_cron').path
if !stdin.tty? File.open(tmp_cron_file, File::WRONLY | File::APPEND) do |file|
stdout file << contents
else end
File.open(Tempfile.new('whenever_tmp_cron').path, File::WRONLY | File::APPEND)
end
)
target_fh << contents
target_fh.close
if !stdin.tty? command = ['crontab']
command << "-u #{@options[:user]}" if @options[:user]
command << tmp_cron_file
if system(command.join(' '))
action = 'written' if @options[:write]
action = 'updated' if @options[:update]
puts "[write] crontab file #{action}"
exit(0) exit(0)
else else
command = ['crontab'] warn "[fail] Couldn't write crontab; try running `whenever' with no options to ensure your schedule file is valid."
command << "-u #{@options[:user]}" if @options[:user] exit(1)
command << target_file
if system(command.join(' '))
action = 'written' if @options[:write]
action = 'updated' if @options[:update]
puts "[write] crontab file #{action}"
exit(0)
else
warn "[fail] Couldn't write crontab; try running `whenever' with no options to ensure your schedule file is valid."
exit(1)
end
end end
end end
def updated_crontab def updated_crontab
# Check for unopened or unclosed identifier blocks # Check for unopened or unclosed identifier blocks
if read_crontab =~ Regexp.new("^#{comment_open}\s*$") && (read_crontab =~ Regexp.new("^#{comment_close}\s*$")).nil? if read_crontab.index(comment_open) && !read_crontab.index(comment_close)
warn "[fail] Unclosed indentifier; Your crontab file contains '#{comment_open}', but no '#{comment_close}'" warn "[fail] Unclosed indentifier; Your crontab file contains '#{comment_open}', but no '#{comment_close}'"
exit(1) exit(1)
elsif (read_crontab =~ Regexp.new("^#{comment_open}\s*$")).nil? && read_crontab =~ Regexp.new("^#{comment_close}\s*$") elsif !read_crontab.index(comment_open) && read_crontab.index(comment_close)
warn "[fail] Unopened indentifier; Your crontab file contains '#{comment_close}', but no '#{comment_open}'" warn "[fail] Unopened indentifier; Your crontab file contains '#{comment_close}', but no '#{comment_open}'"
exit(1) exit(1)
end end
# If an existing identier block is found, replace it with the new cron entries # If an existing identier block is found, replace it with the new cron entries
if read_crontab =~ Regexp.new("^#{comment_open}\s*$") && read_crontab =~ Regexp.new("^#{comment_close}\s*$") if read_crontab.index(comment_open) && read_crontab.index(comment_close)
# If the existing crontab file contains backslashes they get lost going through gsub. read_crontab.gsub(Regexp.new("#{comment_open}.+#{comment_close}", Regexp::MULTILINE), whenever_cron.chomp)
# .gsub('\\', '\\\\\\') preserves them. Go figure.
read_crontab.gsub(Regexp.new("^#{comment_open}\s*$.+^#{comment_close}\s*$", Regexp::MULTILINE), whenever_cron.chomp.gsub('\\', '\\\\\\'))
else # Otherwise, append the new cron entries after any existing ones else # Otherwise, append the new cron entries after any existing ones
[read_crontab, whenever_cron].join("\n\n") [read_crontab, whenever_cron].join("\n\n")
end.gsub(/\n{3,}/, "\n\n") # More than two newlines becomes just two. end
end end
#
def prepare(contents) def prepare(contents)
# Strip n lines from the top of the file as specified by the :cut option. contents.split("\n")[@options[:cut]..-1].join("\n")
# Use split with a -1 limit option to ensure the join is able to rebuild
# the file with all of the original seperators in-tact.
stripped_contents = contents.split($/,-1)[@options[:cut]..-1].join($/)
# Some cron implementations require all non-comment lines to be newline-
# terminated. (issue #95) Strip all newlines and replace with the default
# platform record seperator ($/)
stripped_contents.gsub!(/\s+$/, $/)
end end
def comment_base def comment_base
@ -149,12 +120,5 @@ module Whenever
"# End #{comment_base}" "# End #{comment_base}"
end end
def stdin
$stdin
end
def stdout
$stdout
end
end end
end end

View File

@ -1,24 +1,19 @@
module Whenever module Whenever
module Output module Output
class Cron class Cron
REGEX = /^.+ .+ .+ .+ .+.?$/
attr_accessor :time, :task attr_accessor :time, :task
def initialize(time = nil, task = nil, at = nil) def initialize(time = nil, task = nil, at = nil, output_redirection = nil)
@time = time @time = time
@task = task @task = task
@at = at.is_a?(String) ? (Chronic.parse(at) || 0) : (at || 0) @at = at.is_a?(String) ? (Chronic.parse(at) || 0) : (at || 0)
@output_redirection = output_redirection
end end
def self.enumerate(item, detect_cron = true) def self.enumerate(item)
if item and item.is_a?(String) if item and item.is_a?(String)
items = items = item.split(',')
if detect_cron && item =~ REGEX
[item]
else
item.split(',')
end
else else
items = item items = item
items = [items] unless items and items.respond_to?(:each) items = [items] unless items and items.respond_to?(:each)
@ -28,48 +23,42 @@ module Whenever
def self.output(times, job) def self.output(times, job)
enumerate(times).each do |time| enumerate(times).each do |time|
enumerate(job.at, false).each do |at| enumerate(job.at).each do |at|
yield new(time, job.output, at).output yield new(time, job.output, at, job.output_redirection).output
end end
end end
end end
def output def output
[time_in_cron_syntax, task].compact.join(' ').strip [time_in_cron_syntax, task, output_redirection].compact.join(' ').strip
end end
def time_in_cron_syntax def time_in_cron_syntax
case @time case @time
when REGEX then @time # raw cron sytax given
when Symbol then parse_symbol when Symbol then parse_symbol
when String then parse_as_string when String then parse_as_string
else parse_time else parse_time
end end
end end
def output_redirection
Whenever::Output::Cron::OutputRedirection.new(@output_redirection).to_s unless @output_redirection == :not_set
end
protected protected
def parse_symbol def parse_symbol
shortcut = case @time shortcut = case @time
when :reboot then '@reboot' when :reboot then '@reboot'
when :year then 12.months when :year, :yearly then '@annually'
when :yearly, when :day, :daily then '@daily'
:annually then '@annually' when :midnight then '@midnight'
when :day then 1.day when :month, :monthly then '@monthly'
when :daily then '@daily' when :week, :weekly then '@weekly'
when :midnight then '@midnight' when :hour, :hourly then '@hourly'
when :month then 1.month
when :monthly then '@monthly'
when :week then 1.week
when :weekly then '@weekly'
when :hour then 1.hour
when :hourly then '@hourly'
end end
if shortcut.is_a?(Numeric) if shortcut
@time = shortcut
parse_time
elsif shortcut
if @at.is_a?(Time) || (@at.is_a?(Numeric) && @at > 0) if @at.is_a?(Time) || (@at.is_a?(Numeric) && @at > 0)
raise ArgumentError, "You cannot specify an ':at' when using the shortcuts for times." raise ArgumentError, "You cannot specify an ':at' when using the shortcuts for times."
else else
@ -142,6 +131,7 @@ module Whenever
output[0, max_occurances].join(',') output[0, max_occurances].join(',')
end end
end end
end end
end end

View File

@ -1,28 +1,21 @@
module Whenever module Whenever
class Job class Job
attr_reader :at
attr_reader :at, :output_redirection
def initialize(options = {}) def initialize(options = {})
@options = options @options = options
@at = options.delete(:at)
@template = options.delete(:template) @at = options[:at]
@job_template = options.delete(:job_template) || ":job" @output_redirection = options.has_key?(:output) ? options[:output] : :not_set
@options[:output] = Whenever::Output::Redirection.new(options[:output]).to_s if options.has_key?(:output)
@options[:environment] ||= :production @options[:environment] ||= :production
@options[:path] ||= Whenever.path @options[:path] ||= Whenever.path
end end
def output def output
job = process_template(@template, @options).strip @options[:template].dup.gsub(/:\w+/) do |key|
process_template(@job_template, { :job => job }).strip
end
protected
def process_template(template, options)
template.gsub(/:\w+/) do |key|
before_and_after = [$`[-1..-1], $'[0..0]] before_and_after = [$`[-1..-1], $'[0..0]]
option = options[key.sub(':', '').to_sym] option = @options[key.sub(':', '').to_sym]
if before_and_after.all? { |c| c == "'" } if before_and_after.all? { |c| c == "'" }
escape_single_quotes(option) escape_single_quotes(option)
@ -33,6 +26,8 @@ module Whenever
end end
end end
end end
protected
def escape_single_quotes(str) def escape_single_quotes(str)
str.gsub(/'/) { "'\\''" } str.gsub(/'/) { "'\\''" }
@ -41,5 +36,6 @@ module Whenever
def escape_double_quotes(str) def escape_double_quotes(str)
str.gsub(/"/) { '\"' } str.gsub(/"/) { '\"' }
end end
end end
end end

View File

@ -1,27 +1,31 @@
module Whenever module Whenever
class JobList class JobList
def initialize(options) def initialize(options)
@jobs, @env, @set_variables, @pre_set_variables = {}, {}, {}, {} @jobs, @env, @set_variables = {}, {}, {}
if options.is_a? String case options
options = { :string => options } when String
end config = options
when Hash
pre_set(options[:set]) config = if options[:string]
options[:string]
setup = File.read("#{File.expand_path(File.dirname(__FILE__))}/setup.rb") elsif options[:file]
schedule = if options[:string] File.read(options[:file])
options[:string] end
elsif options[:file] pre_set(options[:set])
File.read(options[:file])
end end
instance_eval(setup + schedule, options[:file] || '<eval>') # Load all job type files.
Dir["#{File.expand_path(File.dirname(__FILE__))}/job_types/*.rb"].each do |file|
eval(File.read(file))
end
eval(config)
end end
def set(variable, value) def set(variable, value)
variable = variable.to_sym return if instance_variable_defined?("@#{variable}".to_sym)
return if @pre_set_variables[variable]
instance_variable_set("@#{variable}".to_sym, value) instance_variable_set("@#{variable}".to_sym, value)
self.class.send(:attr_reader, variable.to_sym) self.class.send(:attr_reader, variable.to_sym)
@ -55,7 +59,9 @@ module Whenever
end end
end end
def generate_cron_output def generate_cron_output
set_path_environment_variable
[environment_variables, cron_jobs].compact.join [environment_variables, cron_jobs].compact.join
end end
@ -73,20 +79,29 @@ module Whenever
pairs.each do |pair| pairs.each do |pair|
next unless pair.index('=') next unless pair.index('=')
variable, value = *pair.split('=') variable, value = *pair.split('=')
unless variable.blank? || value.blank? set(variable.strip.to_sym, value.strip) unless variable.blank? || value.blank?
variable = variable.strip.to_sym
set(variable, value.strip)
@pre_set_variables[variable] = value
end
end end
end end
def set_path_environment_variable
return if path_should_not_be_set_automatically?
@env[:PATH] = read_path unless read_path.blank?
end
def read_path
ENV['PATH'] if ENV
end
def path_should_not_be_set_automatically?
@set_path_automatically === false || @env[:PATH] || @env["PATH"]
end
def environment_variables def environment_variables
return if @env.empty? return if @env.empty?
output = [] output = []
@env.each do |key, val| @env.each do |key, val|
output << "#{key}=#{val.blank? ? '""' : val}\n" output << "#{key}=#{val}\n"
end end
output << "\n" output << "\n"
@ -141,5 +156,6 @@ module Whenever
shortcut_jobs.join + combine(regular_jobs).join shortcut_jobs.join + combine(regular_jobs).join
end end
end end
end end

View File

@ -0,0 +1,3 @@
job_type :command, %(:task)
job_type :runner, %(cd :path && script/runner -e :environment ':task')
job_type :rake, %(cd :path && RAILS_ENV=:environment /usr/bin/env rake :task)

View File

@ -1,55 +1,59 @@
module Whenever module Whenever
module Output module Output
class Redirection class Cron
def initialize(output) class OutputRedirection
@output = output
end def initialize(output)
@output = output
def to_s end
return '' unless defined?(@output)
case @output def to_s
when String then redirect_from_string return '' unless defined?(@output)
when Hash then redirect_from_hash case @output
when NilClass then ">> /dev/null 2>&1" when String then redirect_from_string
else '' when Hash then redirect_from_hash
end when NilClass then ">> /dev/null 2>&1"
end else ''
end
protected end
def stdout protected
return unless @output.has_key?(:standard)
@output[:standard].nil? ? '/dev/null' : @output[:standard] def stdout
end return unless @output.has_key?(:standard)
@output[:standard].nil? ? '/dev/null' : @output[:standard]
def stderr
return unless @output.has_key?(:error)
@output[:error].nil? ? '/dev/null' : @output[:error]
end
def redirect_from_hash
case
when stdout == '/dev/null' && stderr == '/dev/null'
"> /dev/null 2>&1"
when stdout && stderr == '/dev/null'
">> #{stdout} 2> /dev/null"
when stdout && stderr
">> #{stdout} 2>> #{stderr}"
when stderr == '/dev/null'
"2> /dev/null"
when stderr
"2>> #{stderr}"
when stdout == '/dev/null'
"> /dev/null"
when stdout
">> #{stdout}"
else
''
end end
end
def redirect_from_string def stderr
">> #{@output} 2>&1" return unless @output.has_key?(:error)
@output[:error].nil? ? '/dev/null' : @output[:error]
end
def redirect_from_hash
case
when stdout == '/dev/null' && stderr == '/dev/null'
"> /dev/null 2>&1"
when stdout && stderr == '/dev/null'
">> #{stdout} 2> /dev/null"
when stdout && stderr
">> #{stdout} 2>> #{stderr}"
when stderr == '/dev/null'
"2> /dev/null"
when stderr
"2>> #{stderr}"
when stdout == '/dev/null'
"> /dev/null"
when stdout
">> #{stdout}"
else
''
end
end
def redirect_from_string
">> #{@output} 2>&1"
end
end end
end end
end end

View File

@ -1,24 +0,0 @@
# Environemnt defaults to production
set :environment, "production"
# Path defaults to the directory `whenever` was run from
set :path, Whenever.path
# All jobs are wrapped in this template.
# http://blog.scoutapp.com/articles/2010/09/07/rvm-and-cron-in-production
set :job_template, "/bin/bash -l -c ':job'"
job_type :command, ":task :output"
# Run rake through bundler if possible
if Whenever.bundler?
job_type :rake, "cd :path && RAILS_ENV=:environment bundle exec rake :task --silent :output"
else
job_type :rake, "cd :path && RAILS_ENV=:environment rake :task --silent :output"
end
# Create a runner job that's appropriate for the Rails version,
if Whenever.rails3?
job_type :runner, "cd :path && script/rails runner -e :environment ':task' :output"
else
job_type :runner, "cd :path && script/runner -e :environment ':task' :output"
end

1
lib/whenever/vendor/gems/chronic vendored Submodule

@ -0,0 +1 @@
Subproject commit d027ad09333ac49e9eb368c659c5243b515a7694

View File

@ -1,3 +1,3 @@
module Whenever module Whenever
VERSION = '0.6.8' VERSION = '0.5.0'
end end unless defined?(Whenever::VERSION)

View File

@ -65,6 +65,8 @@ This shouldn't get replaced
# End Whenever generated tasks for: Other identifier # End Whenever generated tasks for: Other identifier
EXISTING_CRON EXISTING_CRON
@command.expects(:read_crontab).at_least_once.returns(existing)
new_cron = <<-NEW_CRON new_cron = <<-NEW_CRON
# Something # Something
@ -77,61 +79,38 @@ This shouldn't get replaced
# End Whenever generated tasks for: Other identifier # End Whenever generated tasks for: Other identifier
NEW_CRON NEW_CRON
@command.expects(:read_crontab).at_least_once.returns(existing)
assert_equal new_cron, @command.send(:updated_crontab) assert_equal new_cron, @command.send(:updated_crontab)
@command.expects(:write_crontab).with(new_cron).returns(true) @command.expects(:write_crontab).with(new_cron).returns(true)
assert @command.run assert @command.run
end end
end end
context "A command line update that contains backslashes" do
setup do
@existing = <<-EXISTING_CRON
# Begin Whenever generated tasks for: My identifier
script/runner -e production 'puts '\\''hello'\\'''
# End Whenever generated tasks for: My identifier
EXISTING_CRON
File.expects(:exists?).with('config/schedule.rb').returns(true)
@command = Whenever::CommandLine.new(:update => true, :identifier => 'My identifier')
@command.expects(:read_crontab).at_least_once.returns(@existing)
@command.expects(:whenever_cron).returns(@existing)
end
should "replace the existing block with the backslashes in tact" do
assert_equal @existing, @command.send(:updated_crontab)
end
end
context "A command line update with an identifier similar to an existing one in the crontab already" do
setup do
@existing = <<-EXISTING_CRON
# Begin Whenever generated tasks for: WheneverExisting
# End Whenever generated tasks for: WheneverExisting
EXISTING_CRON
@new = <<-NEW_CRON
# Begin Whenever generated tasks for: Whenever
# End Whenever generated tasks for: Whenever
NEW_CRON
File.expects(:exists?).with('config/schedule.rb').returns(true)
@command = Whenever::CommandLine.new(:update => true, :identifier => 'Whenever')
@command.expects(:read_crontab).at_least_once.returns(@existing)
@command.expects(:whenever_cron).returns(@new)
end
should "append the similarly named command" do
assert_equal @existing + "\n" + @new, @command.send(:updated_crontab)
end
end
context "A command line clear" do context "A command line delete" do
setup do setup do
File.expects(:exists?).with('config/schedule.rb').returns(true) File.expects(:exists?).with('config/schedule.rb').returns(true)
@command = Whenever::CommandLine.new(:clear => true, :identifier => 'My identifier') @command = Whenever::CommandLine.new(:clear => true, :identifier => 'My identifier')
@task = "#{two_hours} /my/command" @task = "#{two_hours} /my/command"
end end
should "clear an existing block if the identifier matches" do should "add an empty identifier block if there is no existing one" do
existing = '# Existing crontab'
@command.expects(:read_crontab).at_least_once.returns(existing)
new_cron = <<-EXPECTED
#{existing}
# Begin Whenever generated tasks for: My identifier
# End Whenever generated tasks for: My identifier
EXPECTED
assert_equal new_cron, @command.send(:updated_crontab)
@command.expects(:write_crontab).with(new_cron).returns(true)
assert @command.run
end
should "delete an existing block if the identifier matches" do
existing = <<-EXISTING_CRON existing = <<-EXISTING_CRON
# Something # Something
@ -145,17 +124,20 @@ This shouldn't get replaced
EXISTING_CRON EXISTING_CRON
@command.expects(:read_crontab).at_least_once.returns(existing) @command.expects(:read_crontab).at_least_once.returns(existing)
new_cron = <<-NEW_CRON new_cron = <<-NEW_CRON
# Something # Something
# Begin Whenever generated tasks for: My identifier
# End Whenever generated tasks for: My identifier
# Begin Whenever generated tasks for: Other identifier # Begin Whenever generated tasks for: Other identifier
This shouldn't get replaced This shouldn't get replaced
# End Whenever generated tasks for: Other identifier # End Whenever generated tasks for: Other identifier
NEW_CRON NEW_CRON
assert_equal new_cron, @command.send(:updated_crontab) assert_equal new_cron, @command.send(:updated_crontab)
@command.expects(:write_crontab).with(new_cron).returns(true) @command.expects(:write_crontab).with(new_cron).returns(true)
assert @command.run assert @command.run
end end
@ -197,7 +179,6 @@ NEW_CRON
setup do setup do
@output = Whenever.cron :set => 'environment=serious', :string => \ @output = Whenever.cron :set => 'environment=serious', :string => \
<<-file <<-file
set :job_template, nil
set :environment, :silly set :environment, :silly
set :path, '/my/path' set :path, '/my/path'
every 2.hours do every 2.hours do
@ -215,7 +196,6 @@ NEW_CRON
setup do setup do
@output = Whenever.cron :set => 'environment=serious&path=/serious/path', :string => \ @output = Whenever.cron :set => 'environment=serious&path=/serious/path', :string => \
<<-file <<-file
set :job_template, nil
set :environment, :silly set :environment, :silly
set :path, '/silly/path' set :path, '/silly/path'
every 2.hours do every 2.hours do
@ -233,7 +213,6 @@ NEW_CRON
setup do setup do
@output = Whenever.cron :set => ' environment = serious& path =/serious/path', :string => \ @output = Whenever.cron :set => ' environment = serious& path =/serious/path', :string => \
<<-file <<-file
set :job_template, nil
set :environment, :silly set :environment, :silly
set :path, '/silly/path' set :path, '/silly/path'
every 2.hours do every 2.hours do
@ -251,7 +230,6 @@ NEW_CRON
setup do setup do
@output = Whenever.cron :set => ' environment=', :string => \ @output = Whenever.cron :set => ' environment=', :string => \
<<-file <<-file
set :job_template, nil
set :environment, :silly set :environment, :silly
set :path, '/silly/path' set :path, '/silly/path'
every 2.hours do every 2.hours do
@ -281,7 +259,8 @@ My whenever job that was already here
# End Whenever generated tasks for: My identifier # End Whenever generated tasks for: My identifier
EXISTING_CRON EXISTING_CRON
assert_equal existing, @command.send(:prepare, existing) # here-doc adds an extra newline we need removed
assert_equal existing.strip, @command.send(:prepare, existing)
end end
should "trim off the top lines of the file" do should "trim off the top lines of the file" do
@ -301,61 +280,8 @@ My whenever job that was already here
# End Whenever generated tasks for: My identifier # End Whenever generated tasks for: My identifier
NEW_CRON NEW_CRON
assert_equal new_cron, @command.send(:prepare, existing) # here-doc adds an extra newline we need removed
end assert_equal new_cron.strip, @command.send(:prepare, existing)
should "preserve terminating newlines in files" do
@command = Whenever::CommandLine.new(:update => true, :identifier => 'My identifier')
existing = <<-EXISTING_CRON
# Begin Whenever generated tasks for: My identifier
My whenever job that was already here
# End Whenever generated tasks for: My identifier
# A non-Whenever task
My non-whenever job that was already here
EXISTING_CRON
assert_equal existing, @command.send(:prepare, existing)
end
end
context 'A command line update that reads the cron from stdin writes to stdout' do
setup do
@mock_stdin = StringIO.new(<<-EXISTING_CRON)
# Something
# Begin Whenever generated tasks for: My identifier
My whenever job that was already here
# End Whenever generated tasks for: My identifier
EXISTING_CRON
@mock_stdout = StringIO.new
@mock_stdin.stubs(:tty?).returns(false)
File.expects(:exists?).with('config/schedule.rb').returns(true)
@command = Whenever::CommandLine.new(:update => true, :identifier => 'My identifier')
@task = "#{two_hours} /my/command"
Whenever.expects(:cron).returns(@task)
@command.stubs(:stdin).returns(@mock_stdin)
@command.stubs(:stdout).returns(@mock_stdout)
end
should "update the file and write out a new file correctly" do
begin
@command.run
@mock_stdout.rewind
asset_equal @mock_stdout.read, <<-NEW_CRON
# Something
# Begin Whenever generated tasks for: My identifier
#{@task}
# End Whenever generated tasks for: My identifier
NEW_CRON
rescue SystemExit => e
assert_equal 0, e.status
end
end end
end end

View File

@ -6,7 +6,6 @@ class OutputAtTest < Test::Unit::TestCase
setup do setup do
@output = Whenever.cron \ @output = Whenever.cron \
<<-file <<-file
set :job_template, nil
every "weekday", :at => '5:02am' do every "weekday", :at => '5:02am' do
command "blahblah" command "blahblah"
end end
@ -22,7 +21,6 @@ class OutputAtTest < Test::Unit::TestCase
setup do setup do
@output = Whenever.cron \ @output = Whenever.cron \
<<-file <<-file
set :job_template, nil
every "weekday", :at => %w(5:02am 3:52pm) do every "weekday", :at => %w(5:02am 3:52pm) do
command "blahblah" command "blahblah"
end end
@ -39,7 +37,6 @@ class OutputAtTest < Test::Unit::TestCase
setup do setup do
@output = Whenever.cron \ @output = Whenever.cron \
<<-file <<-file
set :job_template, nil
every "weekday", :at => '5:02am, 3:52pm' do every "weekday", :at => '5:02am, 3:52pm' do
command "blahblah" command "blahblah"
end end
@ -56,7 +53,6 @@ class OutputAtTest < Test::Unit::TestCase
setup do setup do
@output = Whenever.cron \ @output = Whenever.cron \
<<-file <<-file
set :job_template, nil
every "weekday", :at => '5:02am, 3:02pm' do every "weekday", :at => '5:02am, 3:02pm' do
command "blahblah" command "blahblah"
end end
@ -72,7 +68,6 @@ class OutputAtTest < Test::Unit::TestCase
setup do setup do
@output = Whenever.cron \ @output = Whenever.cron \
<<-file <<-file
set :job_template, nil
every "mon,wed,fri", :at => '5:02am, 3:02pm' do every "mon,wed,fri", :at => '5:02am, 3:02pm' do
command "blahblah" command "blahblah"
end end
@ -88,7 +83,6 @@ class OutputAtTest < Test::Unit::TestCase
setup do setup do
@output = Whenever.cron \ @output = Whenever.cron \
<<-file <<-file
set :job_template, nil
set :path, '/your/path' set :path, '/your/path'
every "mon,wed,fri", :at => '5:02am, 3:02pm' do every "mon,wed,fri", :at => '5:02am, 3:02pm' do
runner "blahblah" runner "blahblah"
@ -105,7 +99,6 @@ class OutputAtTest < Test::Unit::TestCase
setup do setup do
@output = Whenever.cron \ @output = Whenever.cron \
<<-file <<-file
set :job_template, nil
set :path, '/your/path' set :path, '/your/path'
every "mon,wed,fri", :at => '5:02am, 3:02pm' do every "mon,wed,fri", :at => '5:02am, 3:02pm' do
rake "blah:blah" rake "blah:blah"
@ -114,7 +107,7 @@ class OutputAtTest < Test::Unit::TestCase
end end
should "output the rake task using one entry because the times are aligned" do should "output the rake task using one entry because the times are aligned" do
assert_match '2 5,15 * * 1,3,5 cd /your/path && RAILS_ENV=production bundle exec rake blah:blah --silent', @output assert_match '2 5,15 * * 1,3,5 cd /your/path && RAILS_ENV=production /usr/bin/env rake blah:blah', @output
end end
end end
@ -122,7 +115,6 @@ class OutputAtTest < Test::Unit::TestCase
setup do setup do
@output = Whenever.cron \ @output = Whenever.cron \
<<-file <<-file
set :job_template, nil
every [1.month, 1.day], :at => 'january 5:02am, june 17th at 2:22pm, june 3rd at 3:33am' do every [1.month, 1.day], :at => 'january 5:02am, june 17th at 2:22pm, june 3rd at 3:33am' do
command "blahblah" command "blahblah"
end end
@ -146,7 +138,6 @@ class OutputAtTest < Test::Unit::TestCase
setup do setup do
@output = Whenever.cron \ @output = Whenever.cron \
<<-file <<-file
set :job_template, nil
every :reboot do every :reboot do
command "command_1" command "command_1"
command "command_2" command "command_2"
@ -164,9 +155,8 @@ class OutputAtTest < Test::Unit::TestCase
setup do setup do
@output = Whenever.cron \ @output = Whenever.cron \
<<-file <<-file
set :job_template, nil
set :path, '/your/path' set :path, '/your/path'
every :daily do every :day do
rake "blah:blah" rake "blah:blah"
runner "runner_1" runner "runner_1"
command "command_1" command "command_1"
@ -177,7 +167,7 @@ class OutputAtTest < Test::Unit::TestCase
end end
should "output all of the commands @daily" do should "output all of the commands @daily" do
assert_match '@daily cd /your/path && RAILS_ENV=production bundle exec rake blah:blah --silent', @output assert_match '@daily cd /your/path && RAILS_ENV=production /usr/bin/env rake blah:blah', @output
assert_match %(@daily cd /your/path && script/runner -e production 'runner_1'), @output assert_match %(@daily cd /your/path && script/runner -e production 'runner_1'), @output
assert_match '@daily command_1', @output assert_match '@daily command_1', @output
assert_match %(@daily cd /your/path && script/runner -e production 'runner_2'), @output assert_match %(@daily cd /your/path && script/runner -e production 'runner_2'), @output
@ -189,7 +179,6 @@ class OutputAtTest < Test::Unit::TestCase
setup do setup do
@output = Whenever.cron \ @output = Whenever.cron \
<<-file <<-file
set :job_template, nil
every 5.minutes, :at => 1 do every 5.minutes, :at => 1 do
command "blahblah" command "blahblah"
end end
@ -205,7 +194,6 @@ class OutputAtTest < Test::Unit::TestCase
setup do setup do
@output = Whenever.cron \ @output = Whenever.cron \
<<-file <<-file
set :job_template, nil
every 4.minutes, :at => 2 do every 4.minutes, :at => 2 do
command "blahblah" command "blahblah"
end end
@ -221,7 +209,6 @@ class OutputAtTest < Test::Unit::TestCase
setup do setup do
@output = Whenever.cron \ @output = Whenever.cron \
<<-file <<-file
set :job_template, nil
every 3.minutes, :at => 7 do every 3.minutes, :at => 7 do
command "blahblah" command "blahblah"
end end
@ -237,7 +224,6 @@ class OutputAtTest < Test::Unit::TestCase
setup do setup do
@output = Whenever.cron \ @output = Whenever.cron \
<<-file <<-file
set :job_template, nil
every 2.minutes, :at => 27 do every 2.minutes, :at => 27 do
command "blahblah" command "blahblah"
end end
@ -248,21 +234,4 @@ class OutputAtTest < Test::Unit::TestCase
assert_match '27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59 * * * * blahblah', @output assert_match '27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59 * * * * blahblah', @output
end end
end end
context "using raw cron syntax" do
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every '0 0 27,31 * *' do
command "blahblah"
end
file
end
should "output the command using the same cron syntax" do
assert_match '0 0 27,31 * * blahblah', @output
end
end
end end

View File

@ -4,11 +4,10 @@ class OutputDefaultDefinedJobsTest < Test::Unit::TestCase
# command # command
context "A plain command with the job template set to nil" do context "A plain command" do
setup do setup do
@output = Whenever.cron \ @output = Whenever.cron \
<<-file <<-file
set :job_template, nil
every 2.hours do every 2.hours do
command "blahblah" command "blahblah"
end end
@ -20,64 +19,12 @@ class OutputDefaultDefinedJobsTest < Test::Unit::TestCase
end end
end end
context "A plain command with no job template set" do
setup do
@output = Whenever.cron \
<<-file
every 2.hours do
command "blahblah"
end
file
end
should "output the command with the default job template" do
assert_match /^.+ .+ .+ .+ \/bin\/bash -l -c 'blahblah'$/, @output
end
end
context "A plain command that overrides the job_template set" do
setup do
@output = Whenever.cron \
<<-file
set :job_template, "/bin/bash -l -c ':job'"
every 2.hours do
command "blahblah", :job_template => "/bin/sh -l -c ':job'"
end
file
end
should "output the command using that job_template" do
assert_match /^.+ .+ .+ .+ \/bin\/sh -l -c 'blahblah'$/, @output
assert_no_match /bash/, @output
end
end
context "A plain command that is conditional on default environent and path" do
setup do
Whenever.expects(:path).at_least_once.returns('/what/you/want')
@output = Whenever.cron \
<<-file
set :job_template, nil
if environment == 'production' && path == '/what/you/want'
every 2.hours do
command "blahblah"
end
end
file
end
should "output the command" do
assert_match /blahblah/, @output
end
end
# runner # runner
context "A runner with path set" do context "A runner with path set" do
setup do setup do
@output = Whenever.cron \ @output = Whenever.cron \
<<-file <<-file
set :job_template, nil
set :path, '/my/path' set :path, '/my/path'
every 2.hours do every 2.hours do
runner 'blahblah' runner 'blahblah'
@ -94,7 +41,6 @@ class OutputDefaultDefinedJobsTest < Test::Unit::TestCase
setup do setup do
@output = Whenever.cron \ @output = Whenever.cron \
<<-file <<-file
set :job_template, nil
set :path, '/my/path' set :path, '/my/path'
every 2.hours do every 2.hours do
runner "blahblah", :path => '/some/other/path' runner "blahblah", :path => '/some/other/path'
@ -107,31 +53,12 @@ class OutputDefaultDefinedJobsTest < Test::Unit::TestCase
end end
end end
context "A runner for a Rails 3 app" do
setup do
Whenever.expects(:path).at_least_once.returns('/my/path')
Whenever.expects(:rails3?).returns(true)
@output = Whenever.cron \
<<-file
set :job_template, nil
every 2.hours do
runner 'blahblah'
end
file
end
should "use the Rails 3 runner job by default" do
assert_match two_hours + %( cd /my/path && script/rails runner -e production 'blahblah'), @output
end
end
# rake # rake
context "A rake command with path set" do context "A rake command with path set" do
setup do setup do
@output = Whenever.cron \ @output = Whenever.cron \
<<-file <<-file
set :job_template, nil
set :path, '/my/path' set :path, '/my/path'
every 2.hours do every 2.hours do
rake "blahblah" rake "blahblah"
@ -140,25 +67,7 @@ class OutputDefaultDefinedJobsTest < Test::Unit::TestCase
end end
should "output the rake command using that path" do should "output the rake command using that path" do
assert_match two_hours + ' cd /my/path && RAILS_ENV=production bundle exec rake blahblah --silent', @output assert_match two_hours + ' cd /my/path && RAILS_ENV=production /usr/bin/env rake blahblah', @output
end
end
context "A rake for a non-bundler app" do
setup do
Whenever.expects(:path).at_least_once.returns('/my/path')
Whenever.expects(:bundler?).returns(false)
@output = Whenever.cron \
<<-file
set :job_template, nil
every 2.hours do
rake 'blahblah'
end
file
end
should "not use invoke through bundler" do
assert_match two_hours + ' cd /my/path && RAILS_ENV=production rake blahblah --silent', @output
end end
end end
@ -166,7 +75,6 @@ class OutputDefaultDefinedJobsTest < Test::Unit::TestCase
setup do setup do
@output = Whenever.cron \ @output = Whenever.cron \
<<-file <<-file
set :job_template, nil
set :path, '/my/path' set :path, '/my/path'
every 2.hours do every 2.hours do
rake "blahblah", :path => '/some/other/path' rake "blahblah", :path => '/some/other/path'
@ -175,7 +83,7 @@ class OutputDefaultDefinedJobsTest < Test::Unit::TestCase
end end
should "output the rake command using that path" do should "output the rake command using that path" do
assert_match two_hours + ' cd /some/other/path && RAILS_ENV=production bundle exec rake blahblah --silent', @output assert_match two_hours + ' cd /some/other/path && RAILS_ENV=production /usr/bin/env rake blahblah', @output
end end
end end

View File

@ -6,7 +6,6 @@ class OutputDefinedJobTest < Test::Unit::TestCase
setup do setup do
@output = Whenever.cron \ @output = Whenever.cron \
<<-file <<-file
set :job_template, nil
job_type :some_job, "before :task after" job_type :some_job, "before :task after"
every 2.hours do every 2.hours do
some_job "during" some_job "during"
@ -23,7 +22,6 @@ class OutputDefinedJobTest < Test::Unit::TestCase
setup do setup do
@output = Whenever.cron \ @output = Whenever.cron \
<<-file <<-file
set :job_template, nil
job_type :some_job, "before :task after :option1 :option2" job_type :some_job, "before :task after :option1 :option2"
every 2.hours do every 2.hours do
some_job "during", :option1 => 'happy', :option2 => 'birthday' some_job "during", :option1 => 'happy', :option2 => 'birthday'
@ -40,7 +38,6 @@ class OutputDefinedJobTest < Test::Unit::TestCase
setup do setup do
@output = Whenever.cron \ @output = Whenever.cron \
<<-file <<-file
set :job_template, nil
job_type :some_job, "before :task after :option1" job_type :some_job, "before :task after :option1"
set :option1, 'happy' set :option1, 'happy'
every 2.hours do every 2.hours do
@ -58,7 +55,6 @@ class OutputDefinedJobTest < Test::Unit::TestCase
setup do setup do
@output = Whenever.cron \ @output = Whenever.cron \
<<-file <<-file
set :job_template, nil
job_type :some_job, "before :task after :option1" job_type :some_job, "before :task after :option1"
set :option1, 'global' set :option1, 'global'
every 2.hours do every 2.hours do
@ -76,7 +72,6 @@ class OutputDefinedJobTest < Test::Unit::TestCase
setup do setup do
@output = Whenever.cron \ @output = Whenever.cron \
<<-file <<-file
set :job_template, nil
job_type :some_job, "before :task after :option1" job_type :some_job, "before :task after :option1"
every 2.hours do every 2.hours do
some_job "during", :option2 => 'happy' some_job "during", :option2 => 'happy'
@ -91,11 +86,10 @@ class OutputDefinedJobTest < Test::Unit::TestCase
context "A defined job that uses a :path where none is explicitly set" do context "A defined job that uses a :path where none is explicitly set" do
setup do setup do
Whenever.stubs(:path).returns('/my/path') Whenever.expects(:path).returns('/my/path')
@output = Whenever.cron \ @output = Whenever.cron \
<<-file <<-file
set :job_template, nil
job_type :some_job, "cd :path && :task" job_type :some_job, "cd :path && :task"
every 2.hours do every 2.hours do
some_job 'blahblah' some_job 'blahblah'

View File

@ -8,8 +8,6 @@ class OutputEnvTest < Test::Unit::TestCase
<<-file <<-file
env :MYVAR, 'blah' env :MYVAR, 'blah'
env 'MAILTO', "someone@example.com" env 'MAILTO', "someone@example.com"
env :BLANKVAR, ''
env :NILVAR, nil
file file
end end
@ -20,14 +18,39 @@ class OutputEnvTest < Test::Unit::TestCase
should "output MAILTO environment variable" do should "output MAILTO environment variable" do
assert_match "MAILTO=someone@example.com", @output assert_match "MAILTO=someone@example.com", @output
end end
end
should "output BLANKVAR environment variable" do
assert_match "BLANKVAR=\"\"", @output context "No PATH environment variable set" do
setup do
Whenever::JobList.any_instance.expects(:read_path).at_least_once.returns('/usr/local/bin')
@output = Whenever.cron ""
end end
should "output NILVAR environment variable" do should "add a PATH variable based on the user's PATH" do
assert_match "NILVAR=\"\"", @output assert_match "PATH=/usr/local/bin", @output
end
end
context "A PATH environment variable set" do
setup do
Whenever::JobList.stubs(:read_path).returns('/usr/local/bin')
@output = Whenever.cron "env :PATH, '/my/path'"
end
should "use that path and the user's PATH" do
assert_match "PATH=/my/path", @output
assert_no_match /local/, @output
end
end
context "No PATH set and instructed not to automatically load the user's path" do
setup do
@output = Whenever.cron "set :set_path_automatically, false"
end
should "not have a PATH set" do
assert_no_match /PATH/, @output
end end
end end
end end

View File

@ -6,7 +6,6 @@ class OutputRedirectionTest < Test::Unit::TestCase
setup do setup do
@output = Whenever.cron \ @output = Whenever.cron \
<<-file <<-file
set :job_template, nil
set :output, nil set :output, nil
every 2.hours do every 2.hours do
command "blahblah" command "blahblah"
@ -24,7 +23,6 @@ class OutputRedirectionTest < Test::Unit::TestCase
setup do setup do
@output = Whenever.cron \ @output = Whenever.cron \
<<-file <<-file
set :job_template, nil
set :output, 'logfile.log' set :output, 'logfile.log'
every 2.hours do every 2.hours do
command "blahblah" command "blahblah"
@ -41,7 +39,6 @@ class OutputRedirectionTest < Test::Unit::TestCase
setup do setup do
@output = Whenever.cron \ @output = Whenever.cron \
<<-file <<-file
set :job_template, nil
every 2.hours do every 2.hours do
command "blahblah", :output => {:standard => 'dev_null', :error => 'dev_err'} command "blahblah", :output => {:standard => 'dev_null', :error => 'dev_err'}
end end
@ -57,7 +54,6 @@ class OutputRedirectionTest < Test::Unit::TestCase
setup do setup do
@output = Whenever.cron \ @output = Whenever.cron \
<<-file <<-file
set :job_template, nil
set :output, 'logfile.log' set :output, 'logfile.log'
every 2.hours do every 2.hours do
command "blahblah", :output => 'otherlog.log' command "blahblah", :output => 'otherlog.log'
@ -75,7 +71,6 @@ class OutputRedirectionTest < Test::Unit::TestCase
setup do setup do
@output = Whenever.cron \ @output = Whenever.cron \
<<-file <<-file
set :job_template, nil
set :output, 'logfile.log' set :output, 'logfile.log'
every 2.hours do every 2.hours do
command "blahblah", :output => {:error => 'dev_err', :standard => 'dev_null' } command "blahblah", :output => {:error => 'dev_err', :standard => 'dev_null' }
@ -93,7 +88,6 @@ class OutputRedirectionTest < Test::Unit::TestCase
setup do setup do
@output = Whenever.cron \ @output = Whenever.cron \
<<-file <<-file
set :job_template, nil
set :output, 'logfile.log' set :output, 'logfile.log'
every 2.hours do every 2.hours do
command "blahblah", :output => false command "blahblah", :output => false
@ -111,7 +105,6 @@ class OutputRedirectionTest < Test::Unit::TestCase
setup do setup do
@output = Whenever.cron :set => 'output=otherlog.log', :string => \ @output = Whenever.cron :set => 'output=otherlog.log', :string => \
<<-file <<-file
set :job_template, nil
set :output, 'logfile.log' set :output, 'logfile.log'
every 2.hours do every 2.hours do
command "blahblah" command "blahblah"
@ -129,7 +122,6 @@ class OutputRedirectionTest < Test::Unit::TestCase
setup do setup do
@output = Whenever.cron \ @output = Whenever.cron \
<<-file <<-file
set :job_template, nil
set :output, {:error => 'dev_err', :standard => 'dev_null' } set :output, {:error => 'dev_err', :standard => 'dev_null' }
every 2.hours do every 2.hours do
command "blahblah" command "blahblah"
@ -146,7 +138,6 @@ class OutputRedirectionTest < Test::Unit::TestCase
setup do setup do
@output = Whenever.cron \ @output = Whenever.cron \
<<-file <<-file
set :job_template, nil
set :output, {:error => 'dev_null'} set :output, {:error => 'dev_null'}
every 2.hours do every 2.hours do
command "blahblah" command "blahblah"
@ -163,7 +154,6 @@ class OutputRedirectionTest < Test::Unit::TestCase
setup do setup do
@output = Whenever.cron \ @output = Whenever.cron \
<<-file <<-file
set :job_template, nil
set :output, {:standard => 'dev_out'} set :output, {:standard => 'dev_out'}
every 2.hours do every 2.hours do
command "blahblah" command "blahblah"
@ -180,7 +170,6 @@ class OutputRedirectionTest < Test::Unit::TestCase
setup do setup do
@output = Whenever.cron \ @output = Whenever.cron \
<<-file <<-file
set :job_template, nil
every 2.hours do every 2.hours do
command "blahblah", :output => {:error => 'dev_err'} command "blahblah", :output => {:error => 'dev_err'}
end end
@ -196,7 +185,6 @@ class OutputRedirectionTest < Test::Unit::TestCase
setup do setup do
@output = Whenever.cron \ @output = Whenever.cron \
<<-file <<-file
set :job_template, nil
every 2.hours do every 2.hours do
command "blahblah", :output => {:standard => 'dev_out'} command "blahblah", :output => {:standard => 'dev_out'}
end end
@ -212,7 +200,6 @@ class OutputRedirectionTest < Test::Unit::TestCase
setup do setup do
@output = Whenever.cron \ @output = Whenever.cron \
<<-file <<-file
set :job_template, nil
every 2.hours do every 2.hours do
command "blahblah", :output => {:standard => nil} command "blahblah", :output => {:standard => nil}
end end
@ -228,7 +215,6 @@ class OutputRedirectionTest < Test::Unit::TestCase
setup do setup do
@output = Whenever.cron \ @output = Whenever.cron \
<<-file <<-file
set :job_template, nil
every 2.hours do every 2.hours do
command "blahblah", :output => {:error => nil} command "blahblah", :output => {:error => nil}
end end
@ -244,7 +230,6 @@ class OutputRedirectionTest < Test::Unit::TestCase
setup do setup do
@output = Whenever.cron \ @output = Whenever.cron \
<<-file <<-file
set :job_template, nil
every 2.hours do every 2.hours do
command "blahblah", :output => {:error => nil, :standard => nil} command "blahblah", :output => {:error => nil, :standard => nil}
end end
@ -260,7 +245,6 @@ class OutputRedirectionTest < Test::Unit::TestCase
setup do setup do
@output = Whenever.cron \ @output = Whenever.cron \
<<-file <<-file
set :job_template, nil
every 2.hours do every 2.hours do
command "blahblah", :output => {:error => nil, :standard => 'my.log'} command "blahblah", :output => {:error => nil, :standard => 'my.log'}
end end
@ -276,7 +260,6 @@ class OutputRedirectionTest < Test::Unit::TestCase
setup do setup do
@output = Whenever.cron \ @output = Whenever.cron \
<<-file <<-file
set :job_template, nil
every 2.hours do every 2.hours do
command "blahblah", :output => {:error => 'my_error.log', :standard => nil} command "blahblah", :output => {:error => 'my_error.log', :standard => nil}
end end
@ -292,7 +275,6 @@ class OutputRedirectionTest < Test::Unit::TestCase
setup do setup do
@output = Whenever.cron \ @output = Whenever.cron \
<<-file <<-file
set :job_template, nil
set :cron_log, "cron.log" set :cron_log, "cron.log"
every 2.hours do every 2.hours do
command "blahblah" command "blahblah"

View File

@ -174,26 +174,20 @@ class CronTest < Test::Unit::TestCase
context "When parsing time using the cron shortcuts" do context "When parsing time using the cron shortcuts" do
should "parse a :symbol into the correct shortcut" do should "parse a :symbol into the correct shortcut" do
assert_equal '@reboot', parse_time(:reboot) assert_equal '@reboot', parse_time(:reboot)
assert_equal '@annually', parse_time(:annually) assert_equal '@annually', parse_time(:year)
assert_equal '@annually', parse_time(:yearly) assert_equal '@annually', parse_time(:yearly)
assert_equal '@daily', parse_time(:day)
assert_equal '@daily', parse_time(:daily) assert_equal '@daily', parse_time(:daily)
assert_equal '@midnight', parse_time(:midnight) assert_equal '@midnight', parse_time(:midnight)
assert_equal '@monthly', parse_time(:month)
assert_equal '@monthly', parse_time(:monthly) assert_equal '@monthly', parse_time(:monthly)
assert_equal '@weekly', parse_time(:weekly) assert_equal '@hourly', parse_time(:hour)
assert_equal '@hourly', parse_time(:hourly) assert_equal '@hourly', parse_time(:hourly)
end end
should "convert time-based shortcuts to times" do
assert_equal '0 0 1 * *', parse_time(:month)
assert_equal '0 0 * * *', parse_time(:day)
assert_equal '0 * * * *', parse_time(:hour)
assert_equal '0 0 1 12 *', parse_time(:year)
assert_equal '0 0 1,8,15,22 * *', parse_time(:week)
end
should "raise an exception if a valid shortcut is given but also an :at" do should "raise an exception if a valid shortcut is given but also an :at" do
assert_raises ArgumentError do assert_raises ArgumentError do
parse_time(:hourly, nil, "1:00 am") parse_time(:hour, nil, "1:00 am")
end end
assert_raises ArgumentError do assert_raises ArgumentError do
@ -201,16 +195,7 @@ class CronTest < Test::Unit::TestCase
end end
assert_raises ArgumentError do assert_raises ArgumentError do
parse_time(:daily, nil, '4:20pm') parse_time(:day, nil, '4:20pm')
end
end
end
context "When given raw cron sytax" do
should "return the same cron sytax" do
crons = ['0 0 27-31 * *', '* * * * *', '2/3 1,9,22 11-26 1-6 *']
crons.each do |cron|
assert_equal cron, parse_time(cron)
end end
end end
end end

View File

@ -7,6 +7,14 @@ class JobTest < Test::Unit::TestCase
assert_equal 'foo', new_job(:at => 'foo').at assert_equal 'foo', new_job(:at => 'foo').at
end end
should "return :output when #output_redirection is called" do
assert_equal 'foo', new_job(:output => 'foo').output_redirection
end
should "return :not_set when #output_redirection is called and no :output is set" do
assert_equal :not_set, new_job.output_redirection
end
should "substitute the :task when #output is called" do should "substitute the :task when #output is called" do
job = new_job(:template => ":task", :task => 'abc123') job = new_job(:template => ":task", :task => 'abc123')
assert_equal 'abc123', job.output assert_equal 'abc123', job.output
@ -24,6 +32,7 @@ class JobTest < Test::Unit::TestCase
context "A Job with quotes" do context "A Job with quotes" do
should "output the :task if it's in single quotes" do should "output the :task if it's in single quotes" do
job = new_job(:template => "':task'", :task => 'abc123') job = new_job(:template => "':task'", :task => 'abc123')
assert_equal %q('abc123'), job.output assert_equal %q('abc123'), job.output
@ -50,23 +59,6 @@ class JobTest < Test::Unit::TestCase
assert_equal %q(before "quote -> \" <- quote" after), job.output assert_equal %q(before "quote -> \" <- quote" after), job.output
end end
end end
context "A Job with a job_template" do
should "use the job template" do
job = new_job(:template => ':task', :task => 'abc123', :job_template => 'left :job right')
assert_equal 'left abc123 right', job.output
end
should "escape single quotes" do
job = new_job(:template => "before ':task' after", :task => "quote -> ' <- quote", :job_template => "left ':job' right")
assert_equal %q(left 'before '\''quote -> '\\''\\'\\'''\\'' <- quote'\'' after' right), job.output
end
should "escape double quotes" do
job = new_job(:template => 'before ":task" after', :task => 'quote -> " <- quote', :job_template => 'left ":job" right')
assert_equal %q(left "before \"quote -> \\\" <- quote\" after" right), job.output
end
end
private private

View File

@ -1,31 +1,78 @@
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command
# -*- encoding: utf-8 -*- # -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "whenever/version"
Gem::Specification.new do |s| Gem::Specification.new do |s|
s.name = "whenever" s.name = %q{whenever}
s.version = Whenever::VERSION s.version = "0.5.0"
s.platform = Gem::Platform::RUBY
s.authors = ["Javan Makhmali"] s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.email = ["javan@javan.us"] s.authors = ["Javan Makhmali"]
s.homepage = "" s.date = %q{2010-06-28}
s.summary = %q{Cron jobs in ruby.} s.description = %q{Clean ruby syntax for defining and deploying messy cron jobs.}
s.description = %q{Clean ruby syntax for writing and deploying cron jobs.} s.email = %q{javan@javan.us}
s.files = `git ls-files`.split("\n") s.executables = ["whenever", "wheneverize"]
s.test_files = `git ls-files -- test/{functional,unit}/*`.split("\n") s.extra_rdoc_files = [
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } "README.rdoc"
]
s.files = [
".gitignore",
"CHANGELOG.rdoc",
"README.rdoc",
"Rakefile",
"bin/whenever",
"bin/wheneverize",
"lib/whenever.rb",
"lib/whenever/base.rb",
"lib/whenever/command_line.rb",
"lib/whenever/job.rb",
"lib/whenever/job_list.rb",
"lib/whenever/job_types/default.rb",
"lib/whenever/outputs/cron.rb",
"lib/whenever/outputs/cron/output_redirection.rb",
"lib/whenever/version.rb",
"test/command_line_test.rb",
"test/cron_test.rb",
"test/output_at_test.rb",
"test/output_command_test.rb",
"test/output_defined_job_test.rb",
"test/output_env_test.rb",
"test/output_rake_test.rb",
"test/output_redirection_test.rb",
"test/output_runner_test.rb",
"test/test_helper.rb",
"whenever.gemspec"
]
s.homepage = %q{http://github.com/javan/whenever}
s.rdoc_options = ["--charset=UTF-8"]
s.require_paths = ["lib"] s.require_paths = ["lib"]
s.rubygems_version = %q{1.3.6}
s.add_dependency "chronic", ">= 0.4.3" s.summary = %q{Clean ruby syntax for defining and deploying messy cron jobs.}
s.add_dependency "activesupport", ">= 2.3.4" s.test_files = [
"test/command_line_test.rb",
s.add_development_dependency "shoulda", ">= 2.1.1" "test/cron_test.rb",
s.add_development_dependency "mocha", ">= 0.9.5" "test/output_at_test.rb",
s.add_development_dependency "rake" "test/output_command_test.rb",
"test/output_defined_job_test.rb",
# I'm not sure why this isn't installed along with activesupport, "test/output_env_test.rb",
# but for whatever reason running `bundle install` doesn't install "test/output_rake_test.rb",
# i18n so I'm adding it here for now. "test/output_redirection_test.rb",
# https://github.com/rails/rails/blob/master/activesupport/activesupport.gemspec#L19 ? "test/output_runner_test.rb",
s.add_development_dependency "i18n" "test/test_helper.rb"
]
if s.respond_to? :specification_version then
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
s.specification_version = 3
if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<chronic>, [">= 0.2.3"])
else
s.add_dependency(%q<chronic>, [">= 0.2.3"])
end
else
s.add_dependency(%q<chronic>, [">= 0.2.3"])
end
end end