whenever - initial gem2deb package.
authorFrantišek Dvořák <valtri@civ.zcu.cz>
Tue, 11 Mar 2014 22:22:21 +0000 (23:22 +0100)
committerFrantišek Dvořák <valtri@civ.zcu.cz>
Tue, 11 Mar 2014 22:22:21 +0000 (23:22 +0100)
46 files changed:
ruby-whenever/.gitignore [new file with mode: 0644]
ruby-whenever/.travis.yml [new file with mode: 0644]
ruby-whenever/CHANGELOG.md [new file with mode: 0644]
ruby-whenever/Gemfile [new file with mode: 0644]
ruby-whenever/LICENSE [new file with mode: 0644]
ruby-whenever/README.md [new file with mode: 0644]
ruby-whenever/Rakefile [new file with mode: 0644]
ruby-whenever/bin/whenever [new file with mode: 0755]
ruby-whenever/bin/wheneverize [new file with mode: 0755]
ruby-whenever/checksums.yaml.gz [new file with mode: 0644]
ruby-whenever/debian/changelog [new file with mode: 0644]
ruby-whenever/debian/compat [new file with mode: 0644]
ruby-whenever/debian/control [new file with mode: 0644]
ruby-whenever/debian/copyright [new file with mode: 0644]
ruby-whenever/debian/ruby-test-files.yaml [new file with mode: 0644]
ruby-whenever/debian/ruby-whenever.docs [new file with mode: 0644]
ruby-whenever/debian/rules [new file with mode: 0755]
ruby-whenever/debian/source/format [new file with mode: 0644]
ruby-whenever/debian/watch [new file with mode: 0644]
ruby-whenever/lib/whenever.rb [new file with mode: 0644]
ruby-whenever/lib/whenever/capistrano.rb [new file with mode: 0644]
ruby-whenever/lib/whenever/capistrano/v2/hooks.rb [new file with mode: 0644]
ruby-whenever/lib/whenever/capistrano/v2/recipes.rb [new file with mode: 0644]
ruby-whenever/lib/whenever/capistrano/v2/support.rb [new file with mode: 0644]
ruby-whenever/lib/whenever/capistrano/v3/tasks/whenever.rake [new file with mode: 0644]
ruby-whenever/lib/whenever/command_line.rb [new file with mode: 0644]
ruby-whenever/lib/whenever/cron.rb [new file with mode: 0644]
ruby-whenever/lib/whenever/job.rb [new file with mode: 0644]
ruby-whenever/lib/whenever/job_list.rb [new file with mode: 0644]
ruby-whenever/lib/whenever/output_redirection.rb [new file with mode: 0644]
ruby-whenever/lib/whenever/setup.rb [new file with mode: 0644]
ruby-whenever/lib/whenever/tasks/whenever.rake [new file with mode: 0644]
ruby-whenever/lib/whenever/version.rb [new file with mode: 0644]
ruby-whenever/metadata.yml [new file with mode: 0644]
ruby-whenever/test/functional/command_line_test.rb [new file with mode: 0644]
ruby-whenever/test/functional/output_at_test.rb [new file with mode: 0644]
ruby-whenever/test/functional/output_default_defined_jobs_test.rb [new file with mode: 0644]
ruby-whenever/test/functional/output_defined_job_test.rb [new file with mode: 0644]
ruby-whenever/test/functional/output_env_test.rb [new file with mode: 0644]
ruby-whenever/test/functional/output_jobs_for_roles_test.rb [new file with mode: 0644]
ruby-whenever/test/functional/output_redirection_test.rb [new file with mode: 0644]
ruby-whenever/test/test_helper.rb [new file with mode: 0644]
ruby-whenever/test/unit/capistrano_support_test.rb [new file with mode: 0644]
ruby-whenever/test/unit/cron_test.rb [new file with mode: 0644]
ruby-whenever/test/unit/job_test.rb [new file with mode: 0644]
ruby-whenever/whenever.gemspec [new file with mode: 0644]

diff --git a/ruby-whenever/.gitignore b/ruby-whenever/.gitignore
new file mode 100644 (file)
index 0000000..a894873
--- /dev/null
@@ -0,0 +1,5 @@
+.DS_Store
+pkg
+doc
+.*.sw[a-z]
+Gemfile.lock
diff --git a/ruby-whenever/.travis.yml b/ruby-whenever/.travis.yml
new file mode 100644 (file)
index 0000000..b9ca1cc
--- /dev/null
@@ -0,0 +1,11 @@
+language: ruby
+rvm:
+  - 1.8.7
+  - 1.9.2
+  - 1.9.3
+  - 2.0.0
+  - 2.1.0
+  - ree
+  - jruby
+  - jruby-18mode
+  - jruby-19mode
diff --git a/ruby-whenever/CHANGELOG.md b/ruby-whenever/CHANGELOG.md
new file mode 100644 (file)
index 0000000..3044492
--- /dev/null
@@ -0,0 +1,292 @@
+### 0.9.2 / March 4, 2014
+
+* Fix issues generating arguments for `execute` in Capistrano 3 tasks. [Javan Makhmali]
+
+
+### 0.9.1 / March 2, 2014
+
+* Pass `--roles` option to `whenever` in Capistrano 3 tasks. [betesh, Javan Makhmali]
+
+* Allow setting `:whenever_command` for Capistrano 3. [Javan Makhmali]
+
+* Allow `:whenever` command to be mapped in SSHKit. [Javan Makhmali]
+
+
+### 0.9.0 / December 17, 2013
+
+* Capistrano V3 support. [Philip Hallstrom]
+
+* Process params in job templates. [Austin Ziegler]
+
+
+### 0.8.4 / July 22, 2012
+
+* Don't require schedule file when clearing. [Javan Makhmali]
+
+* Use bin/rails when available. [Javan Makhmali]
+
+
+### 0.8.3 / July 11, 2013
+
+* Improve Cap rollback logic. [Jeroen Jacobs]
+
+* Allow configuration of the environment variable. [andfx]
+
+* Output option can be a callable Proc. [Li Xiao]
+
+
+### 0.8.2 / January 10, 2013
+
+* Fix Capistrano host options. [Igor Yamolov, Wes Morgan]
+
+* Improve JRuby test support. [Igor Yamolov]
+
+* Use correct release path in Cap task. [Wes Morgan]
+
+
+### 0.8.1 / December 22nd, 2012
+
+* Fix multiserver roles bug. [Wes Morgan]
+
+* Refactor Cap recipes and add tests for them. [Wes Morgan]
+
+* Fix file not found error when running under JRuby. [Wes Morgan]
+
+* Stop interpolating template attributes with no corresponding value. [Vincent Boisard]
+
+* Support for raw cron separated by tabs. [Étienne Barrié]
+
+
+### 0.8.0 / November 8th, 2012
+
+* Separate Capistrano recipes to allow custom execution. [Bogdan Gusiev]
+
+* Execute `whenever:update_crontab` before `deploy:finalize_update`, not `deploy:restart`. [Michal Wrobel]
+
+* Added a new `script` job type. [Ján Suchal]
+
+* Use correct path in Cap task. [Alex Dean]
+
+* Fix that setup.rb and schedule.rb were eval'd together. [Niklas H]
+
+* New Capistrano roles feature. [Wes Morgan]
+
+* Stop clearing the crontab during a deploy. [Javan Makhmali]
+
+* Bump Chronic gem dependency. [rainchen]
+
+
+### 0.7.3 / February 23rd, 2012
+
+* Make included Capistrano task compatible with both new and old versions of Cap. [Giacomo Macrì]
+
+
+### 0.7.2 / December 23rd, 2011
+
+* Accept @reboot and friends as raw cron syntax. [Felix Buenemann]
+
+* Fix clear_crontab task so it will work both standalone and during deploy. [Justin Giancola]
+
+
+### 0.7.1 / December 19th, 2011
+
+* Require thread before active_support for compatibility with Rails < 2.3.11 and RubyGems >= 1.6.0. [Micah Geisel]
+
+* More advanced role filtering in Cap task. [Brad Gessler]
+
+* Added whenever_variables as a configuration variable in Cap task. [Steve Agalloco]
+
+* Escape percent signs and reject newlines in jobs. [Amir Yalon]
+
+* Escape paths so spaces don't trip up cron. [Javan Makhmali]
+
+* Fix ambiguous handling of 1.month with :at. #99 [Javan Makhmali]
+
+
+### 0.7.0 / September 2nd, 2011
+
+* Use mojombo's chronic, it's active again. [Javan Makhmali]
+
+* Capistrano task enhancements. [Chris Griego]
+
+* wheneverize command defaults to '.' directory. [Andrew Nesbitt]
+
+* rake job_type uses bundler if detected. [Michał Szajbe]
+
+* Indicate filename in exceptions stemming from schedule file. [Javan Makhmali]
+
+* Don't require rubygems, bundler where possible. [Oleg Pudeyev]
+
+* Documentation and code cleanup. [many nice people]
+
+
+### 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)]
+
+* Jobs < 1.hour can specify an :at. [gorenje]
+
+* --clear option to remove crontab entries for a specific [identifier]. [mraidel (Michael Raidel)]
+
+
+### 0.4.2 / April 26th, 2010
+
+* runners now cd into the app's directory and then execute. [Michael Guterl]
+
+* Fix STDERR output redirection to file to append instead of overwrite. [weplay]
+
+* Move require of tempfile lib to file that actually uses it. [Finn Smith]
+
+* bugfix: comparison Time with 0 failed. #32 [Dan Hixon]
+
+
+### 0.4.1 / November 30th, 2009
+
+* exit(0) instead of just exit to make JRuby happy. [Elan Meng]
+
+* Fixed activesupport deprecation warning by requiring active_support. #37 [Andrew Nesbitt]
+
+
+### 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]
+
+* 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
+
+* No longer tries (and fails) to combine @shortcut jobs. #20 [Javan Makhmali]
+
+
+### 0.3.6 / June 15th, 2009
+
+* Setting a PATH in the crontab automatically based on the user's PATH. [Javan Makhmali]
+
+
+### 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]
+
+* Fixed issue with new lines. #18 [Javan Makhmali]
+
+### 0.3.1 / June 25th, 2009
+
+* Removed activesupport gem dependency. #1 [Javan Makhmali]
+
+* Switched to numeric days of the week for Solaris support (and probably others). #8 [Roger Ertesvåg]
+
+
+### 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]
+
+
+### 0.2.2 / April 30th, 2009
+
+* Days of week jobs can now accept an :at directive (ex: every :monday, :at => '5pm'). [David Eisinger]
+
+* Fixed command line test so it runs without a config/schedule.rb present. [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
+
+* 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
+
+* 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
+
+* Added --load-file and --user opts to whenever binary. [Javan Makhmali]
+
+
+### 0.1.3 / February 16th, 2009
+
+* Added 'rake' helper for defining scheduled rake tasks. [Javan Makhmali]
+
+* Renamed :cron_environment and :cron_path to :enviroment and :path for better (word) compatibility with rake tasks. [Javan Makhmali]
+
+* Improved test load paths so tests can be run individually. [Javan Makhmali]
+
+* Got rid of already initialized constant warning. [Javan Makhmali]
+
+* Requiring specific gem versions: Chronic >=0.2.3 and activesupport >= 1.3.0 [Javan Makhmali]
+
+
+### 0.1.0 / February 15th, 2009
+
+* Initial release [Javan Makhmali]
diff --git a/ruby-whenever/Gemfile b/ruby-whenever/Gemfile
new file mode 100644 (file)
index 0000000..cf4e178
--- /dev/null
@@ -0,0 +1,9 @@
+source "http://rubygems.org"
+
+# Specify your gem's dependencies in whenever.gemspec
+gemspec
+
+if RUBY_VERSION < "1.9.3"
+  gem "activesupport", "< 4.0.0"
+  gem "shoulda-matchers", "<= 2.0.0"
+end
diff --git a/ruby-whenever/LICENSE b/ruby-whenever/LICENSE
new file mode 100644 (file)
index 0000000..cf55cec
--- /dev/null
@@ -0,0 +1,22 @@
+Copyright (c) 2014 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.
diff --git a/ruby-whenever/README.md b/ruby-whenever/README.md
new file mode 100644 (file)
index 0000000..10336ea
--- /dev/null
@@ -0,0 +1,242 @@
+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 for 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
+
+# run this task only on servers with the :app role in Capistrano
+# see Capistrano roles section below
+every :day, :at => '12:20am', :roles => [:app] do
+  rake "app_server:task"
+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 && :environment_variable=:environment bundle exec rake :task --silent :output"
+job_type :runner,  "cd :path && script/rails runner -e :environment ':task' :output"
+job_type :script,  "cd :path && :environment_variable=:environment bundle exec script/:task :output"
+```
+
+Pre-Rails 3 apps and apps that don't use Bundler will redefine the `rake` and `runner` jobs respectively to function correctly.
+
+If a `:path` is not set it will default to the directory in which `whenever` was executed. `:environment_variable` will default to 'RAILS_ENV'. `: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. For Capistrano V3, see the next section.
+
+In your "config/deploy.rb" file:
+
+```ruby
+require "whenever/capistrano"
+```
+
+Take a look at the recipe for options you can set. <https://github.com/javan/whenever/blob/master/lib/whenever/capistrano/v2/recipes.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`.
+
+If both your environments are on the same server you'll want to namespace them or they'll overwrite each other when you deploy:
+
+```ruby
+set :whenever_environment, defer { stage }
+set :whenever_identifier, defer { "#{application}_#{stage}" }
+require "whenever/capistrano"
+```
+
+### Capistrano V3 Integration
+
+In your "Capfile" file:
+
+```ruby
+require "whenever/capistrano"
+```
+
+Take a look at the load:defaults (bottom of file) task for options you can set. <http://github.com/javan/whenever/blob/master/lib/whenever/tasks/whenever.rake>. For example, to namespace the crontab entries by application and stage do this.
+
+```ruby
+set :whenever_identifier, ->{ "#{fetch(:application)}_#{fetch(:stage)}" }
+```
+
+### Capistrano roles
+
+The first thing to know about the new roles support is that it is entirely
+optional and backwards-compatible. If you don't need different jobs running on
+different servers in your capistrano deployment, then you can safely stop reading
+now and everything should just work the same way it always has.
+
+When you define a job in your schedule.rb file, by default it will be deployed to
+all servers in the whenever_roles list (which defaults to [:db]).
+
+However, if you want to restrict certain jobs to only run on subset of servers,
+you can add a :roles => [...] argument to their definitions. **Make sure to add
+that role to the whenever_roles list in your deploy.rb.**
+
+When you run `cap deploy`, jobs with a :roles list specified will only be added to
+the crontabs on servers with one or more of the roles in that list.
+
+Jobs with no :roles argument will be deployed to all servers in the whenever_roles
+list. This is to maintain backward compatibility with previous releases of whenever.
+
+So, for example, with the default whenever_roles of [:db], a job like this would be
+deployed to all servers with the :db role:
+
+```ruby
+every :day, :at => '12:20am' do
+  rake 'foo:bar'
+end
+```
+
+If we set whenever_roles to [:db, :app] in deploy.rb, and have the following
+jobs in schedule.rb:
+
+```ruby
+every :day, :at => '1:37pm', :roles => [:app] do
+  rake 'app:task' # will only be added to crontabs of :app servers
+end
+
+every :hour, :roles => [:db] do
+  rake 'db:task' # will only be added to crontabs of :db servers
+end
+
+every :day, :at => '12:02am' do
+  command "run_this_everywhere" # will be deployed to :db and :app servers
+end
+```
+
+Here are the basic rules:
+
+  1. If a server's role isn't listed in whenever_roles, it will *never* have jobs
+     added to its crontab.
+  1. If a server's role is listed in the whenever_roles, then it will have all
+     jobs added to its crontab that either list that role in their :roles arg or
+     that don't have a :roles arg.
+  1. If a job has a :roles arg but that role isn't in the whenever_roles list,
+     that job *will not* be deployed to any server.
+
+### 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.
+
+### 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-2.1.0, JRuby, and Rubinius. [![Build Status](https://secure.travis-ci.org/javan/whenever.png)](http://travis-ci.org/javan/whenever)
+
+----
+
+Copyright &copy; 2014 Javan Makhmali
diff --git a/ruby-whenever/Rakefile b/ruby-whenever/Rakefile
new file mode 100644 (file)
index 0000000..16dc1b4
--- /dev/null
@@ -0,0 +1,17 @@
+begin
+  require 'bundler'
+rescue LoadError => e
+  warn("warning: Could not load bundler: #{e}")
+  warn("         Some rake tasks will not be defined")
+else
+  Bundler::GemHelper.install_tasks
+end
+
+require 'rake/testtask'
+Rake::TestTask.new(:test) do |test|
+  test.libs      << 'lib' << 'test'
+  test.pattern   = 'test/{functional,unit}/**/*_test.rb'
+  test.verbose   = true
+end
+
+task :default => :test
\ No newline at end of file
diff --git a/ruby-whenever/bin/whenever b/ruby-whenever/bin/whenever
new file mode 100755 (executable)
index 0000000..70a5bff
--- /dev/null
@@ -0,0 +1,41 @@
+#!/usr/bin/env ruby
+
+require 'optparse'
+require 'whenever'
+require 'whenever/version'
+
+options = {}
+
+OptionParser.new do |opts|
+  opts.banner = "Usage: whenever [options]"
+  opts.on('-i', '--update-crontab [identifier]', 'Default: full path to schedule.rb file') do |identifier|
+    options[:update] = true
+    options[:identifier] = identifier if identifier
+  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|
+    options[:clear] = true
+    options[:identifier] = identifier if identifier
+  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|
+    options[:file] = file if file
+  end
+  opts.on('-u', '--user [user]', 'Default: current user') do |user|
+    options[:user] = user if user
+  end
+  opts.on('-k', '--cut [lines]', 'Cut lines from the top of the cronfile') do |lines|
+    options[:cut] = lines.to_i if lines
+  end
+  opts.on('-r', '--roles [role1,role2]', 'Comma-separated list of server roles to generate cron jobs for') do |roles|
+    options[:roles] = roles.split(',').map(&:to_sym) if roles
+  end
+  opts.on('-v', '--version') { puts "Whenever v#{Whenever::VERSION}"; exit(0) }
+end.parse!
+
+Whenever::CommandLine.execute(options)
diff --git a/ruby-whenever/bin/wheneverize b/ruby-whenever/bin/wheneverize
new file mode 100755 (executable)
index 0000000..b208594
--- /dev/null
@@ -0,0 +1,68 @@
+#!/usr/bin/env ruby
+
+# This file is based heavily on Capistrano's `capify` command
+
+require 'optparse'
+require 'fileutils'
+
+OptionParser.new do |opts|
+  opts.banner = "Usage: #{File.basename($0)} [path]"
+
+  begin
+    opts.parse!(ARGV)
+  rescue OptionParser::ParseError => e
+    warn e.message
+    puts opts
+    exit 1
+  end
+end
+
+unless ARGV.empty?
+  if !File.exists?(ARGV.first)
+    abort "`#{ARGV.first}' does not exist."
+  elsif !File.directory?(ARGV.first)
+    abort "`#{ARGV.first}' is not a directory."
+  elsif ARGV.length > 1
+    abort "Too many arguments; please specify only the directory to wheneverize."
+  end
+end
+
+content = <<-FILE
+# Use this file to easily define all of your cron jobs.
+#
+# It's helpful, but not entirely necessary to understand cron before proceeding.
+# http://en.wikipedia.org/wiki/Cron
+
+# Example:
+#
+# set :output, "/path/to/my/cron_log.log"
+#
+# every 2.hours do
+#   command "/usr/bin/some_great_command"
+#   runner "MyModel.some_method"
+#   rake "some:great:rake:task"
+# end
+#
+# every 4.days do
+#   runner "AnotherModel.prune_old_records"
+# end
+
+# Learn more: http://github.com/javan/whenever
+FILE
+
+file = 'config/schedule.rb'
+base = ARGV.empty? ? '.' : ARGV.shift
+
+file = File.join(base, file)
+if File.exists?(file)
+  warn "[skip] `#{file}' already exists"
+elsif File.exists?(file.downcase)
+  warn "[skip] `#{file.downcase}' exists, which could conflict with `#{file}'"
+elsif !File.exists?(File.dirname(file))
+  warn "[skip] directory `#{File.dirname(file)}' does not exist"
+else
+  puts "[add] writing `#{file}'"
+  File.open(file, "w") { |f| f.write(content) }
+end
+
+puts "[done] wheneverized!"
diff --git a/ruby-whenever/checksums.yaml.gz b/ruby-whenever/checksums.yaml.gz
new file mode 100644 (file)
index 0000000..69c314e
Binary files /dev/null and b/ruby-whenever/checksums.yaml.gz differ
diff --git a/ruby-whenever/debian/changelog b/ruby-whenever/debian/changelog
new file mode 100644 (file)
index 0000000..394768f
--- /dev/null
@@ -0,0 +1,5 @@
+ruby-whenever (0.9.2-1) UNRELEASED; urgency=medium
+
+  * Initial release (Closes: #nnnn)
+
+ -- MAINTAINER <valtri@myriad14.zcu.cz>  Tue, 11 Mar 2014 23:18:38 +0100
diff --git a/ruby-whenever/debian/compat b/ruby-whenever/debian/compat
new file mode 100644 (file)
index 0000000..7f8f011
--- /dev/null
@@ -0,0 +1 @@
+7
diff --git a/ruby-whenever/debian/control b/ruby-whenever/debian/control
new file mode 100644 (file)
index 0000000..c8efae6
--- /dev/null
@@ -0,0 +1,19 @@
+Source: ruby-whenever
+Section: ruby
+Priority: optional
+Maintainer: Debian Ruby Extras Maintainers <pkg-ruby-extras-maintainers@lists.alioth.debian.org>
+Uploaders:  <>
+Build-Depends: debhelper (>= 7.0.50~), gem2deb (>= 0.6.1~)
+Standards-Version: 3.9.4
+#Vcs-Git: git://anonscm.debian.org/pkg-ruby-extras/ruby-whenever.git
+#Vcs-Browser: http://anonscm.debian.org/gitweb/?p=pkg-ruby-extras/ruby-whenever.git;a=summary
+Homepage: 
+XS-Ruby-Versions: all
+
+Package: ruby-whenever
+Architecture: all
+XB-Ruby-Versions: ${ruby:Versions}
+Depends: ${shlibs:Depends}, ${misc:Depends}, ruby | ruby-interpreter
+# chronic (>= 0.6.3), activesupport (>= 2.3.4), shoulda (>= 2.1.1, development), mocha (>= 0.9.5, development), rake (>= 0, development)
+Description: Cron jobs in ruby.
+ Clean ruby syntax for writing and deploying cron jobs.
diff --git a/ruby-whenever/debian/copyright b/ruby-whenever/debian/copyright
new file mode 100644 (file)
index 0000000..73c614d
--- /dev/null
@@ -0,0 +1,35 @@
+Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
+Upstream-Name: whenever
+Source: FIXME <http://example.com/>
+
+Files: *
+Copyright: <years> <put author's name and email here>
+           <years> <likewise for another author>
+License: GPL-2+ (FIXME)
+
+Files: debian/*
+Copyright: 2014  <>
+License: GPL-2+ (FIXME)
+Comment: the Debian packaging is licensed under the same terms as the original package.
+
+License: GPL-2+ (FIXME)
+ This program is free software; you can redistribute it
+ and/or modify it under the terms of the GNU General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later
+ version.
+ .
+ This program is distributed in the hope that it will be
+ useful, but WITHOUT ANY WARRANTY; without even the implied
+ warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ PURPOSE.  See the GNU General Public License for more
+ details.
+ .
+ You should have received a copy of the GNU General Public
+ License along with this package; if not, write to the Free
+ Software Foundation, Inc., 51 Franklin St, Fifth Floor,
+ Boston, MA  02110-1301 USA
+ .
+ On Debian systems, the full text of the GNU General Public
+ License version 2 can be found in the file
+ `/usr/share/common-licenses/GPL-2'.
diff --git a/ruby-whenever/debian/ruby-test-files.yaml b/ruby-whenever/debian/ruby-test-files.yaml
new file mode 100644 (file)
index 0000000..0090af6
--- /dev/null
@@ -0,0 +1,11 @@
+---
+- test/functional/command_line_test.rb
+- test/functional/output_at_test.rb
+- test/functional/output_default_defined_jobs_test.rb
+- test/functional/output_defined_job_test.rb
+- test/functional/output_env_test.rb
+- test/functional/output_jobs_for_roles_test.rb
+- test/functional/output_redirection_test.rb
+- test/unit/capistrano_support_test.rb
+- test/unit/cron_test.rb
+- test/unit/job_test.rb
diff --git a/ruby-whenever/debian/ruby-whenever.docs b/ruby-whenever/debian/ruby-whenever.docs
new file mode 100644 (file)
index 0000000..07b3c9e
--- /dev/null
@@ -0,0 +1,2 @@
+# FIXME: READMEs found
+# README.md
diff --git a/ruby-whenever/debian/rules b/ruby-whenever/debian/rules
new file mode 100755 (executable)
index 0000000..82ddc0c
--- /dev/null
@@ -0,0 +1,15 @@
+#!/usr/bin/make -f
+#export DH_VERBOSE=1
+#
+# Uncomment to ignore all test failures (but the tests will run anyway)
+#export DH_RUBY_IGNORE_TESTS=all
+#
+# Uncomment to ignore some test failures (but the tests will run anyway).
+# Valid values:
+#export DH_RUBY_IGNORE_TESTS=ruby1.9.1 ruby2.0 require-rubygems
+#
+# If you need to specify the .gemspec (eg there is more than one)
+#export DH_RUBY_GEMSPEC=gem.gemspec
+
+%:
+       dh $@ --buildsystem=ruby --with ruby
diff --git a/ruby-whenever/debian/source/format b/ruby-whenever/debian/source/format
new file mode 100644 (file)
index 0000000..163aaf8
--- /dev/null
@@ -0,0 +1 @@
+3.0 (quilt)
diff --git a/ruby-whenever/debian/watch b/ruby-whenever/debian/watch
new file mode 100644 (file)
index 0000000..b1bf76d
--- /dev/null
@@ -0,0 +1,2 @@
+version=3
+http://pkg-ruby-extras.alioth.debian.org/cgi-bin/gemwatch/whenever .*/whenever-(.*).tar.gz
diff --git a/ruby-whenever/lib/whenever.rb b/ruby-whenever/lib/whenever.rb
new file mode 100644 (file)
index 0000000..7a2253a
--- /dev/null
@@ -0,0 +1,33 @@
+require 'thread'
+require 'active_support/all'
+
+module Whenever
+  autoload :JobList,           'whenever/job_list'
+  autoload :Job,               'whenever/job'
+  autoload :CommandLine,       'whenever/command_line'
+
+  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.bin_rails?
+    File.exists?(File.join(path, 'bin', 'rails'))
+  end
+
+  def self.script_rails?
+    File.exists?(File.join(path, 'script', 'rails'))
+  end
+
+  def self.bundler?
+    File.exists?(File.join(path, 'Gemfile'))
+  end
+end
diff --git a/ruby-whenever/lib/whenever/capistrano.rb b/ruby-whenever/lib/whenever/capistrano.rb
new file mode 100644 (file)
index 0000000..621da04
--- /dev/null
@@ -0,0 +1,7 @@
+require 'capistrano/version'
+
+if defined?(Capistrano::VERSION) && Gem::Version.new(Capistrano::VERSION).release >= Gem::Version.new('3.0.0')
+  load File.expand_path("../tasks/whenever.rake", __FILE__)
+else
+  require 'whenever/capistrano/v2/hooks'
+end
diff --git a/ruby-whenever/lib/whenever/capistrano/v2/hooks.rb b/ruby-whenever/lib/whenever/capistrano/v2/hooks.rb
new file mode 100644 (file)
index 0000000..750fdc8
--- /dev/null
@@ -0,0 +1,8 @@
+require "whenever/capistrano/v2/recipes"
+
+Capistrano::Configuration.instance(:must_exist).load do
+  # Write the new cron jobs near the end.
+  before "deploy:finalize_update", "whenever:update_crontab"
+  # If anything goes wrong, undo.
+  after "deploy:rollback", "whenever:update_crontab"
+end
diff --git a/ruby-whenever/lib/whenever/capistrano/v2/recipes.rb b/ruby-whenever/lib/whenever/capistrano/v2/recipes.rb
new file mode 100644 (file)
index 0000000..1deb870
--- /dev/null
@@ -0,0 +1,48 @@
+require 'whenever/capistrano/v2/support'
+
+Capistrano::Configuration.instance(:must_exist).load do
+  Whenever::CapistranoSupport.load_into(self)
+
+  _cset(:whenever_roles)        { :db }
+  _cset(:whenever_options)      { {:roles => fetch(:whenever_roles)} }
+  _cset(:whenever_command)      { "whenever" }
+  _cset(:whenever_identifier)   { fetch :application }
+  _cset(:whenever_environment)  { fetch :rails_env, "production" }
+  _cset(:whenever_variables)    { "environment=#{fetch :whenever_environment}" }
+  _cset(:whenever_update_flags) { "--update-crontab #{fetch :whenever_identifier} --set #{fetch :whenever_variables}" }
+  _cset(:whenever_clear_flags)  { "--clear-crontab #{fetch :whenever_identifier}" }
+
+  namespace :whenever do
+    desc "Update application's crontab entries using Whenever"
+    task :update_crontab do
+      args = {
+        :command => fetch(:whenever_command),
+        :flags   => fetch(:whenever_update_flags),
+        :path    => fetch(:latest_release)
+      }
+
+      if whenever_servers.any?
+        args = whenever_prepare_for_rollback(args) if task_call_frames[0].task.fully_qualified_name == 'deploy:rollback'
+        whenever_run_commands(args)
+
+        on_rollback do
+          args = whenever_prepare_for_rollback(args)
+          whenever_run_commands(args)
+        end
+      end
+    end
+
+    desc "Clear application's crontab entries using Whenever"
+    task :clear_crontab do
+      if whenever_servers.any?
+        args = {
+          :command => fetch(:whenever_command),
+          :flags   => fetch(:whenever_clear_flags),
+          :path    => fetch(:latest_release)
+        }
+
+        whenever_run_commands(args)
+      end
+    end
+  end
+end
diff --git a/ruby-whenever/lib/whenever/capistrano/v2/support.rb b/ruby-whenever/lib/whenever/capistrano/v2/support.rb
new file mode 100644 (file)
index 0000000..d6f6058
--- /dev/null
@@ -0,0 +1,53 @@
+module Whenever
+  module CapistranoSupport
+    def self.load_into(capistrano_configuration)
+      capistrano_configuration.load do
+
+        def whenever_options
+          fetch(:whenever_options)
+        end
+
+        def whenever_roles
+          Array(whenever_options[:roles])
+        end
+
+        def whenever_servers
+          find_servers(whenever_options)
+        end
+
+        def whenever_server_roles
+          whenever_servers.inject({}) do |map, server|
+            map[server] = role_names_for_host(server) & whenever_roles
+            map
+          end
+        end
+
+        def whenever_prepare_for_rollback args
+          if fetch(:previous_release)
+            # rollback to the previous release's crontab
+            args[:path] = fetch(:previous_release)
+          else
+            # clear the crontab if no previous release
+            args[:path]  = fetch(:release_path)
+            args[:flags] = fetch(:whenever_clear_flags)
+          end
+          args
+        end
+
+        def whenever_run_commands(args)
+          unless [:command, :path, :flags].all? { |a| args.include?(a) }
+            raise ArgumentError, ":command, :path, & :flags are required"
+          end
+
+          whenever_server_roles.each do |server, roles|
+            roles_arg = roles.empty? ? "" : " --roles #{roles.join(',')}"
+
+            command = "cd #{args[:path]} && #{args[:command]} #{args[:flags]}#{roles_arg}"
+            run command, whenever_options.merge(:hosts => server)
+          end
+        end
+
+      end
+    end
+  end
+end
diff --git a/ruby-whenever/lib/whenever/capistrano/v3/tasks/whenever.rake b/ruby-whenever/lib/whenever/capistrano/v3/tasks/whenever.rake
new file mode 100644 (file)
index 0000000..7fcacb4
--- /dev/null
@@ -0,0 +1,43 @@
+namespace :whenever do
+  def setup_whenever_task(*args, &block)
+    args = Array(fetch(:whenever_command)) + args
+
+    on roles fetch(:whenever_roles) do |host|
+      host_args = Array(yield(host))
+      within release_path do
+        with fetch(:whenever_command_environment_variables) do
+          execute *(args + host_args)
+        end
+      end
+    end
+  end
+
+  desc "Update application's crontab entries using Whenever"
+  task :update_crontab do
+    setup_whenever_task do |host|
+      roles = host.roles_array.join(",")
+      [fetch(:whenever_update_flags),  "--roles=#{roles}"]
+    end
+  end
+
+  desc "Clear application's crontab entries using Whenever"
+  task :clear_crontab do
+    setup_whenever_task(fetch(:whenever_clear_flags))
+  end
+
+  after "deploy:updated",  "whenever:update_crontab"
+  after "deploy:reverted", "whenever:update_crontab"
+end
+
+namespace :load do
+  task :defaults do
+    set :whenever_roles,        ->{ :db }
+    set :whenever_command,      ->{ [:bundle, :exec, :whenever] }
+    set :whenever_command_environment_variables, ->{ {} }
+    set :whenever_identifier,   ->{ fetch :application }
+    set :whenever_environment,  ->{ fetch :rails_env, "production" }
+    set :whenever_variables,    ->{ "environment=#{fetch :whenever_environment}" }
+    set :whenever_update_flags, ->{ "--update-crontab #{fetch :whenever_identifier} --set #{fetch :whenever_variables}" }
+    set :whenever_clear_flags,  ->{ "--clear-crontab #{fetch :whenever_identifier}" }
+  end
+end
diff --git a/ruby-whenever/lib/whenever/command_line.rb b/ruby-whenever/lib/whenever/command_line.rb
new file mode 100644 (file)
index 0000000..08e6c09
--- /dev/null
@@ -0,0 +1,134 @@
+require 'fileutils'
+require 'tempfile'
+
+module Whenever
+  class CommandLine
+    def self.execute(options={})
+      new(options).run
+    end
+
+    def initialize(options={})
+      @options = options
+
+      @options[:file]       ||= 'config/schedule.rb'
+      @options[:cut]        ||= 0
+      @options[:identifier] ||= default_identifier
+
+      if !File.exists?(@options[:file]) && @options[:clear].nil?
+        warn("[fail] Can't find file: #{@options[:file]}")
+        exit(1)
+      end
+
+      if [@options[:update], @options[:write], @options[:clear]].compact.length > 1
+        warn("[fail] Can only update, write or clear. Choose one.")
+        exit(1)
+      end
+
+      unless @options[:cut].to_s =~ /[0-9]*/
+        warn("[fail] Can't cut negative lines from the crontab #{options[:cut]}")
+        exit(1)
+      end
+      @options[:cut] = @options[:cut].to_i
+    end
+
+    def run
+      if @options[:update] || @options[:clear]
+        write_crontab(updated_crontab)
+      elsif @options[:write]
+        write_crontab(whenever_cron)
+      else
+        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)
+      end
+    end
+
+  protected
+
+    def default_identifier
+      File.expand_path(@options[:file])
+    end
+
+    def whenever_cron
+      return '' if @options[:clear]
+      @whenever_cron ||= [comment_open, Whenever.cron(@options), comment_close].compact.join("\n") + "\n"
+    end
+
+    def read_crontab
+      return @current_crontab if @current_crontab
+
+      command = ['crontab -l']
+      command << "-u #{@options[:user]}" if @options[:user]
+
+      command_results  = %x[#{command.join(' ')} 2> /dev/null]
+      @current_crontab = $?.exitstatus.zero? ? prepare(command_results) : ''
+    end
+
+    def write_crontab(contents)
+      tmp_cron_file = Tempfile.open('whenever_tmp_cron')
+      tmp_cron_file << contents
+      tmp_cron_file.fsync
+
+      command = ['crontab']
+      command << "-u #{@options[:user]}" if @options[:user]
+      command << tmp_cron_file.path
+
+      if system(command.join(' '))
+        action = 'written' if @options[:write]
+        action = 'updated' if @options[:update]
+        puts "[write] crontab file #{action}"
+        tmp_cron_file.close!
+        exit(0)
+      else
+        warn "[fail] Couldn't write crontab; try running `whenever' with no options to ensure your schedule file is valid."
+        tmp_cron_file.close!
+        exit(1)
+      end
+    end
+
+    def updated_crontab
+      # Check for unopened or unclosed identifier blocks
+      if read_crontab =~ Regexp.new("^#{comment_open}\s*$") && (read_crontab =~ Regexp.new("^#{comment_close}\s*$")).nil?
+        warn "[fail] Unclosed indentifier; Your crontab file contains '#{comment_open}', but no '#{comment_close}'"
+        exit(1)
+      elsif (read_crontab =~ Regexp.new("^#{comment_open}\s*$")).nil? && read_crontab =~ Regexp.new("^#{comment_close}\s*$")
+        warn "[fail] Unopened indentifier; Your crontab file contains '#{comment_close}', but no '#{comment_open}'"
+        exit(1)
+      end
+
+      # 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 the existing crontab file contains backslashes they get lost going through gsub.
+        # .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
+        [read_crontab, whenever_cron].join("\n\n")
+      end.gsub(/\n{3,}/, "\n\n") # More than two newlines becomes just two.
+    end
+
+    def prepare(contents)
+      # Strip n lines from the top of the file as specified by the :cut option.
+      # 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
+
+    def comment_base
+      "Whenever generated tasks for: #{@options[:identifier]}"
+    end
+
+    def comment_open
+      "# Begin #{comment_base}"
+    end
+
+    def comment_close
+      "# End #{comment_base}"
+    end
+  end
+end
diff --git a/ruby-whenever/lib/whenever/cron.rb b/ruby-whenever/lib/whenever/cron.rb
new file mode 100644 (file)
index 0000000..fe07374
--- /dev/null
@@ -0,0 +1,152 @@
+require 'chronic'
+
+module Whenever
+  module Output
+    class Cron
+      KEYWORDS = [:reboot, :yearly, :annually, :monthly, :weekly, :daily, :midnight, :hourly]
+      REGEX = /^(@(#{KEYWORDS.join '|'})|.+\s+.+\s+.+\s+.+\s+.+.?)$/
+
+      attr_accessor :time, :task
+
+      def initialize(time = nil, task = nil, at = nil)
+        @at_given = at
+        @time = time
+        @task = task
+        @at   = at.is_a?(String) ? (Chronic.parse(at) || 0) : (at || 0)
+      end
+
+      def self.enumerate(item, detect_cron = true)
+        if item and item.is_a?(String)
+          items =
+            if detect_cron && item =~ REGEX
+              [item]
+            else
+              item.split(',')
+            end
+        else
+          items = item
+          items = [items] unless items and items.respond_to?(:each)
+        end
+        items
+      end
+
+      def self.output(times, job)
+        enumerate(times).each do |time|
+          enumerate(job.at, false).each do |at|
+            yield new(time, job.output, at).output
+          end
+        end
+      end
+
+      def output
+        [time_in_cron_syntax, task].compact.join(' ').strip
+      end
+
+      def time_in_cron_syntax
+        case @time
+          when REGEX  then @time # raw cron sytax given
+          when Symbol then parse_symbol
+          when String then parse_as_string
+          else parse_time
+        end
+      end
+
+    protected
+      def day_given?
+        months = %w(jan feb mar apr may jun jul aug sep oct nov dec)
+        @at_given.is_a?(String) && months.any? { |m| @at_given.downcase.index(m) }
+      end
+
+      def parse_symbol
+        shortcut = case @time
+          when *KEYWORDS then "@#{@time}" # :reboot => '@reboot'
+          when :year     then 12.months
+          when :day      then 1.day
+          when :month    then 1.month
+          when :week     then 1.week
+          when :hour     then 1.hour
+        end
+
+        if shortcut.is_a?(Numeric)
+          @time = shortcut
+          parse_time
+        elsif shortcut
+          if @at.is_a?(Time) || (@at.is_a?(Numeric) && @at > 0)
+            raise ArgumentError, "You cannot specify an ':at' when using the shortcuts for times."
+          else
+            return shortcut
+          end
+        else
+          parse_as_string
+        end
+      end
+
+      def parse_time
+        timing = Array.new(5, '*')
+        case @time
+          when 0.seconds...1.minute
+            raise ArgumentError, "Time must be in minutes or higher"
+          when 1.minute...1.hour
+            minute_frequency = @time / 60
+            timing[0] = comma_separated_timing(minute_frequency, 59, @at || 0)
+          when 1.hour...1.day
+            hour_frequency = (@time / 60 / 60).round
+            timing[0] = @at.is_a?(Time) ? @at.min : @at
+            timing[1] = comma_separated_timing(hour_frequency, 23)
+          when 1.day...1.month
+            day_frequency = (@time / 24 / 60 / 60).round
+            timing[0] = @at.is_a?(Time) ? @at.min  : 0
+            timing[1] = @at.is_a?(Time) ? @at.hour : @at
+            timing[2] = comma_separated_timing(day_frequency, 31, 1)
+          when 1.month..12.months
+            month_frequency = (@time / 30  / 24 / 60 / 60).round
+            timing[0] = @at.is_a?(Time) ? @at.min  : 0
+            timing[1] = @at.is_a?(Time) ? @at.hour : 0
+            timing[2] = if @at.is_a?(Time)
+              day_given? ? @at.day : 1
+            else
+              @at.zero? ? 1 : @at
+            end
+            timing[3] = comma_separated_timing(month_frequency, 12, 1)
+          else
+            return parse_as_string
+        end
+        timing.join(' ')
+      end
+
+      def parse_as_string
+        return unless @time
+        string = @time.to_s
+
+        timing = Array.new(4, '*')
+        timing[0] = @at.is_a?(Time) ? @at.min  : 0
+        timing[1] = @at.is_a?(Time) ? @at.hour : 0
+
+        return (timing << '1-5') * " " if string.downcase.index('weekday')
+        return (timing << '6,0') * " " if string.downcase.index('weekend')
+
+        %w(sun mon tue wed thu fri sat).each_with_index do |day, i|
+          return (timing << i) * " " if string.downcase.index(day)
+        end
+
+        raise ArgumentError, "Couldn't parse: #{@time}"
+      end
+
+      def comma_separated_timing(frequency, max, start = 0)
+        return start     if frequency.blank? || frequency.zero?
+        return '*'       if frequency == 1
+        return frequency if frequency > (max * 0.5).ceil
+
+        original_start = start
+
+        start += frequency unless (max + 1).modulo(frequency).zero? || start > 0
+        output = (start..max).step(frequency).to_a
+
+        max_occurances = (max.to_f  / (frequency.to_f)).round
+        max_occurances += 1 if original_start.zero?
+
+        output[0, max_occurances].join(',')
+      end
+    end
+  end
+end
diff --git a/ruby-whenever/lib/whenever/job.rb b/ruby-whenever/lib/whenever/job.rb
new file mode 100644 (file)
index 0000000..05aa6d5
--- /dev/null
@@ -0,0 +1,54 @@
+require 'shellwords'
+
+module Whenever
+  class Job
+    attr_reader :at, :roles
+
+    def initialize(options = {})
+      @options = options
+      @at                               = options.delete(:at)
+      @template                         = options.delete(:template)
+      @job_template                     = options.delete(:job_template) || ":job"
+      @roles                            = Array.wrap(options.delete(:roles))
+      @options[:output]                 = options.has_key?(:output) ? Whenever::Output::Redirection.new(options[:output]).to_s : ''
+      @options[:environment_variable] ||= "RAILS_ENV"
+      @options[:environment]          ||= :production
+      @options[:path]                   = Shellwords.shellescape(@options[:path] || Whenever.path)
+    end
+
+    def output
+      job = process_template(@template, @options)
+      out = process_template(@job_template, @options.merge(:job => job))
+      out.gsub(/%/, '\%')
+    end
+
+    def has_role?(role)
+      roles.empty? || roles.include?(role)
+    end
+
+  protected
+
+    def process_template(template, options)
+      template.gsub(/:\w+/) do |key|
+        before_and_after = [$`[-1..-1], $'[0..0]]
+        option = options[key.sub(':', '').to_sym] || key
+
+        if before_and_after.all? { |c| c == "'" }
+          escape_single_quotes(option)
+        elsif before_and_after.all? { |c| c == '"' }
+          escape_double_quotes(option)
+        else
+          option
+        end
+      end.squish
+    end
+
+    def escape_single_quotes(str)
+      str.gsub(/'/) { "'\\''" }
+    end
+
+    def escape_double_quotes(str)
+      str.gsub(/"/) { '\"' }
+    end
+  end
+end
diff --git a/ruby-whenever/lib/whenever/job_list.rb b/ruby-whenever/lib/whenever/job_list.rb
new file mode 100644 (file)
index 0000000..7740d9a
--- /dev/null
@@ -0,0 +1,155 @@
+module Whenever
+  class JobList
+    attr_reader :roles
+
+    def initialize(options)
+      @jobs, @env, @set_variables, @pre_set_variables = {}, {}, {}, {}
+
+      if options.is_a? String
+        options = { :string => options }
+      end
+
+      pre_set(options[:set])
+
+      @roles = options[:roles] || []
+
+      setup_file = File.expand_path('../setup.rb', __FILE__)
+      setup = File.read(setup_file)
+      schedule = if options[:string]
+        options[:string]
+      elsif options[:file]
+        File.read(options[:file])
+      end
+
+      instance_eval(setup, setup_file)
+      instance_eval(schedule, options[:file] || '<eval>')
+    end
+
+    def set(variable, value)
+      variable = variable.to_sym
+      return if @pre_set_variables[variable]
+
+      instance_variable_set("@#{variable}".to_sym, value)
+      self.class.send(:attr_reader, variable.to_sym)
+      @set_variables[variable] = value
+    end
+
+    def env(variable, value)
+      @env[variable.to_s] = value
+    end
+
+    def every(frequency, options = {})
+      @current_time_scope = frequency
+      @options = options
+      yield
+    end
+
+    def job_type(name, template)
+      class_eval do
+        define_method(name) do |task, *args|
+          options = { :task => task, :template => template }
+          options.merge!(args[0]) if args[0].is_a? Hash
+
+          # :cron_log was an old option for output redirection, it remains for backwards compatibility
+          options[:output] = (options[:cron_log] || @cron_log) if defined?(@cron_log) || options.has_key?(:cron_log)
+          # :output is the newer, more flexible option.
+          options[:output] = @output if defined?(@output) && !options.has_key?(:output)
+
+          @jobs[@current_time_scope] ||= []
+          @jobs[@current_time_scope] << Whenever::Job.new(@options.merge(@set_variables).merge(options))
+        end
+      end
+    end
+
+    def generate_cron_output
+      [environment_variables, cron_jobs].compact.join
+    end
+
+  private
+
+    #
+    # Takes a string like: "variable1=something&variable2=somethingelse"
+    # and breaks it into variable/value pairs. Used for setting variables at runtime from the command line.
+    # Only works for setting values as strings.
+    #
+    def pre_set(variable_string = nil)
+      return if variable_string.blank?
+
+      pairs = variable_string.split('&')
+      pairs.each do |pair|
+        next unless pair.index('=')
+        variable, value = *pair.split('=')
+        unless variable.blank? || value.blank?
+          variable = variable.strip.to_sym
+          set(variable, value.strip)
+          @pre_set_variables[variable] = value
+        end
+      end
+    end
+
+    def environment_variables
+      return if @env.empty?
+
+      output = []
+      @env.each do |key, val|
+        output << "#{key}=#{val.blank? ? '""' : val}\n"
+      end
+      output << "\n"
+
+      output.join
+    end
+
+    #
+    # Takes the standard cron output that Whenever generates and finds
+    # similar entries that can be combined. For example: If a job should run
+    # at 3:02am and 4:02am, instead of creating two jobs this method combines
+    # them into one that runs on the 2nd minute at the 3rd and 4th hour.
+    #
+    def combine(entries)
+      entries.map! { |entry| entry.split(/ +/, 6) }
+      0.upto(4) do |f|
+        (entries.length-1).downto(1) do |i|
+          next if entries[i][f] == '*'
+          comparison = entries[i][0...f] + entries[i][f+1..-1]
+          (i-1).downto(0) do |j|
+            next if entries[j][f] == '*'
+            if comparison == entries[j][0...f] + entries[j][f+1..-1]
+              entries[j][f] += ',' + entries[i][f]
+              entries.delete_at(i)
+              break
+            end
+          end
+        end
+      end
+
+      entries.map { |entry| entry.join(' ') }
+    end
+
+    def cron_jobs
+      return if @jobs.empty?
+
+      shortcut_jobs = []
+      regular_jobs = []
+
+      output_all = roles.empty?
+      @jobs.each do |time, jobs|
+        jobs.each do |job|
+          next unless output_all || roles.any? do |r|
+            job.has_role?(r)
+          end
+          Whenever::Output::Cron.output(time, job) do |cron|
+            cron << "\n\n"
+
+            if cron.starts_with?("@")
+              shortcut_jobs << cron
+            else
+              regular_jobs << cron
+            end
+          end
+        end
+      end
+
+      shortcut_jobs.join + combine(regular_jobs).join
+    end
+  end
+end
diff --git a/ruby-whenever/lib/whenever/output_redirection.rb b/ruby-whenever/lib/whenever/output_redirection.rb
new file mode 100644 (file)
index 0000000..772cc20
--- /dev/null
@@ -0,0 +1,57 @@
+module Whenever
+  module Output
+    class Redirection
+      def initialize(output)
+        @output = output
+      end
+      
+      def to_s
+        return '' unless defined?(@output)
+        case @output
+          when String   then redirect_from_string
+          when Hash     then redirect_from_hash
+          when NilClass then ">> /dev/null 2>&1"
+          when Proc     then @output.call
+          else ''
+        end 
+      end
+      
+    protected
+      
+      def stdout
+        return unless @output.has_key?(:standard)
+        @output[:standard].nil? ? '/dev/null' : @output[:standard]
+      end
+
+      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
+
+      def redirect_from_string
+        ">> #{@output} 2>&1"
+      end
+    end
+  end
+end
diff --git a/ruby-whenever/lib/whenever/setup.rb b/ruby-whenever/lib/whenever/setup.rb
new file mode 100644 (file)
index 0000000..e2a02c4
--- /dev/null
@@ -0,0 +1,26 @@
+# Environment variable defaults to RAILS_ENV
+set :environment_variable, "RAILS_ENV"
+# Environment 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'"
+
+set :runner_command, case
+  when Whenever.bin_rails?
+    "bin/rails runner"
+  when Whenever.script_rails?
+    "script/rails runner"
+  else
+    "script/runner"
+  end
+
+set :bundle_command, Whenever.bundler? ? "bundle exec" : ""
+
+job_type :command, ":task :output"
+job_type :rake,    "cd :path && :environment_variable=:environment :bundle_command rake :task --silent :output"
+job_type :script,  "cd :path && :environment_variable=:environment :bundle_command script/:task :output"
+job_type :runner,  "cd :path && :runner_command -e :environment ':task' :output"
diff --git a/ruby-whenever/lib/whenever/tasks/whenever.rake b/ruby-whenever/lib/whenever/tasks/whenever.rake
new file mode 100644 (file)
index 0000000..7fcacb4
--- /dev/null
@@ -0,0 +1,43 @@
+namespace :whenever do
+  def setup_whenever_task(*args, &block)
+    args = Array(fetch(:whenever_command)) + args
+
+    on roles fetch(:whenever_roles) do |host|
+      host_args = Array(yield(host))
+      within release_path do
+        with fetch(:whenever_command_environment_variables) do
+          execute *(args + host_args)
+        end
+      end
+    end
+  end
+
+  desc "Update application's crontab entries using Whenever"
+  task :update_crontab do
+    setup_whenever_task do |host|
+      roles = host.roles_array.join(",")
+      [fetch(:whenever_update_flags),  "--roles=#{roles}"]
+    end
+  end
+
+  desc "Clear application's crontab entries using Whenever"
+  task :clear_crontab do
+    setup_whenever_task(fetch(:whenever_clear_flags))
+  end
+
+  after "deploy:updated",  "whenever:update_crontab"
+  after "deploy:reverted", "whenever:update_crontab"
+end
+
+namespace :load do
+  task :defaults do
+    set :whenever_roles,        ->{ :db }
+    set :whenever_command,      ->{ [:bundle, :exec, :whenever] }
+    set :whenever_command_environment_variables, ->{ {} }
+    set :whenever_identifier,   ->{ fetch :application }
+    set :whenever_environment,  ->{ fetch :rails_env, "production" }
+    set :whenever_variables,    ->{ "environment=#{fetch :whenever_environment}" }
+    set :whenever_update_flags, ->{ "--update-crontab #{fetch :whenever_identifier} --set #{fetch :whenever_variables}" }
+    set :whenever_clear_flags,  ->{ "--clear-crontab #{fetch :whenever_identifier}" }
+  end
+end
diff --git a/ruby-whenever/lib/whenever/version.rb b/ruby-whenever/lib/whenever/version.rb
new file mode 100644 (file)
index 0000000..a37ca55
--- /dev/null
@@ -0,0 +1,3 @@
+module Whenever
+  VERSION = '0.9.2'
+end
diff --git a/ruby-whenever/metadata.yml b/ruby-whenever/metadata.yml
new file mode 100644 (file)
index 0000000..caa57ed
--- /dev/null
@@ -0,0 +1,161 @@
+--- !ruby/object:Gem::Specification
+name: whenever
+version: !ruby/object:Gem::Version
+  version: 0.9.2
+platform: ruby
+authors:
+- Javan Makhmali
+autorequire: 
+bindir: bin
+cert_chain: []
+date: 2014-03-04 00:00:00.000000000 Z
+dependencies:
+- !ruby/object:Gem::Dependency
+  name: chronic
+  requirement: !ruby/object:Gem::Requirement
+    requirements:
+    - - '>='
+      - !ruby/object:Gem::Version
+        version: 0.6.3
+  type: :runtime
+  prerelease: false
+  version_requirements: !ruby/object:Gem::Requirement
+    requirements:
+    - - '>='
+      - !ruby/object:Gem::Version
+        version: 0.6.3
+- !ruby/object:Gem::Dependency
+  name: activesupport
+  requirement: !ruby/object:Gem::Requirement
+    requirements:
+    - - '>='
+      - !ruby/object:Gem::Version
+        version: 2.3.4
+  type: :runtime
+  prerelease: false
+  version_requirements: !ruby/object:Gem::Requirement
+    requirements:
+    - - '>='
+      - !ruby/object:Gem::Version
+        version: 2.3.4
+- !ruby/object:Gem::Dependency
+  name: shoulda
+  requirement: !ruby/object:Gem::Requirement
+    requirements:
+    - - '>='
+      - !ruby/object:Gem::Version
+        version: 2.1.1
+  type: :development
+  prerelease: false
+  version_requirements: !ruby/object:Gem::Requirement
+    requirements:
+    - - '>='
+      - !ruby/object:Gem::Version
+        version: 2.1.1
+- !ruby/object:Gem::Dependency
+  name: mocha
+  requirement: !ruby/object:Gem::Requirement
+    requirements:
+    - - '>='
+      - !ruby/object:Gem::Version
+        version: 0.9.5
+  type: :development
+  prerelease: false
+  version_requirements: !ruby/object:Gem::Requirement
+    requirements:
+    - - '>='
+      - !ruby/object:Gem::Version
+        version: 0.9.5
+- !ruby/object:Gem::Dependency
+  name: rake
+  requirement: !ruby/object:Gem::Requirement
+    requirements:
+    - - '>='
+      - !ruby/object:Gem::Version
+        version: '0'
+  type: :development
+  prerelease: false
+  version_requirements: !ruby/object:Gem::Requirement
+    requirements:
+    - - '>='
+      - !ruby/object:Gem::Version
+        version: '0'
+description: Clean ruby syntax for writing and deploying cron jobs.
+email:
+- javan@javan.us
+executables:
+- whenever
+- wheneverize
+extensions: []
+extra_rdoc_files: []
+files:
+- .gitignore
+- .travis.yml
+- CHANGELOG.md
+- Gemfile
+- LICENSE
+- README.md
+- Rakefile
+- bin/whenever
+- bin/wheneverize
+- lib/whenever.rb
+- lib/whenever/capistrano.rb
+- lib/whenever/capistrano/v2/hooks.rb
+- lib/whenever/capistrano/v2/recipes.rb
+- lib/whenever/capistrano/v2/support.rb
+- lib/whenever/capistrano/v3/tasks/whenever.rake
+- lib/whenever/command_line.rb
+- lib/whenever/cron.rb
+- lib/whenever/job.rb
+- lib/whenever/job_list.rb
+- lib/whenever/output_redirection.rb
+- lib/whenever/setup.rb
+- lib/whenever/tasks/whenever.rake
+- lib/whenever/version.rb
+- test/functional/command_line_test.rb
+- test/functional/output_at_test.rb
+- test/functional/output_default_defined_jobs_test.rb
+- test/functional/output_defined_job_test.rb
+- test/functional/output_env_test.rb
+- test/functional/output_jobs_for_roles_test.rb
+- test/functional/output_redirection_test.rb
+- test/test_helper.rb
+- test/unit/capistrano_support_test.rb
+- test/unit/cron_test.rb
+- test/unit/job_test.rb
+- whenever.gemspec
+homepage: ''
+licenses:
+- MIT
+metadata: {}
+post_install_message: 
+rdoc_options: []
+require_paths:
+- lib
+required_ruby_version: !ruby/object:Gem::Requirement
+  requirements:
+  - - '>='
+    - !ruby/object:Gem::Version
+      version: '0'
+required_rubygems_version: !ruby/object:Gem::Requirement
+  requirements:
+  - - '>='
+    - !ruby/object:Gem::Version
+      version: '0'
+requirements: []
+rubyforge_project: 
+rubygems_version: 2.0.14
+signing_key: 
+specification_version: 4
+summary: Cron jobs in ruby.
+test_files:
+- test/functional/command_line_test.rb
+- test/functional/output_at_test.rb
+- test/functional/output_default_defined_jobs_test.rb
+- test/functional/output_defined_job_test.rb
+- test/functional/output_env_test.rb
+- test/functional/output_jobs_for_roles_test.rb
+- test/functional/output_redirection_test.rb
+- test/unit/capistrano_support_test.rb
+- test/unit/cron_test.rb
+- test/unit/job_test.rb
diff --git a/ruby-whenever/test/functional/command_line_test.rb b/ruby-whenever/test/functional/command_line_test.rb
new file mode 100644 (file)
index 0000000..d390a4a
--- /dev/null
@@ -0,0 +1,334 @@
+require File.expand_path(File.dirname(__FILE__) + "/../test_helper")
+
+class CommandLineTest < Test::Unit::TestCase
+
+  context "A command line write" do
+    setup do
+      File.expects(:exists?).with('config/schedule.rb').returns(true)
+      @command = Whenever::CommandLine.new(:write => true, :identifier => 'My identifier')
+      @task = "#{two_hours} /my/command"
+      Whenever.expects(:cron).returns(@task)
+    end
+
+    should "output the cron job with identifier blocks" do
+      output = <<-EXPECTED
+# Begin Whenever generated tasks for: My identifier
+#{@task}
+# End Whenever generated tasks for: My identifier
+EXPECTED
+
+      assert_equal output, @command.send(:whenever_cron)
+    end
+
+    should "write the crontab when run" do
+      @command.expects(:write_crontab).returns(true)
+      assert @command.run
+    end
+  end
+
+  context "A command line update" do
+    setup do
+      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)
+    end
+
+    should "add the cron to the end of the file if there is no existing identifier block" do
+      existing = '# Existing crontab'
+      @command.expects(:read_crontab).at_least_once.returns(existing)
+
+      new_cron = <<-EXPECTED
+#{existing}
+
+# Begin Whenever generated tasks for: My identifier
+#{@task}
+# 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 "replace an existing block if the identifier matches" do
+      existing = <<-EXISTING_CRON
+# Something
+
+# Begin Whenever generated tasks for: My identifier
+My whenever job that was already here
+# End Whenever generated tasks for: My identifier
+
+# Begin Whenever generated tasks for: Other identifier
+This shouldn't get replaced
+# End Whenever generated tasks for: Other identifier
+EXISTING_CRON
+
+      new_cron = <<-NEW_CRON
+# Something
+
+# Begin Whenever generated tasks for: My identifier
+#{@task}
+# End Whenever generated tasks for: My identifier
+
+# Begin Whenever generated tasks for: Other identifier
+This shouldn't get replaced
+# End Whenever generated tasks for: Other identifier
+NEW_CRON
+
+      @command.expects(:read_crontab).at_least_once.returns(existing)
+      assert_equal new_cron, @command.send(:updated_crontab)
+
+      @command.expects(:write_crontab).with(new_cron).returns(true)
+      assert @command.run
+    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
+    setup do
+      File.expects(:exists?).with('config/schedule.rb').returns(true)
+      @command = Whenever::CommandLine.new(:clear => true, :identifier => 'My identifier')
+      @task = "#{two_hours} /my/command"
+    end
+
+    should "clear an existing block if the identifier matches" do
+      existing = <<-EXISTING_CRON
+# Something
+
+# Begin Whenever generated tasks for: My identifier
+My whenever job that was already here
+# End Whenever generated tasks for: My identifier
+
+# Begin Whenever generated tasks for: Other identifier
+This shouldn't get replaced
+# End Whenever generated tasks for: Other identifier
+EXISTING_CRON
+
+      @command.expects(:read_crontab).at_least_once.returns(existing)
+
+      new_cron = <<-NEW_CRON
+# Something
+
+# Begin Whenever generated tasks for: Other identifier
+This shouldn't get replaced
+# End Whenever generated tasks for: Other identifier
+NEW_CRON
+
+      assert_equal new_cron, @command.send(:updated_crontab)
+
+      @command.expects(:write_crontab).with(new_cron).returns(true)
+      assert @command.run
+    end
+  end
+
+  context "A command line clear with no schedule file" do
+    setup do
+      File.expects(:exists?).with('config/schedule.rb').returns(false)
+      @command = Whenever::CommandLine.new(:clear => true, :identifier => 'My identifier')
+    end
+
+    should "run successfully" do
+      @command.expects(:write_crontab).returns(true)
+      assert @command.run
+    end
+  end
+
+  context "A command line update with no identifier" do
+    setup do
+      File.expects(:exists?).with('config/schedule.rb').returns(true)
+      Whenever::CommandLine.any_instance.expects(:default_identifier).returns('DEFAULT')
+      @command = Whenever::CommandLine.new(:update => true, :file => @file)
+    end
+
+    should "use the default identifier" do
+      assert_equal "Whenever generated tasks for: DEFAULT", @command.send(:comment_base)
+    end
+  end
+
+  context "combined params" do
+    setup do
+      Whenever::CommandLine.any_instance.expects(:exit)
+      Whenever::CommandLine.any_instance.expects(:warn)
+      File.expects(:exists?).with('config/schedule.rb').returns(true)
+    end
+
+    should "exit with write and clear" do
+      @command = Whenever::CommandLine.new(:write => true, :clear => true)
+    end
+
+    should "exit with write and update" do
+      @command = Whenever::CommandLine.new(:write => true, :update => true)
+    end
+
+    should "exit with update and clear" do
+      @command = Whenever::CommandLine.new(:update => true, :clear => true)
+    end
+  end
+
+  context "A runner where the environment is overridden using the :set option" do
+    setup do
+      @output = Whenever.cron :set => 'environment=serious', :string => \
+      <<-file
+        set :job_template, nil
+        set :environment, :silly
+        set :path, '/my/path'
+        every 2.hours do
+          runner "blahblah"
+        end
+      file
+    end
+
+    should "output the runner using the override environment" do
+      assert_match two_hours + %( cd /my/path && script/runner -e serious 'blahblah'), @output
+    end
+  end
+
+  context "A runner where the environment and path are overridden using the :set option" do
+    setup do
+      @output = Whenever.cron :set => 'environment=serious&path=/serious/path', :string => \
+      <<-file
+        set :job_template, nil
+        set :environment, :silly
+        set :path, '/silly/path'
+        every 2.hours do
+          runner "blahblah"
+        end
+      file
+    end
+
+    should "output the runner using the overridden path and environment" do
+      assert_match two_hours + %( cd /serious/path && script/runner -e serious 'blahblah'), @output
+    end
+  end
+
+  context "A runner where the environment and path are overridden using the :set option with spaces in the string" do
+    setup do
+      @output = Whenever.cron :set => ' environment = serious&  path =/serious/path', :string => \
+      <<-file
+        set :job_template, nil
+        set :environment, :silly
+        set :path, '/silly/path'
+        every 2.hours do
+          runner "blahblah"
+        end
+      file
+    end
+
+    should "output the runner using the overridden path and environment" do
+      assert_match two_hours + %( cd /serious/path && script/runner -e serious 'blahblah'), @output
+    end
+  end
+
+  context "A runner where the environment is overridden using the :set option but no value is given" do
+    setup do
+      @output = Whenever.cron :set => ' environment=', :string => \
+      <<-file
+        set :job_template, nil
+        set :environment, :silly
+        set :path, '/silly/path'
+        every 2.hours do
+          runner "blahblah"
+        end
+      file
+    end
+
+    should "output the runner using the original environmnet" do
+      assert_match two_hours + %( cd /silly/path && script/runner -e silly 'blahblah'), @output
+    end
+  end
+
+  context "prepare-ing the output" do
+    setup do
+      File.expects(:exists?).with('config/schedule.rb').returns(true)
+    end
+
+    should "not trim off the top lines of the file" do
+      @command = Whenever::CommandLine.new(:update => true, :identifier => 'My identifier', :cut => 0)
+      existing = <<-EXISTING_CRON
+# Useless Comments
+# at the top of the file
+
+# Begin Whenever generated tasks for: My identifier
+My whenever job that was already here
+# End Whenever generated tasks for: My identifier
+EXISTING_CRON
+
+      assert_equal existing, @command.send(:prepare, existing)
+    end
+
+    should "trim off the top lines of the file" do
+      @command = Whenever::CommandLine.new(:update => true, :identifier => 'My identifier', :cut => '3')
+      existing = <<-EXISTING_CRON
+# Useless Comments
+# at the top of the file
+
+# Begin Whenever generated tasks for: My identifier
+My whenever job that was already here
+# End Whenever generated tasks for: My identifier
+EXISTING_CRON
+
+      new_cron = <<-NEW_CRON
+# Begin Whenever generated tasks for: My identifier
+My whenever job that was already here
+# End Whenever generated tasks for: My identifier
+NEW_CRON
+
+      assert_equal new_cron, @command.send(:prepare, existing)
+    end
+
+    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
+
+end
diff --git a/ruby-whenever/test/functional/output_at_test.rb b/ruby-whenever/test/functional/output_at_test.rb
new file mode 100644 (file)
index 0000000..2295a0e
--- /dev/null
@@ -0,0 +1,268 @@
+require File.expand_path(File.dirname(__FILE__) + "/../test_helper")
+
+class OutputAtTest < Test::Unit::TestCase
+  
+  context "weekday at a (single) given time" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        every "weekday", :at => '5:02am' do
+          command "blahblah"
+        end
+      file
+    end
+    
+    should "output the command using that time" do
+      assert_match '2 5 * * 1-5 blahblah', @output
+    end
+  end
+  
+  context "weekday at a multiple diverse times, via an array" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        every "weekday", :at => %w(5:02am 3:52pm) do
+          command "blahblah"
+        end
+      file
+    end
+    
+    should "output the commands for both times given" do
+      assert_match '2 5 * * 1-5 blahblah', @output
+      assert_match '52 15 * * 1-5 blahblah', @output
+    end
+  end
+  
+  context "weekday at a multiple diverse times, comma separated" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        every "weekday", :at => '5:02am, 3:52pm' do
+          command "blahblah"
+        end
+      file
+    end
+    
+    should "output the commands for both times given" do
+      assert_match '2 5 * * 1-5 blahblah', @output
+      assert_match '52 15 * * 1-5 blahblah', @output
+    end
+  end
+  
+  context "weekday at a multiple aligned times" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        every "weekday", :at => '5:02am, 3:02pm' do
+          command "blahblah"
+        end
+      file
+    end
+    
+    should "output the command using one entry because the times are aligned" do
+      assert_match '2 5,15 * * 1-5 blahblah', @output
+    end
+  end
+  
+  context "various days at a various aligned times" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        every "mon,wed,fri", :at => '5:02am, 3:02pm' do
+          command "blahblah"
+        end
+      file
+    end
+    
+    should "output the command using one entry because the times are aligned" do
+      assert_match '2 5,15 * * 1,3,5 blahblah', @output
+    end
+  end
+  
+  context "various days at a various aligned times using a runner" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        set :path, '/your/path'
+        every "mon,wed,fri", :at => '5:02am, 3:02pm' do
+          runner "blahblah"
+        end
+      file
+    end
+    
+    should "output the runner using one entry because the times are aligned" do
+      assert_match %(2 5,15 * * 1,3,5 cd /your/path && script/runner -e production 'blahblah'), @output
+    end
+  end
+  
+  context "various days at a various aligned times using a rake task" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        set :path, '/your/path'
+        every "mon,wed,fri", :at => '5:02am, 3:02pm' do
+          rake "blah:blah"
+        end
+      file
+    end
+    
+    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
+    end
+  end
+  
+  context "A command every 1.month at very diverse times" do
+    setup do
+      @output = Whenever.cron \
+      <<-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
+          command "blahblah"
+        end
+      file
+    end
+    
+    should "output 6 commands since none align" do
+      # The 1.month commands
+      assert_match '2 5 1 * * blahblah', @output
+      assert_match '22 14 17 * * blahblah', @output
+      assert_match '33 3 3 * * blahblah', @output
+      
+      # The 1.day commands
+      assert_match '2 5 * * * blahblah', @output
+      assert_match '22 14 * * * blahblah', @output
+      assert_match '33 3 * * * blahblah', @output
+    end
+  end
+  
+  context "Multiple commands output every :reboot" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        every :reboot do
+          command "command_1"
+          command "command_2"
+        end
+      file
+    end
+    
+    should "output both commands @reboot" do
+      assert_match "@reboot command_1", @output
+      assert_match "@reboot command_2", @output
+    end
+  end
+  
+  context "Many different job types output every :day" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        set :path, '/your/path'
+        every :daily do
+          rake "blah:blah"
+          runner "runner_1"
+          command "command_1"
+          runner "runner_2"
+          command "command_2"
+        end
+      file
+    end
+    
+    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 && script/runner -e production 'runner_1'), @output
+      assert_match '@daily command_1', @output
+      assert_match %(@daily cd /your/path && script/runner -e production 'runner_2'), @output
+      assert_match '@daily command_2', @output
+    end
+  end
+  
+  context "every 5 minutes but but starting at 1" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        every 5.minutes, :at => 1 do
+          command "blahblah"
+        end
+      file
+    end
+    
+    should "output the command using that time" do
+      assert_match '1,6,11,16,21,26,31,36,41,46,51,56 * * * * blahblah', @output
+    end
+  end
+
+  context "every 4 minutes but starting at 2" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        every 4.minutes, :at => 2 do
+          command "blahblah"
+        end
+      file
+    end
+    
+    should "output the command using that time" do
+      assert_match '2,6,10,14,18,22,26,30,34,38,42,46,50,54,58 * * * * blahblah', @output
+    end
+  end
+
+  context "every 3 minutes but starting at 7" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        every 3.minutes, :at => 7 do
+          command "blahblah"
+        end
+      file
+    end
+    
+    should "output the command using that time" do
+      assert_match '7,10,13,16,19,22,25,28,31,34,37,40,43,46,49,52,55,58 * * * * blahblah', @output
+    end
+  end
+
+  context "every 2 minutes but starting at 27" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        every 2.minutes, :at => 27 do
+          command "blahblah"
+        end
+      file
+    end
+    
+    should "output the command using that time" do
+      assert_match '27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59 * * * * blahblah', @output
+    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
diff --git a/ruby-whenever/test/functional/output_default_defined_jobs_test.rb b/ruby-whenever/test/functional/output_default_defined_jobs_test.rb
new file mode 100644 (file)
index 0000000..1f3ce87
--- /dev/null
@@ -0,0 +1,345 @@
+require File.expand_path(File.dirname(__FILE__) + "/../test_helper")
+
+class OutputDefaultDefinedJobsTest < Test::Unit::TestCase
+
+  # command
+
+  context "A plain command with the job template set to nil" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        every 2.hours do
+          command "blahblah"
+        end
+      file
+    end
+
+    should "output the command" do
+      assert_match /^.+ .+ .+ .+ blahblah$/, @output
+    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 with a job_template using a normal parameter" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, "/bin/bash -l -c 'cd :path && :job'"
+        every 2.hours do
+          set :path, "/tmp"
+          command "blahblah"
+        end
+      file
+    end
+
+    should "output the command using that job_template" do
+      assert_match /^.+ .+ .+ .+ \/bin\/bash -l -c 'cd \/tmp \&\& 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 overrides the job_template set using a parameter" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, "/bin/bash -l -c 'cd :path && :job'"
+        every 2.hours do
+          set :path, "/tmp"
+          command "blahblah", :job_template => "/bin/sh -l -c 'cd :path && :job'"
+        end
+      file
+    end
+
+    should "output the command using that job_template" do
+      assert_match /^.+ .+ .+ .+ \/bin\/sh -l -c 'cd \/tmp && 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
+
+  context "A runner with path set" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        set :path, '/my/path'
+        every 2.hours do
+          runner 'blahblah'
+        end
+      file
+    end
+
+    should "output the runner using that path" do
+      assert_match two_hours + %( cd /my/path && script/runner -e production 'blahblah'), @output
+    end
+  end
+
+  context "A runner that overrides the path set" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        set :path, '/my/path'
+        every 2.hours do
+          runner "blahblah", :path => '/some/other/path'
+        end
+      file
+    end
+
+    should "output the runner using that path" do
+      assert_match two_hours + %( cd /some/other/path && script/runner -e production 'blahblah'), @output
+    end
+  end
+
+  context "A runner for an app with bin/rails" do
+    setup do
+      Whenever.expects(:path).at_least_once.returns('/my/path')
+      Whenever.expects(:bin_rails?).returns(true)
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        every 2.hours do
+          runner 'blahblah'
+        end
+      file
+    end
+
+    should "use a script/rails runner job by default" do
+      assert_match two_hours + %( cd /my/path && bin/rails runner -e production 'blahblah'), @output
+    end
+  end
+
+  context "A runner for an app with script/rails" do
+    setup do
+      Whenever.expects(:path).at_least_once.returns('/my/path')
+      Whenever.expects(:script_rails?).returns(true)
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        every 2.hours do
+          runner 'blahblah'
+        end
+      file
+    end
+
+    should "use a script/rails runner job by default" do
+      assert_match two_hours + %( cd /my/path && script/rails runner -e production 'blahblah'), @output
+    end
+  end
+
+  # rake
+
+  context "A rake command with path set" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        set :path, '/my/path'
+        every 2.hours do
+          rake "blahblah"
+        end
+      file
+    end
+
+    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
+    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
+
+  context "A rake command that overrides the path set" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        set :path, '/my/path'
+        every 2.hours do
+          rake "blahblah", :path => '/some/other/path'
+        end
+      file
+    end
+
+    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
+    end
+  end
+
+  context "A rake command that sets the environment variable" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        set :path, '/my/path'
+        set :environment_variable, 'RAKE_ENV'
+        every 2.hours do
+          rake "blahblah"
+        end
+      file
+    end
+
+    should "output the rake command using that environment variable" do
+      assert_match two_hours + ' cd /my/path && RAKE_ENV=production bundle exec rake blahblah --silent', @output
+    end
+  end
+
+  context "A rake command that overrides the environment variable" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        set :path, '/my/path'
+        set :environment_variable, 'RAKE_ENV'
+        every 2.hours do
+          rake "blahblah", :environment_variable => 'SOME_ENV'
+        end
+      file
+    end
+
+    should "output the rake command using that environment variable" do
+      assert_match two_hours + ' cd /my/path && SOME_ENV=production bundle exec rake blahblah --silent', @output
+    end
+  end
+
+    # script
+
+  context "A script command with path set" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        set :path, '/my/path'
+        every 2.hours do
+          script "blahblah"
+        end
+      file
+    end
+
+    should "output the script command using that path" do
+      assert_match two_hours + ' cd /my/path && RAILS_ENV=production bundle exec script/blahblah', @output
+    end
+  end
+
+  context "A script command 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
+          script 'blahblah'
+        end
+      file
+    end
+
+    should "not use invoke through bundler" do
+      assert_match two_hours + ' cd /my/path && RAILS_ENV=production script/blahblah', @output
+    end
+  end
+
+  context "A script command that uses output" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        set :output, '/log/file'
+        set :path, '/my/path'
+        every 2.hours do
+          script "blahblah", :path => '/some/other/path'
+        end
+      file
+    end
+
+    should "output the script command using that path" do
+      assert_match two_hours + ' cd /some/other/path && RAILS_ENV=production bundle exec script/blahblah >> /log/file 2>&1', @output
+    end
+  end
+
+  context "A script command that uses an environment variable" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        set :environment_variable, 'RAKE_ENV'
+        set :path, '/my/path'
+        every 2.hours do
+          script "blahblah"
+        end
+      file
+    end
+
+    should "output the script command using that environment variable" do
+      assert_match two_hours + ' cd /my/path && RAKE_ENV=production bundle exec script/blahblah', @output
+    end
+  end
+
+end
diff --git a/ruby-whenever/test/functional/output_defined_job_test.rb b/ruby-whenever/test/functional/output_defined_job_test.rb
new file mode 100644 (file)
index 0000000..970677d
--- /dev/null
@@ -0,0 +1,111 @@
+require File.expand_path(File.dirname(__FILE__) + "/../test_helper")
+
+class OutputDefinedJobTest < Test::Unit::TestCase
+
+  context "A defined job with a :task" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        job_type :some_job, "before :task after"
+        every 2.hours do
+          some_job "during"
+        end
+      file
+    end
+
+    should "output the defined job with the task" do
+      assert_match /^.+ .+ .+ .+ before during after$/, @output
+    end
+  end
+
+  context "A defined job with a :task and some options" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        job_type :some_job, "before :task after :option1 :option2"
+        every 2.hours do
+          some_job "during", :option1 => 'happy', :option2 => 'birthday'
+        end
+      file
+    end
+
+    should "output the defined job with the task and options" do
+      assert_match /^.+ .+ .+ .+ before during after happy birthday$/, @output
+    end
+  end
+
+  context "A defined job with a :task and an option where the option is set globally" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        job_type :some_job, "before :task after :option1"
+        set :option1, 'happy'
+        every 2.hours do
+          some_job "during"
+        end
+      file
+    end
+
+    should "output the defined job with the task and options" do
+      assert_match /^.+ .+ .+ .+ before during after happy$/, @output
+    end
+  end
+
+  context "A defined job with a :task and an option where the option is set globally and locally" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        job_type :some_job, "before :task after :option1"
+        set :option1, 'global'
+        every 2.hours do
+          some_job "during", :option1 => 'local'
+        end
+      file
+    end
+
+    should "output the defined job using the local option" do
+      assert_match /^.+ .+ .+ .+ before during after local$/, @output
+    end
+  end
+
+  context "A defined job with a :task and an option that is not set" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        job_type :some_job, "before :task after :option1"
+        every 2.hours do
+          some_job "during", :option2 => 'happy'
+        end
+      file
+    end
+
+    should "output the defined job with that option left untouched" do
+      assert_match /^.+ .+ .+ .+ before during after :option1$/, @output
+    end
+  end
+
+  context "A defined job that uses a :path where none is explicitly set" do
+    setup do
+      Whenever.stubs(:path).returns('/my/path')
+
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        job_type :some_job, "cd :path && :task"
+        every 2.hours do
+          some_job 'blahblah'
+        end
+      file
+    end
+
+    should "default to using the Whenever.path" do
+      assert_match two_hours + %( cd /my/path && blahblah), @output
+    end
+  end
+
+end
diff --git a/ruby-whenever/test/functional/output_env_test.rb b/ruby-whenever/test/functional/output_env_test.rb
new file mode 100644 (file)
index 0000000..320a676
--- /dev/null
@@ -0,0 +1,33 @@
+require File.expand_path(File.dirname(__FILE__) + "/../test_helper")
+
+class OutputEnvTest < Test::Unit::TestCase
+
+  context "The output from Whenever with environment variables set" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        env :MYVAR, 'blah'
+        env 'MAILTO', "someone@example.com"
+        env :BLANKVAR, ''
+        env :NILVAR, nil
+      file
+    end
+
+    should "output MYVAR environment variable" do
+      assert_match "MYVAR=blah", @output
+    end
+  
+    should "output MAILTO environment variable" do
+      assert_match "MAILTO=someone@example.com", @output
+    end
+
+    should "output BLANKVAR environment variable" do
+      assert_match "BLANKVAR=\"\"", @output
+    end
+
+    should "output NILVAR environment variable" do
+      assert_match "NILVAR=\"\"", @output
+    end
+  end
+
+end
diff --git a/ruby-whenever/test/functional/output_jobs_for_roles_test.rb b/ruby-whenever/test/functional/output_jobs_for_roles_test.rb
new file mode 100644 (file)
index 0000000..0bf9e4e
--- /dev/null
@@ -0,0 +1,85 @@
+require File.expand_path(File.dirname(__FILE__) + "/../test_helper")
+
+class OutputJobsForRolesTest < Test::Unit::TestCase
+  context "with one role requested and specified on the job" do
+    setup do
+      @output = Whenever.cron :roles => [:role1], :string => \
+      <<-file
+        every 2.hours, :roles => [:role1] do
+          command "blahblah"
+        end
+      file
+    end
+
+    should "output the cron job" do
+      assert_equal two_hours + " /bin/bash -l -c 'blahblah'\n\n", @output
+    end
+  end
+
+  context "with one role requested but none specified on the job" do
+    setup do
+      @output = Whenever.cron :roles => [:role1], :string => \
+      <<-file
+        every 2.hours do
+          command "blahblah"
+        end
+      file
+    end
+
+    # this should output the job because not specifying a role means "all roles"
+    should "output the cron job" do
+      assert_equal two_hours + " /bin/bash -l -c 'blahblah'\n\n", @output
+    end
+  end
+
+  context "with no roles requested but one specified on the job" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        every 2.hours, :roles => [:role1] do
+          command "blahblah"
+        end
+      file
+    end
+
+    # this should output the job because not requesting roles means "all roles"
+    should "output the cron job" do
+      assert_equal two_hours + " /bin/bash -l -c 'blahblah'\n\n", @output
+    end
+  end
+
+  context "with a different role requested than the one specified on the job" do
+    setup do
+      @output = Whenever.cron :roles => [:role1], :string => \
+      <<-file
+        every 2.hours, :roles => [:role2] do
+          command "blahblah"
+        end
+      file
+    end
+
+    should "not output the cron job" do
+      assert_equal "", @output
+    end
+  end
+
+  context "with 2 roles requested and a job defined for each" do
+    setup do
+      @output = Whenever.cron :roles => [:role1, :role2], :string => \
+      <<-file
+        every 2.hours, :roles => [:role1] do
+          command "role1_cmd"
+        end
+
+        every :hour, :roles => [:role2] do
+          command "role2_cmd"
+        end
+      file
+    end
+
+    should "output both jobs" do
+      assert_match two_hours + " /bin/bash -l -c 'role1_cmd'", @output
+      assert_match "0 * * * * /bin/bash -l -c 'role2_cmd'", @output
+    end
+  end
+end
diff --git a/ruby-whenever/test/functional/output_redirection_test.rb b/ruby-whenever/test/functional/output_redirection_test.rb
new file mode 100644 (file)
index 0000000..b03abce
--- /dev/null
@@ -0,0 +1,326 @@
+require File.expand_path(File.dirname(__FILE__) + "/../test_helper")
+
+class OutputRedirectionTest < Test::Unit::TestCase
+
+  context "A command when the output is set to nil" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        set :output, nil
+        every 2.hours do
+          command "blahblah"
+        end
+      file
+    end
+  
+    should "output the command with the log syntax appended" do
+      assert_match /^.+ .+ .+ .+ blahblah >> \/dev\/null 2>&1$/, @output
+    end
+  end
+
+
+  context "A command when the output is set" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        set :output, 'logfile.log'
+        every 2.hours do
+          command "blahblah"
+        end
+      file
+    end
+  
+    should "output the command with the log syntax appended" do
+      assert_match /^.+ .+ .+ .+ blahblah >> logfile.log 2>&1$/, @output
+    end
+  end
+
+  context "A command when the error and standard output is set by the command" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        every 2.hours do
+          command "blahblah", :output => {:standard => 'dev_null', :error => 'dev_err'}
+        end
+      file
+    end
+
+    should "output the command without the log syntax appended" do
+      assert_match /^.+ .+ .+ .+ blahblah >> dev_null 2>> dev_err$/, @output
+    end
+  end
+
+  context "A command when the output is set and the comand overrides it" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        set :output, 'logfile.log'
+        every 2.hours do
+          command "blahblah", :output => 'otherlog.log'
+        end
+      file
+    end
+  
+    should "output the command with the command syntax appended" do
+      assert_no_match /.+ .+ .+ .+ blahblah >> logfile.log 2>&1/, @output
+      assert_match /^.+ .+ .+ .+ blahblah >> otherlog.log 2>&1$/, @output
+    end
+  end
+
+  context "A command when the output is set and the comand overrides with standard and error" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        set :output, 'logfile.log'
+        every 2.hours do
+          command "blahblah", :output => {:error => 'dev_err', :standard => 'dev_null' }
+        end
+      file
+    end
+  
+    should "output the command with the overridden redirection syntax appended" do
+      assert_no_match /.+ .+ .+ .+ blahblah >> logfile.log 2>&1/, @output
+      assert_match /^.+ .+ .+ .+ blahblah >> dev_null 2>> dev_err$/, @output
+    end
+  end
+
+  context "A command when the output is set and the comand rejects it" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        set :output, 'logfile.log'
+        every 2.hours do
+          command "blahblah", :output => false
+        end
+      file
+    end
+
+    should "output the command without the log syntax appended" do
+      assert_no_match /.+ .+ .+ .+ blahblah >> logfile.log 2>&1/, @output
+      assert_match /^.+ .+ .+ .+ blahblah$/, @output
+    end
+  end
+
+  context "A command when the output is set and is overridden by the :set option" do
+    setup do
+      @output = Whenever.cron :set => 'output=otherlog.log', :string => \
+      <<-file
+        set :job_template, nil
+        set :output, 'logfile.log'
+        every 2.hours do
+          command "blahblah"
+        end
+      file
+    end
+
+    should "output the otherlog.log as the log file" do
+      assert_no_match /.+ .+ .+ .+ blahblah >> logfile.log 2>&1/, @output
+      assert_match /^.+ .+ .+ .+ blahblah >> otherlog.log 2>&1/, @output
+    end
+  end
+
+  context "A command when the error and standard output is set" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        set :output, {:error => 'dev_err', :standard => 'dev_null' }
+        every 2.hours do
+          command "blahblah"
+        end
+      file
+    end
+
+    should "output the command without the redirection syntax appended" do
+      assert_match /^.+ .+ .+ .+ blahblah >> dev_null 2>> dev_err$/, @output
+    end
+  end
+
+  context "A command when error output is set" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        set :output, {:error => 'dev_null'}
+        every 2.hours do
+          command "blahblah"
+        end
+      file
+    end
+
+    should "output the command without the standard error syntax appended" do
+      assert_match /^.+ .+ .+ .+ blahblah 2>> dev_null$/, @output
+    end
+  end
+
+  context "A command when the standard output is set" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        set :output, {:standard => 'dev_out'}
+        every 2.hours do
+          command "blahblah"
+        end
+      file
+    end
+
+    should "output the command with standard output syntax appended" do
+      assert_match /^.+ .+ .+ .+ blahblah >> dev_out$/, @output
+    end
+  end
+
+  context "A command when error output is set by the command" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        every 2.hours do
+          command "blahblah", :output => {:error => 'dev_err'}
+        end
+      file
+    end
+
+    should "output the command without the log syntax appended" do
+      assert_match /^.+ .+ .+ .+ blahblah 2>> dev_err$/, @output
+    end
+  end
+
+  context "A command when standard output is set by the command" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        every 2.hours do
+          command "blahblah", :output => {:standard => 'dev_out'}
+        end
+      file
+    end
+
+    should "output the command without the log syntax appended" do
+      assert_match /^.+ .+ .+ .+ blahblah >> dev_out$/, @output
+    end
+  end
+
+  context "A command when standard output is set to nil" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        every 2.hours do
+          command "blahblah", :output => {:standard => nil}
+        end
+      file
+    end
+
+    should "output the command with stdout directed to /dev/null" do
+      assert_match /^.+ .+ .+ .+ blahblah > \/dev\/null$/, @output
+    end
+  end
+
+  context "A command when standard error is set to nil" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        every 2.hours do
+          command "blahblah", :output => {:error => nil}
+        end
+      file
+    end
+
+    should "output the command with stderr directed to /dev/null" do
+      assert_match /^.+ .+ .+ .+ blahblah 2> \/dev\/null$/, @output
+    end
+  end
+
+  context "A command when standard output and standard error is set to nil" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        every 2.hours do
+          command "blahblah", :output => {:error => nil, :standard => nil}
+        end
+      file
+    end
+
+    should "output the command with stderr directed to /dev/null" do
+      assert_match /^.+ .+ .+ .+ blahblah > \/dev\/null 2>&1$/, @output
+    end
+  end
+
+  context "A command when standard output is set and standard error is set to nil" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        every 2.hours do
+          command "blahblah", :output => {:error => nil, :standard => 'my.log'}
+        end
+      file
+    end
+
+    should "output the command with stderr directed to /dev/null" do
+      assert_match /^.+ .+ .+ .+ blahblah >> my.log 2> \/dev\/null$/, @output
+    end
+  end
+
+  context "A command when standard output is nil and standard error is set" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        every 2.hours do
+          command "blahblah", :output => {:error => 'my_error.log', :standard => nil}
+        end
+      file
+    end
+
+    should "output the command with stderr directed to /dev/null" do
+      assert_match /^.+ .+ .+ .+ blahblah >> \/dev\/null 2>> my_error.log$/, @output
+    end
+  end
+
+  context "A command when the deprecated :cron_log is set" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        set :cron_log, "cron.log"
+        every 2.hours do
+          command "blahblah"
+        end
+      file
+    end
+
+    should "output the command with with the stdout and stderr going to the log" do
+      assert_match /^.+ .+ .+ .+ blahblah >> cron.log 2>&1$/, @output
+    end
+  end
+
+
+  context "A command when the standard output is set to a lambda" do
+    setup do
+      @output = Whenever.cron \
+      <<-file
+        set :job_template, nil
+        set :output, lambda { "2>&1 | logger -t whenever_cron" }
+        every 2.hours do
+          command "blahblah"
+        end
+      file
+    end
+
+    should "output the command by result of the lambda evaluated" do
+      assert_match /^.+ .+ .+ .+ blahblah 2>&1 | logger -t whenever_cron$/, @output
+    end
+  end
+
+end
diff --git a/ruby-whenever/test/test_helper.rb b/ruby-whenever/test/test_helper.rb
new file mode 100644 (file)
index 0000000..54aed70
--- /dev/null
@@ -0,0 +1,18 @@
+# Want to test the files here, in lib, not in an installed version of the gem.
+$:.unshift File.expand_path(File.dirname(__FILE__) + '/../lib')
+require 'whenever'
+require 'test/unit'
+require 'shoulda'
+require 'mocha'
+
+module TestExtensions
+  
+  def two_hours
+    "0 0,2,4,6,8,10,12,14,16,18,20,22 * * *"
+  end
+  
+end
+
+class Test::Unit::TestCase
+  include TestExtensions
+end
\ No newline at end of file
diff --git a/ruby-whenever/test/unit/capistrano_support_test.rb b/ruby-whenever/test/unit/capistrano_support_test.rb
new file mode 100644 (file)
index 0000000..4816dac
--- /dev/null
@@ -0,0 +1,169 @@
+require File.expand_path(File.dirname(__FILE__) + "/../test_helper")
+require File.expand_path(File.dirname(__FILE__) + "/../../lib/whenever/capistrano/v2/support")
+
+class CapistranoSupportTestSubject
+  include Whenever::CapistranoSupport
+end
+
+class CapistranoSupportTest < Test::Unit::TestCase
+  context "when using capistrano support module" do
+    setup do
+      @capistrano = CapistranoSupportTestSubject.new
+      configuration = mock
+      configuration.stubs(:load).yields(@capistrano)
+      Whenever::CapistranoSupport.load_into(configuration)
+    end
+
+    context "#whenever_options" do
+      should "return fetch(:whenever_options)" do
+        @capistrano.expects(:fetch).with(:whenever_options)
+        @capistrano.whenever_options
+      end
+    end
+
+    context "#whenever_roles with one role" do
+      setup do
+        @capistrano.stubs(:whenever_options).returns({:roles => :role1})
+      end
+
+      should "return whenever_options[:roles] as an array" do
+        assert_equal [:role1], @capistrano.whenever_roles
+      end
+    end
+
+    context "#whenever_roles with no defined roles" do
+      setup do
+        @capistrano.stubs(:whenever_options).returns({})
+      end
+
+      should "return an empty array" do
+        assert_equal [], @capistrano.whenever_roles
+      end
+    end
+
+    context "#whenever_servers" do
+      should "return the list of servers returned by find_servers" do
+        @capistrano.stubs(:whenever_options).returns({})
+        @capistrano.stubs(:find_servers).returns([:server1, :server2])
+
+        assert_equal [:server1, :server2], @capistrano.whenever_servers
+      end
+    end
+
+    context "#whenever_server_roles" do
+      setup do
+        @mock_servers = ["foo", "bar"]
+        @capistrano.stubs(:whenever_servers).returns(@mock_servers)
+      end
+
+      should "return a map of servers to their role(s)" do
+        @capistrano.stubs(:whenever_roles).returns([:role1, :role2])
+        @capistrano.stubs(:role_names_for_host).with("foo").returns([:role1])
+        @capistrano.stubs(:role_names_for_host).with("bar").returns([:role2])
+        assert_equal({"foo" => [:role1], "bar" => [:role2]}, @capistrano.whenever_server_roles)
+      end
+
+      should "exclude non-requested roles" do
+        @capistrano.stubs(:whenever_roles).returns([:role1, :role2])
+        @capistrano.stubs(:role_names_for_host).with("foo").returns([:role1, :role3])
+        @capistrano.stubs(:role_names_for_host).with("bar").returns([:role2])
+        assert_equal({"foo" => [:role1], "bar" => [:role2]}, @capistrano.whenever_server_roles)
+      end
+
+      should "include all roles for servers w/ >1 when they're requested" do
+        @capistrano.stubs(:whenever_roles).returns([:role1, :role2, :role3])
+        @capistrano.stubs(:role_names_for_host).with("foo").returns([:role1, :role3])
+        @capistrano.stubs(:role_names_for_host).with("bar").returns([:role2])
+        assert_equal({"foo" => [:role1, :role3], "bar" => [:role2]}, @capistrano.whenever_server_roles)
+      end
+    end
+
+    context "#whenever_prepare_for_rollback" do
+      should "set path to previous_release if there is a previous release" do
+        args = {}
+        @capistrano.stubs(:fetch).with(:previous_release).returns("/some/path/20121221010000")
+        assert_equal({:path => "/some/path/20121221010000"}, @capistrano.whenever_prepare_for_rollback(args))
+      end
+
+      should "set path to release_path and flags to whenever_clear_flags if there is no previous release" do
+        args = {}
+        @capistrano.stubs(:fetch).with(:previous_release).returns(nil)
+        @capistrano.stubs(:fetch).with(:release_path).returns("/some/path/20121221010000")
+        @capistrano.stubs(:fetch).with(:whenever_clear_flags).returns("--clear-crontab whenever_identifier")
+        assert_equal({:path => "/some/path/20121221010000", :flags => "--clear-crontab whenever_identifier"}, @capistrano.whenever_prepare_for_rollback(args))
+      end
+    end
+
+    context "#whenever_run_commands" do
+      should "require :command arg" do
+        assert_raise ArgumentError do
+          @capistrano.whenever_run_commands(:options => {}, :path => {}, :flags => {})
+        end
+      end
+
+      should "require :path arg" do
+        assert_raise ArgumentError do
+          @capistrano.whenever_run_commands(:options => {}, :command => {}, :flags => {})
+        end
+      end
+
+      should "require :flags arg" do
+        assert_raise ArgumentError do
+          @capistrano.whenever_run_commands(:options => {}, :path => {}, :command => {})
+        end
+      end
+
+      context "with some servers defined" do
+        setup do
+          @mock_server1, @mock_server2, @mock_server3 = mock("Server1"), mock("Server2"), mock("Server3")
+          @mock_server1.stubs(:host).returns("server1.foo.com")
+          @mock_server2.stubs(:host).returns("server2.foo.com")
+          @mock_server3.stubs(:host => "server3.foo.com", :port => 1022, :user => 'test')
+          @mock_servers = [@mock_server1, @mock_server2]
+        end
+
+        should "call run for each host w/ appropriate role args" do
+          @capistrano.stubs(:role_names_for_host).with(@mock_server1).returns([:role1])
+          @capistrano.stubs(:role_names_for_host).with(@mock_server2).returns([:role2])
+          @capistrano.stubs(:whenever_servers).returns(@mock_servers)
+          roles = [:role1, :role2]
+          @capistrano.stubs(:whenever_options).returns({:roles => roles})
+
+          @capistrano.expects(:run).once.with('cd /foo/bar && whenever --flag1 --flag2 --roles role1', {:roles => roles, :hosts => @mock_server1})
+          @capistrano.expects(:run).once.with('cd /foo/bar && whenever --flag1 --flag2 --roles role2', {:roles => roles, :hosts => @mock_server2})
+
+          @capistrano.whenever_run_commands(:command => "whenever",
+                                            :path => "/foo/bar",
+                                            :flags => "--flag1 --flag2")
+        end
+
+        should "call run w/ all role args for servers w/ >1 role" do
+          @capistrano.stubs(:role_names_for_host).with(@mock_server1).returns([:role1, :role3])
+          @capistrano.stubs(:whenever_servers).returns([@mock_server1])
+          roles = [:role1, :role2, :role3]
+          @capistrano.stubs(:whenever_options).returns({:roles => roles})
+
+          @capistrano.expects(:run).once.with('cd /foo/bar && whenever --flag1 --flag2 --roles role1,role3', {:roles => roles, :hosts => @mock_server1})
+
+          @capistrano.whenever_run_commands(:command => "whenever",
+                                            :path => "/foo/bar",
+                                            :flags => "--flag1 --flag2")
+        end
+
+        should "call run w/ proper server options (port, user)" do
+          @capistrano.stubs(:role_names_for_host).with(@mock_server3).returns([:role3])
+          @capistrano.stubs(:whenever_servers).returns([@mock_server3])
+          @capistrano.stubs(:whenever_options).returns({:roles => [:role3]})
+
+          @capistrano.expects(:run).once.with do |command, options|
+            options[:hosts].user == "test" && options[:hosts].port == 1022
+          end
+
+          @capistrano.whenever_run_commands(:command => "whenever",
+                                            :path => "/foo/bar",
+                                            :flags => "--flag1 --flag2")
+        end
+      end
+    end
+  end
+end
diff --git a/ruby-whenever/test/unit/cron_test.rb b/ruby-whenever/test/unit/cron_test.rb
new file mode 100644 (file)
index 0000000..490d50c
--- /dev/null
@@ -0,0 +1,253 @@
+require File.expand_path(File.dirname(__FILE__) + "/../test_helper")
+
+class CronTest < Test::Unit::TestCase
+
+  context "When parsing time in minutes" do
+    should "raise if less than 1 minute" do
+      assert_raises ArgumentError do
+        parse_time(59.seconds)
+      end
+
+      assert_raises ArgumentError do
+        parse_time(0.minutes)
+      end
+    end
+
+    # For santity, do some tests on straight String
+    should "parse correctly" do
+      assert_equal '* * * * *', parse_time(1.minute)
+      assert_equal '0,5,10,15,20,25,30,35,40,45,50,55 * * * *', parse_time(5.minutes)
+      assert_equal '7,14,21,28,35,42,49,56 * * * *', parse_time(7.minutes)
+      assert_equal '0,30 * * * *', parse_time(30.minutes)
+      assert_equal '32 * * * *', parse_time(32.minutes)
+      assert_not_equal '60 * * * *', parse_time(60.minutes) # 60 minutes bumps up into the hour range
+    end
+
+    # Test all minutes
+    (2..59).each do |num|
+      should "parse correctly for #{num} minutes" do
+        start = 0
+        start += num unless 60.modulo(num).zero?
+        minutes = (start..59).step(num).to_a
+
+        assert_equal "#{minutes.join(',')} * * * *", parse_time(num.minutes)
+      end
+    end
+  end
+
+  context "When parsing time in hours" do
+    should "parse correctly" do
+      assert_equal '0 * * * *', parse_time(1.hour)
+      assert_equal '0 0,2,4,6,8,10,12,14,16,18,20,22 * * *', parse_time(2.hours)
+      assert_equal '0 0,3,6,9,12,15,18,21 * * *', parse_time(3.hours)
+      assert_equal '0 5,10,15,20 * * *', parse_time(5.hours)
+      assert_equal '0 17 * * *', parse_time(17.hours)
+      assert_not_equal '0 24 * * *', parse_time(24.hours) # 24 hours bumps up into the day range
+    end
+
+    (2..23).each do |num|
+      should "parse correctly for #{num} hours" do
+        start = 0
+        start += num unless 24.modulo(num).zero?
+        hours = (start..23).step(num).to_a
+
+        assert_equal "0 #{hours.join(',')} * * *", parse_time(num.hours)
+      end
+    end
+
+    should "parse correctly when given an 'at' with minutes as an Integer" do
+      assert_minutes_equals "1",  1
+      assert_minutes_equals "14", 14
+      assert_minutes_equals "27", 27
+      assert_minutes_equals "55", 55
+    end
+
+    should "parse correctly when given an 'at' with minutes as a Time" do
+      # Basically just testing that Chronic parses some times and we get the minutes out of it
+      assert_minutes_equals "1",  '3:01am'
+      assert_minutes_equals "1",  'January 21 2:01 PM'
+      assert_minutes_equals "0",  'midnight'
+      assert_minutes_equals "59", '13:59'
+    end
+  end
+
+  context "When parsing time in days (of month)" do
+    should "parse correctly" do
+      assert_equal '0 0 * * *', parse_time(1.days)
+      assert_equal '0 0 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31 * *', parse_time(2.days)
+      assert_equal '0 0 1,5,9,13,17,21,25,29 * *', parse_time(4.days)
+      assert_equal '0 0 1,8,15,22 * *', parse_time(7.days)
+      assert_equal '0 0 1,17 * *', parse_time(16.days)
+      assert_equal '0 0 17 * *', parse_time(17.days)
+      assert_equal '0 0 29 * *', parse_time(29.days)
+      assert_not_equal '0 0 30 * *', parse_time(30.days) # 30 days bumps into the month range
+    end
+
+    should "parse correctly when given an 'at' with hours, minutes as a Time" do
+      # first param is an array with [hours, minutes]
+      assert_hours_and_minutes_equals %w(3 45),  '3:45am'
+      assert_hours_and_minutes_equals %w(20 1),  '8:01pm'
+      assert_hours_and_minutes_equals %w(0 0),   'midnight'
+      assert_hours_and_minutes_equals %w(1 23),  '1:23 AM'
+      assert_hours_and_minutes_equals %w(23 59), 'March 21 11:59 pM'
+    end
+
+    should "parse correctly when given an 'at' with hours as an Integer" do
+      # first param is an array with [hours, minutes]
+      assert_hours_and_minutes_equals %w(1 0),  1
+      assert_hours_and_minutes_equals %w(3 0),  3
+      assert_hours_and_minutes_equals %w(15 0), 15
+      assert_hours_and_minutes_equals %w(19 0), 19
+      assert_hours_and_minutes_equals %w(23 0), 23
+    end
+  end
+
+  context "When parsing time in months" do
+    should "parse correctly" do
+      assert_equal '0 0 1 * *', parse_time(1.month)
+      assert_equal '0 0 1 1,3,5,7,9,11 *', parse_time(2.months)
+      assert_equal '0 0 1 1,4,7,10 *', parse_time(3.months)
+      assert_equal '0 0 1 1,5,9 *', parse_time(4.months)
+      assert_equal '0 0 1 1,6 *', parse_time(5.months)
+      assert_equal '0 0 1 7 *', parse_time(7.months)
+      assert_equal '0 0 1 8 *', parse_time(8.months)
+      assert_equal '0 0 1 9 *', parse_time(9.months)
+      assert_equal '0 0 1 10 *', parse_time(10.months)
+      assert_equal '0 0 1 11 *', parse_time(11.months)
+      assert_equal '0 0 1 12 *', parse_time(12.months)
+    end
+
+    should "parse months with a date and/or time" do
+      # should set the day to 1 if no date is given
+      assert_equal '0 17 1 * *', parse_time(1.month, nil, "5pm")
+      # should use the date if one is given
+      assert_equal '0 2 23 * *', parse_time(1.month, nil, "February 23rd at 2am")
+      # should use an iteger as the day
+      assert_equal '0 0 5 * *', parse_time(1.month, nil, 5)
+    end
+
+    should "parse correctly when given an 'at' with days, hours, minutes as a Time" do
+      # first param is an array with [days, hours, minutes]
+      assert_days_and_hours_and_minutes_equals %w(1 3 45),  'January 1st 3:45am'
+      assert_days_and_hours_and_minutes_equals %w(11 23 0), 'Feb 11 11PM'
+      assert_days_and_hours_and_minutes_equals %w(22 1 1), 'march 22nd at 1:01 am'
+      assert_days_and_hours_and_minutes_equals %w(23 0 0), 'march 22nd at midnight' # looks like midnight means the next day
+    end
+
+    should "parse correctly when given an 'at' with days as an Integer" do
+      # first param is an array with [days, hours, minutes]
+      assert_days_and_hours_and_minutes_equals %w(1 0 0),  1
+      assert_days_and_hours_and_minutes_equals %w(15 0 0), 15
+      assert_days_and_hours_and_minutes_equals %w(29 0 0), 29
+    end
+  end
+
+  context "When parsing time in days (of week)" do
+    should "parse days of the week correctly" do
+      {
+        '0' => %w(sun Sunday SUNDAY SUN),
+        '1' => %w(mon Monday MONDAY MON),
+        '2' => %w(tue tues Tuesday TUESDAY TUE),
+        '3' => %w(wed Wednesday WEDNESDAY WED),
+        '4' => %w(thu thurs thur Thursday THURSDAY THU),
+        '5' => %w(fri Friday FRIDAY FRI),
+        '6' => %w(sat Saturday SATURDAY SAT)
+      }.each do |day, day_tests|
+        day_tests.each do |day_test|
+          assert_equal "0 0 * * #{day}", parse_time(day_test)
+        end
+      end
+    end
+
+    should "allow additional directives" do
+      assert_equal '30 13 * * 5', parse_time('friday', nil, "1:30 pm")
+      assert_equal '22 2 * * 1', parse_time('Monday', nil, "2:22am")
+      assert_equal '55 17 * * 4', parse_time('THU', nil, "5:55PM")
+    end
+
+    should "parse weekday correctly" do
+      assert_equal '0 0 * * 1-5', parse_time('weekday')
+      assert_equal '0 0 * * 1-5', parse_time('Weekdays')
+      assert_equal '0 1 * * 1-5', parse_time('Weekdays', nil, "1:00 am")
+      assert_equal '59 5 * * 1-5', parse_time('Weekdays', nil, "5:59 am")
+    end
+
+    should "parse weekend correctly" do
+      assert_equal '0 0 * * 6,0', parse_time('weekend')
+      assert_equal '0 0 * * 6,0', parse_time('Weekends')
+      assert_equal '0 7 * * 6,0', parse_time('Weekends', nil, "7am")
+      assert_equal '2 18 * * 6,0', parse_time('Weekends', nil, "6:02PM")
+    end
+  end
+
+  context "When parsing time using the cron shortcuts" do
+    should "parse a :symbol into the correct shortcut" do
+      assert_equal '@reboot',   parse_time(:reboot)
+      assert_equal '@annually', parse_time(:annually)
+      assert_equal '@yearly',   parse_time(:yearly)
+      assert_equal '@daily',    parse_time(:daily)
+      assert_equal '@midnight', parse_time(:midnight)
+      assert_equal '@monthly',  parse_time(:monthly)
+      assert_equal '@weekly',   parse_time(:weekly)
+      assert_equal '@hourly',   parse_time(:hourly)
+    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
+      assert_raises ArgumentError do
+        parse_time(:hourly, nil, "1:00 am")
+      end
+
+      assert_raises ArgumentError do
+        parse_time(:reboot, nil, 5)
+      end
+
+      assert_raises ArgumentError do
+        parse_time(:daily, 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 *',
+               "*\t*\t*\t*\t*",
+               '@reboot', '@yearly', '@annually', '@monthly', '@weekly',
+               '@daily', '@midnight', '@hourly']
+      crons.each do |cron|
+        assert_equal cron, parse_time(cron)
+      end
+    end
+  end
+
+private
+
+  def assert_days_and_hours_and_minutes_equals(expected, time)
+    cron = parse_time(2.months, 'some task', time)
+    minutes, hours, days, *garbage = cron.split(' ')
+    assert_equal expected, [days, hours, minutes]
+  end
+
+  def assert_hours_and_minutes_equals(expected, time)
+    cron = parse_time(2.days, 'some task', time)
+    minutes, hours, *garbage = cron.split(' ')
+    assert_equal expected, [hours, minutes]
+  end
+
+  def assert_minutes_equals(expected, time)
+    cron = parse_time(2.hours, 'some task', time)
+    assert_equal expected, cron.split(' ')[0]
+  end
+
+  def parse_time(time = nil, task = nil, at = nil)
+    Whenever::Output::Cron.new(time, task, at).time_in_cron_syntax
+  end
+
+end
\ No newline at end of file
diff --git a/ruby-whenever/test/unit/job_test.rb b/ruby-whenever/test/unit/job_test.rb
new file mode 100644 (file)
index 0000000..25e4da8
--- /dev/null
@@ -0,0 +1,124 @@
+require File.expand_path(File.dirname(__FILE__) + "/../test_helper")
+
+class JobTest < Test::Unit::TestCase
+
+  context "A Job" do
+    should "return the :at set when #at is called" do
+      assert_equal 'foo', new_job(:at => 'foo').at
+    end
+
+    should "return the :roles set when #roles is called" do
+      assert_equal ['foo', 'bar'], new_job(:roles => ['foo', 'bar']).roles
+    end
+
+    should "return whether it has a role from #has_role?" do
+      assert new_job(:roles => 'foo').has_role?('foo')
+      assert_equal false, new_job(:roles => 'bar').has_role?('foo')
+    end
+
+    should "substitute the :task when #output is called" do
+      job = new_job(:template => ":task", :task => 'abc123')
+      assert_equal 'abc123', job.output
+    end
+
+    should "substitute the :path when #output is called" do
+      assert_equal 'foo', new_job(:template => ':path', :path => 'foo').output
+    end
+
+    should "substitute the :path with the default Whenever.path if none is provided when #output is called" do
+      Whenever.expects(:path).returns('/my/path')
+      assert_equal '/my/path', new_job(:template => ':path').output
+    end
+
+    should "not substitute parameters for which no value is set" do
+      assert_equal 'Hello :world', new_job(:template => ':matching :world', :matching => 'Hello').output
+    end
+
+    should "escape the :path" do
+      assert_equal '/my/spacey\ path', new_job(:template => ':path', :path => '/my/spacey path').output
+    end
+
+    should "escape percent signs" do
+      job = new_job(
+        :template => "before :foo after",
+        :foo => "percent -> % <- percent"
+      )
+      assert_equal %q(before percent -> \% <- percent after), job.output
+    end
+
+    should "assume percent signs are not already escaped" do
+      job = new_job(
+        :template => "before :foo after",
+        :foo => %q(percent preceded by a backslash -> \% <-)
+      )
+      assert_equal %q(before percent preceded by a backslash -> \\\% <- after), job.output
+    end
+
+    should "squish spaces and newlines" do
+      job = new_job(
+        :template => "before :foo after",
+        :foo => "newline -> \n <- newline space ->     <- space"
+      )
+
+      assert_equal "before newline -> <- newline space -> <- space after", job.output
+    end
+  end
+
+
+  context "A Job with quotes" do
+    should "output the :task if it's in single quotes" do
+      job = new_job(:template => "':task'", :task => 'abc123')
+      assert_equal %q('abc123'), job.output
+    end
+
+    should "output the :task if it's in double quotes" do
+      job = new_job(:template => '":task"', :task => 'abc123')
+      assert_equal %q("abc123"), job.output
+    end
+
+    should "output escaped single quotes in when it's wrapped in them" do
+      job = new_job(
+        :template => "before ':foo' after",
+        :foo => "quote -> ' <- quote"
+      )
+      assert_equal %q(before 'quote -> '\'' <- quote' after), job.output
+    end
+
+    should "output escaped double quotes when it's wrapped in them" do
+      job = new_job(
+        :template => 'before ":foo" after',
+        :foo => 'quote -> " <- quote'
+      )
+      assert_equal %q(before "quote -> \" <- quote" after), job.output
+    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 "reuse parameter in the job template" do
+      job = new_job(:template => ':path :task', :path => 'path', :task => "abc123", :job_template => ':path left :job right')
+      assert_equal 'path left path 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
+
+  def new_job(options={})
+    Whenever::Job.new(options)
+  end
+
+end
diff --git a/ruby-whenever/whenever.gemspec b/ruby-whenever/whenever.gemspec
new file mode 100644 (file)
index 0000000..b0bf7b2
--- /dev/null
@@ -0,0 +1,26 @@
+# -*- encoding: utf-8 -*-
+$:.push File.expand_path("../lib", __FILE__)
+require "whenever/version"
+
+Gem::Specification.new do |s|
+  s.name        = "whenever"
+  s.version     = Whenever::VERSION
+  s.platform    = Gem::Platform::RUBY
+  s.authors     = ["Javan Makhmali"]
+  s.email       = ["javan@javan.us"]
+  s.license     = "MIT"
+  s.homepage    = ""
+  s.summary     = %q{Cron jobs in ruby.}
+  s.description = %q{Clean ruby syntax for writing and deploying cron jobs.}
+  s.files         = `git ls-files`.split("\n")
+  s.test_files    = `git ls-files -- test/{functional,unit}/*`.split("\n")
+  s.executables   = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
+  s.require_paths = ["lib"]
+
+  s.add_dependency "chronic", ">= 0.6.3"
+  s.add_dependency "activesupport", ">= 2.3.4"
+
+  s.add_development_dependency "shoulda", ">= 2.1.1"
+  s.add_development_dependency "mocha", ">= 0.9.5"
+  s.add_development_dependency "rake"
+end