deploy_pin 1.8.7 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,23 +1,54 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- # Task wrapper
4
3
  module DeployPin
4
+ # A task loaded from a file in {DeployPin.tasks_path}.
5
+ #
6
+ # The file starts with a header, followed by the code to run:
7
+ #
8
+ # # 20190401135040:I
9
+ # # task_title: Backfill user names
10
+ # # affected_areas: users
11
+ #
12
+ # # === task code goes down here ===
13
+ # User.where(name: nil).find_each { |user| user.update!(name: user.email) }
14
+ #
15
+ # The first line is `# <identifier>:<group>`, or `# <identifier>:<group>:recurring`
16
+ # for a task that runs on every deployment. Negative identifiers sort after
17
+ # the other tasks of their group.
18
+ #
19
+ # The code is evaluated in the context of the task, so it can call the
20
+ # {ParallelWrapper} `parallel_*` methods and {#increment_progress!}.
21
+ #
22
+ # Tasks run under {DeployPin.statement_timeout}, unless their code calls
23
+ # {Database.execute_with_timeout} or uses Parallel.
5
24
  # :reek:TooManyMethods
6
25
  class Task # rubocop:disable Metrics/ClassLength
7
26
  extend ::DeployPin::ParallelWrapper
8
27
  include ::DeployPin::ParallelWrapper
9
28
 
10
- attr_reader :file,
11
- :identifier,
12
- :group,
13
- :title,
14
- :affected_areas,
15
- :script,
16
- :recurring,
17
- :explicit_timeout
18
-
29
+ # @return [String] path of the task file, or the task source for built-in tasks
30
+ attr_reader :file
31
+ # @return [Integer, nil] the identifier from the header, usually a timestamp
32
+ attr_reader :identifier
33
+ # @return [String, nil] the group from the header, one of {DeployPin.groups}
34
+ attr_reader :group
35
+ # @return [String] the `task_title` from the header
36
+ attr_reader :title
37
+ # @return [String] the `affected_areas` from the header
38
+ attr_reader :affected_areas
39
+ # @return [String] the code to run
40
+ attr_reader :script
41
+ # @return [String, nil] `"recurring"` for a task that runs on every deployment
42
+ attr_reader :recurring
43
+ # @return [Boolean] whether the code calls {Database.execute_with_timeout} itself
44
+ attr_reader :explicit_timeout
45
+
46
+ # @!method progress
47
+ # @return [Integer] the progress saved with {#increment_progress!} or {#save_progress!}
19
48
  delegate :progress, to: :record
20
49
 
50
+ # @param file [String] path of a task file, or task source starting with
51
+ # `# no_file_task`. Call {#parse} to load it.
21
52
  def initialize(file)
22
53
  @file = file
23
54
  @identifier = nil
@@ -29,21 +60,31 @@ module DeployPin
29
60
  @parallel = false
30
61
  end
31
62
 
63
+ # Evaluates the task code.
64
+ #
65
+ # @return [Object] the result of the code
32
66
  def run
33
67
  # eval script
34
68
  eval(script)
35
69
  end
36
70
 
71
+ # @return [Object, nil] the stored record for this task (see {Storage}), or nil
37
72
  def record
38
- DeployPin::Record.find_by(uuid: identifier)
73
+ DeployPin::Storage.record_class.find_by(uuid: identifier)
39
74
  end
40
75
 
76
+ # Creates the stored record for a non-recurring task if it does not exist yet.
77
+ #
78
+ # @return [void]
41
79
  def prepare
42
80
  return if recurring
43
81
 
44
- DeployPin::Record.create(uuid: identifier) unless record
82
+ DeployPin::Storage.record_class.create(uuid: identifier) unless record
45
83
  end
46
84
 
85
+ # Stores the completion time of a non-recurring task.
86
+ #
87
+ # @return [void]
47
88
  def mark
48
89
  return if recurring
49
90
 
@@ -51,18 +92,35 @@ module DeployPin
51
92
  record.update(completed_at: Time.current)
52
93
  end
53
94
 
95
+ # Adds to the saved progress, so a long task can resume where it stopped.
96
+ #
97
+ # @example In a task file
98
+ # User.where('id > ?', progress).find_each do |user|
99
+ # user.touch
100
+ # increment_progress!(1)
101
+ # end
102
+ # @param incrementor [Integer]
103
+ # @return [void]
104
+ # @raise [NotImplementedError] for recurring tasks
54
105
  def increment_progress!(incrementor)
55
106
  raise NotImplementedError, 'Recurring tasks do not support progress yet.' if recurring
56
107
 
57
108
  record.increment!(:progress, incrementor)
58
109
  end
59
110
 
111
+ # Overwrites the saved progress.
112
+ #
113
+ # @param value [Integer]
114
+ # @return [void]
115
+ # @raise [NotImplementedError] for recurring tasks
60
116
  def save_progress!(value)
61
117
  raise NotImplementedError, 'Recurring tasks do not support progress yet.' if recurring
62
118
 
63
119
  record.update(progress: value)
64
120
  end
65
121
 
122
+ # @return [Boolean, nil] whether the task has been completed; nil for
123
+ # recurring tasks and tasks that have not started
66
124
  def done?
67
125
  return if recurring
68
126
  return unless record
@@ -70,10 +128,14 @@ module DeployPin
70
128
  record.completed_at.present?
71
129
  end
72
130
 
131
+ # @return [Boolean] whether the task should run under {DeployPin.statement_timeout}
73
132
  def under_timeout?
74
133
  !explicit_timeout? && !parallel?
75
134
  end
76
135
 
136
+ # Reads the header and the code from {#file}.
137
+ #
138
+ # @return [void]
77
139
  # :reek:TooManyStatements
78
140
  def parse # rubocop:disable Metrics/MethodLength
79
141
  each_line do |line|
@@ -96,6 +158,8 @@ module DeployPin
96
158
  end
97
159
  # :reek:TooManyStatements
98
160
 
161
+ # @yieldparam line [String] each line of the task source
162
+ # @return [void]
99
163
  def each_line(&block)
100
164
  if file.starts_with?('# no_file_task')
101
165
  file.each_line(&block)
@@ -104,6 +168,7 @@ module DeployPin
104
168
  end
105
169
  end
106
170
 
171
+ # @return [Hash{Symbol => Object}] identifier, group, title and affected areas, for formatters
107
172
  def details
108
173
  {
109
174
  identifier:,
@@ -113,15 +178,21 @@ module DeployPin
113
178
  }
114
179
  end
115
180
 
181
+ # Whether another task has the same code but a different identifier.
182
+ #
183
+ # @param other [Task]
184
+ # @return [Boolean]
116
185
  def eql?(other)
117
186
  # same script & different identifier
118
187
  script == other.script && identifier != other.identifier
119
188
  end
120
189
 
190
+ # @return [Integer] a timestamp a year ahead, used to sort negative identifiers last
121
191
  def unreachable_future
122
192
  1.year.from_now.to_date.strftime('%Y%m%d%H%M%S').to_i
123
193
  end
124
194
 
195
+ # @return [Array(Integer, Integer)] group position and identifier, used for sorting
125
196
  def sorting_key
126
197
  if identifier.to_i.negative?
127
198
  [group_index, unreachable_future + identifier]
@@ -130,13 +201,17 @@ module DeployPin
130
201
  end
131
202
  end
132
203
 
133
- # for sorting
204
+ # Orders tasks by group position, then identifier.
205
+ #
206
+ # @param other [Task]
207
+ # @return [Integer, nil]
134
208
  def <=>(other)
135
209
  sorting_key <=> other.sorting_key
136
210
  end
137
211
 
138
212
  protected
139
213
 
214
+ # @return [Integer, nil] position of {#group} in {DeployPin.groups}
140
215
  def group_index
141
216
  DeployPin.groups.index(group)
142
217
  end
@@ -1,18 +1,33 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- # check task criteria
4
3
  module DeployPin
4
+ # Decides whether a task is selected by a list of identifiers. Each
5
+ # identifier is a group name or a task identifier:
6
+ #
7
+ # * `"I"` or `"20190401135040"` selects matching tasks that are not done yet;
8
+ # * `"I!"` or `"20190401135040!"` selects matching tasks even if they are done;
9
+ # * `"!I"` or `"!20190401135040"` excludes matching tasks.
10
+ #
11
+ # @example Re-run one task and skip group II
12
+ # DeployPin::TaskCriteria.new(identifiers: %w[I 20190401135040! !II]).suitable?(task)
5
13
  class TaskCriteria
6
- SKIP_REGEXEP = /\A!(.+[^!])\z/
7
- FORCE_REGEXP = /\A([^!].+)!\z/
14
+ # Matches an identifier that excludes tasks (`!I`).
15
+ SKIP_REGEXEP = /\A!([^!]+)\z/
16
+ # Matches an identifier that forces tasks to run again (`I!`).
17
+ FORCE_REGEXP = /\A([^!]+)!\z/
18
+ # Matches a plain identifier (`I`).
8
19
  COMMON_REGEXP = /(^[^!]?.+[^!]?$)/
9
20
 
21
+ # @return [Array<String, Integer>]
10
22
  attr_reader :identifiers
11
23
 
24
+ # @param identifiers [Array<String, Integer>] groups and task identifiers
12
25
  def initialize(identifiers:)
13
26
  @identifiers = identifiers
14
27
  end
15
28
 
29
+ # @param task [Task] a parsed task
30
+ # @return [Boolean] whether the task is selected
16
31
  def suitable?(task)
17
32
  task_cover = lambda { |task, regexp|
18
33
  items = identifiers.flat_map { |x| x.to_s.scan(regexp) }.flatten
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module DeployPin
4
- VERSION = '1.8.7'
4
+ # The gem version.
5
+ VERSION = '1.10.0'
5
6
  end
data/lib/deploy_pin.rb CHANGED
@@ -9,11 +9,123 @@ require 'deploy_pin/task_criteria'
9
9
  require 'deploy_pin/engine'
10
10
  require 'deploy_pin/database'
11
11
  require 'deploy_pin/database_engine'
12
+ require 'deploy_pin/storage'
12
13
  require 'parallel'
13
14
  require 'ruby-progressbar'
14
15
  require 'colorize'
15
16
 
17
+ # DeployPin runs one-off and recurring tasks around a deployment
18
+ # (for example, data migrations before or after the code is released).
19
+ #
20
+ # Tasks are plain Ruby files kept in {DeployPin.tasks_path}. Each one has a
21
+ # header with an identifier, a group and a title. Tasks run in group order,
22
+ # and each non-recurring task runs only once: its completion is stored in
23
+ # the configured {DeployPin.storage}.
24
+ #
25
+ # Configure it in an initializer generated by `rails g deploy_pin:install`.
26
+ #
27
+ # @example config/initializers/deploy_pin.rb
28
+ # DeployPin.setup do
29
+ # tasks_path 'lib/deploy_pin'
30
+ # groups %w[pre I II III]
31
+ # fallback_group 'III'
32
+ # statement_timeout 10.minutes
33
+ # end
34
+ #
35
+ # @!method self.continue_on_error(val = nil)
36
+ # When true, a failing task is logged and the run moves on to the next task
37
+ # instead of raising. Defaults to `false`.
38
+ # @param val [Boolean, nil] new value; omit to read the current one
39
+ # @return [Boolean]
40
+ #
41
+ # @!method self.deployment_state_transition(val = nil)
42
+ # Enables tracking of the deployment state in Redis, exposed through
43
+ # {DeploymentState#ongoing_deployment?} and {DeploymentState#pending_deployment?}.
44
+ # @example
45
+ # deployment_state_transition({
46
+ # ongoing: %w[I III], # groups that start and end the "ongoing" state
47
+ # pending: 'rollback', # group that sets the "pending" state
48
+ # ttl: 20.seconds, # how long to cache the state in memory
49
+ # redis_url: 'redis://localhost:6379'
50
+ # })
51
+ # @param val [Hash, nil] new value; omit to read the current one
52
+ # @return [Hash, nil]
53
+ #
54
+ # @!method self.fallback_group(val = nil)
55
+ # Default group for `rails g deploy_pin:task` when `--group` is not given.
56
+ # @param val [String, nil] new value; omit to read the current one
57
+ # @return [String, nil]
58
+ #
59
+ # @!method self.groups(val = nil)
60
+ # Ordered list of task groups. Tasks run in this group order, and a task's
61
+ # group must be one of these.
62
+ # @param val [Array<String>, nil] new value; omit to read the current one
63
+ # @return [Array<String>, nil]
64
+ #
65
+ # @!method self.list_formatter(val = nil)
66
+ # Prints a task for `rake deploy_pin:list`.
67
+ # @param val [Proc, nil] `->(index, task) { ... }`; omit to read the current one
68
+ # @return [Proc, nil]
69
+ #
70
+ # @!method self.short_list_formatter(val = nil)
71
+ # Prints a group of tasks for `rake deploy_pin:short_list`.
72
+ # @param val [Proc, nil] `->(group, tasks, start_index) { ... }`; omit to read the current one
73
+ # @return [Proc, nil]
74
+ #
75
+ # @!method self.run_formatter(val = nil)
76
+ # Prints progress for `rake deploy_pin:run`. It is called once before a task
77
+ # starts (`start` is true) and, for executable tasks, once after it finishes
78
+ # with its `duration` in seconds.
79
+ # @param val [Proc, nil] `->(index, task_count, task, executable, start, duration = nil) { ... }`;
80
+ # omit to read the current one
81
+ # @return [Proc, nil]
82
+ #
83
+ # @!method self.statement_timeout(val = nil)
84
+ # Default database statement timeout for tasks and for
85
+ # {Database.execute_with_timeout}. Requires ActiveRecord.
86
+ # @param val [ActiveSupport::Duration, Numeric, nil] new value; omit to read the current one
87
+ # @return [ActiveSupport::Duration, Numeric, nil]
88
+ #
89
+ # @!method self.storage(val = nil)
90
+ # Where task records are stored: `:active_record` (default) or `:mongoid`.
91
+ # @see Storage
92
+ # @param val [Symbol, nil] new value; omit to read the current one
93
+ # @return [Symbol]
94
+ #
95
+ # @!method self.task_wrapper(val = nil)
96
+ # Wraps the execution of every task, for example to add logging or error
97
+ # reporting. It must call `task_runner.call` to run the task.
98
+ # @example
99
+ # task_wrapper ->(task, task_runner) { Rails.logger.tagged(task.identifier) { task_runner.call } }
100
+ # @param val [Proc, nil] `->(task, task_runner) { ... }`; omit to read the current one
101
+ # @return [Proc]
102
+ #
103
+ # @!method self.test_framework(val = nil)
104
+ # Test framework for the test file that `rails g deploy_pin:task` creates
105
+ # next to each task; `false` turns test generation off. When not set, RSpec
106
+ # is used if the `RSpec` constant is loaded (e.g. rspec-rails in the
107
+ # `:development` group); otherwise no test is generated.
108
+ # @see TaskGenerator::TEST_FRAMEWORKS
109
+ # @param val [Symbol, false, nil] new value; omit to read the current one
110
+ # @return [Symbol, false, nil]
111
+ #
112
+ # @!method self.tests_path(val = nil)
113
+ # Directory for the tests that `rails g deploy_pin:task` creates. When not
114
+ # set, the test framework's default is used (`spec/deploy_pin` for RSpec).
115
+ # @param val [String, nil] new value; omit to read the current one
116
+ # @return [String, nil]
117
+ #
118
+ # @!method self.tasks_path(val = nil)
119
+ # Directory that holds task files.
120
+ # @param val [String, nil] new value; omit to read the current one
121
+ # @return [String, nil]
16
122
  module DeployPin
123
+ # Storage models are loaded lazily, so only the configured ORM has to be present.
124
+ autoload :ApplicationRecord, 'deploy_pin/storage/active_record/application_record'
125
+ autoload :Record, 'deploy_pin/storage/active_record/record'
126
+ autoload :MongoidRecord, 'deploy_pin/storage/mongoid_record'
127
+
128
+ # Names of the configuration options. Each one is a reader/writer method on {DeployPin}.
17
129
  OPTIONS = %i[
18
130
  continue_on_error
19
131
  deployment_state_transition
@@ -23,12 +135,17 @@ module DeployPin
23
135
  short_list_formatter
24
136
  run_formatter
25
137
  statement_timeout
138
+ storage
26
139
  task_wrapper
27
140
  tasks_path
141
+ test_framework
142
+ tests_path
28
143
  ].freeze
29
144
 
145
+ # Values the options are reset to by {setup_defaults!}.
30
146
  DEFAULTS = {
31
147
  continue_on_error: false,
148
+ storage: :active_record,
32
149
  task_wrapper: ->(_task, task_runner) { task_runner.call }
33
150
  }.freeze
34
151
 
@@ -42,10 +159,22 @@ module DeployPin
42
159
  }, __FILE__, __LINE__ - 6
43
160
  end
44
161
 
162
+ # Configures DeployPin. The block is evaluated on the {DeployPin} module, so
163
+ # every option can be called without a receiver.
164
+ #
165
+ # @example
166
+ # DeployPin.setup do
167
+ # groups %w[I II III]
168
+ # end
169
+ # @yield the configuration block
170
+ # @return [void]
45
171
  def self.setup(&block)
46
172
  instance_eval(&block)
47
173
  end
48
174
 
175
+ # Resets the options listed in {DEFAULTS} to their default values.
176
+ #
177
+ # @return [void]
49
178
  def self.setup_defaults!
50
179
  DEFAULTS.each do |option, value|
51
180
  instance_variable_set(:"@#{option}", value)
@@ -54,6 +183,10 @@ module DeployPin
54
183
 
55
184
  setup_defaults!
56
185
 
186
+ # Whether an option has been set, even to `nil`.
187
+ #
188
+ # @param option [Symbol] one of {OPTIONS}
189
+ # @return [Boolean]
57
190
  def self.enabled?(option)
58
191
  instance_variable_defined?("@#{option}")
59
192
  end
@@ -1,31 +1,54 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module DeployPin
4
+ # `rails g deploy_pin:install [--storage=mongoid]`: creates the initializer
5
+ # and, for ActiveRecord, the `deploy_pins` migration.
4
6
  class InstallGenerator < Rails::Generators::Base
5
7
  include Rails::Generators::Migration
6
8
 
7
9
  source_root File.expand_path('templates', __dir__)
8
10
  desc 'Add the migration & initializer for DeployPin'
9
11
 
12
+ class_option :storage, type: :string, default: 'active_record', enum: %w[active_record mongoid],
13
+ desc: 'Storage provider for task records'
14
+
15
+ # @param path [String] migrations directory
16
+ # @return [String] the next migration timestamp
10
17
  def self.next_migration_number(path)
11
18
  next_migration_number = current_migration_number(path) + 1
12
19
  ActiveRecord::Migration.next_migration_number(next_migration_number)
13
20
  end
14
21
 
22
+ # Creates the `deploy_pins` migration, unless the storage is Mongoid.
23
+ # @return [void]
15
24
  def copy_migrations
25
+ return if mongoid?
26
+
16
27
  migration_template 'create_deploy_pins.rb', 'db/migrate/create_deploy_pins.rb'
17
28
  end
18
29
 
30
+ # Creates `config/initializers/deploy_pin.rb`.
31
+ # @return [void]
19
32
  def copy_initializer
20
33
  template 'deploy_pin.rb', 'config/initializers/deploy_pin.rb'
21
34
  end
22
35
 
23
- def activerecord_migration_class
24
- if ::ActiveRecord::Migration.respond_to?(:current_version)
36
+ # Reminds Mongoid users to create the indexes.
37
+ # @return [void]
38
+ def mongoid_indexes_hint
39
+ say 'Run `rails db:mongoid:create_indexes` to create the DeployPin indexes.' if mongoid?
40
+ end
41
+
42
+ private
43
+
44
+ # Used by the migration template.
45
+ # :reek:UtilityFunction
46
+ def activerecord_migration_class
25
47
  "ActiveRecord::Migration[#{::ActiveRecord::Migration.current_version}]"
26
- else
27
- 'ActiveRecord::Migration'
28
48
  end
29
- end
49
+
50
+ def mongoid?
51
+ options[:storage] == 'mongoid'
52
+ end
30
53
  end
31
54
  end
@@ -1,10 +1,16 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  DeployPin.setup do
4
+ <% if options[:storage] != 'active_record' -%>
5
+ storage :<%= options[:storage] %>
6
+ <% end -%>
4
7
  tasks_path 'lib/deploy_pin'
5
8
  groups %w[pre I II III]
6
9
  fallback_group 'III'
7
10
  statement_timeout 10.minutes
11
+ # Tests generated for each task: RSpec is used when it is loaded, or set it here.
12
+ # test_framework :rspec # false to not generate tests
13
+ # tests_path 'spec/deploy_pin'
8
14
  deployment_state_transition({
9
15
  ongoing: %w[I III],
10
16
  pending: 'rollback', # enters to pending step before "rollback"
@@ -6,3 +6,8 @@ Example:
6
6
 
7
7
  This will create:
8
8
  lib/deploy_pin/{task_id}_some_name_of_task.rb
9
+ spec/deploy_pin/{task_id}_some_name_of_task_spec.rb
10
+
11
+ The test framework comes from DeployPin.test_framework (default: rspec),
12
+ and the directory from DeployPin.tests_path (default: spec/deploy_pin).
13
+ Use --skip-test to not create the test, or --test-framework=rspec to pick one.
@@ -1,13 +1,35 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module DeployPin
4
+ # `rails g deploy_pin:task <title> --group <group> [--parallel] [--recurring --identifier <id>]`:
5
+ # creates a task file in {DeployPin.tasks_path}, and a test for it with
6
+ # the configured {DeployPin.test_framework} in {DeployPin.tests_path}
7
+ # (`spec/deploy_pin` for RSpec by default).
8
+ #
9
+ # @example Skip the test, or pick the framework for one task
10
+ # rails g deploy_pin:task backfill_users -g I --skip-test
11
+ # rails g deploy_pin:task backfill_users -g I --test-framework=rspec
4
12
  class TaskGenerator < Rails::Generators::Base
13
+ # Supported test frameworks: the default directory for the tests (used
14
+ # when {DeployPin.tests_path} is not set) and the test file name, where
15
+ # `%<task>s` is the task file name without `.rb`.
16
+ TEST_FRAMEWORKS = {
17
+ rspec: { path: 'spec/deploy_pin', file: '%<task>s_spec.rb' }
18
+ }.freeze
19
+
20
+ # Printed when no test framework is configured and none is detected.
21
+ UNDETECTED_TEST_FRAMEWORK = 'test for the task: no test framework detected. ' \
22
+ 'Add rspec-rails to the :development group, or set DeployPin.test_framework :rspec'
23
+
5
24
  class_option :parallel, type: :boolean, aliases: '-p'
6
25
  class_option :recurring, type: :boolean, aliases: '-r'
7
26
  class_option :identifier, aliases: '-i'
8
27
  argument :title, required: true
9
28
  class_option :group, aliases: '-g', default: DeployPin.fallback_group
10
29
  class_option :author, aliases: '-a'
30
+ class_option :test_framework, type: :string,
31
+ desc: "Test framework for the task's test (default: DeployPin.test_framework)"
32
+ class_option :skip_test, type: :boolean, default: false, desc: 'Do not generate a test for the task'
11
33
 
12
34
  source_root File.expand_path('templates', __dir__)
13
35
 
@@ -19,6 +41,8 @@ module DeployPin
19
41
  validate
20
42
  end
21
43
 
44
+ # Writes the task file, named after its identifier and title.
45
+ # @return [void]
22
46
  def create_task_file
23
47
  template_file = if options[:parallel]
24
48
  'parallel_task.rb.erb'
@@ -30,16 +54,77 @@ module DeployPin
30
54
  @group = options[:group]
31
55
  @recurring = options[:recurring]
32
56
  @identifier = @recurring ? options[:identifier] : Time.now.strftime('%Y%m%d%H%M%S')
33
- filename = @recurring ? "r_#{@identifier}_#{title}.rb" : "#{@identifier}_#{title}.rb"
34
- template template_file, "#{DeployPin.tasks_path}/#{filename}"
57
+ template template_file, task_path
58
+ end
59
+
60
+ # Writes the test for the task, unless tests are turned off.
61
+ # @return [void]
62
+ def create_test_file
63
+ framework = test_framework
64
+ return if framework == false # turned off on purpose
65
+ return say_status(:skip, UNDETECTED_TEST_FRAMEWORK, :yellow) unless framework
66
+
67
+ template "#{framework}/task_spec.rb.erb", test_file_path(framework)
35
68
  end
36
69
 
70
+ # @return [void]
71
+ # @raise [Thor::Error] if the group is missing or not in {DeployPin.groups},
72
+ # or the test framework is not one of {TEST_FRAMEWORKS}
37
73
  def validate
38
74
  raise Thor::Error, set_color('Missing required option: --group', :red) if options[:group].blank?
39
75
 
40
- return if DeployPin.groups.include?(options[:group])
76
+ unless DeployPin.groups.include?(options[:group])
77
+ raise Thor::Error, set_color("Group '#{options[:group]}' is not defined in DeployPin.groups", :red)
78
+ end
41
79
 
42
- raise Thor::Error, set_color("Group '#{options[:group]}' is not defined in DeployPin.groups", :red)
80
+ validate_test_framework
43
81
  end
82
+
83
+ private
84
+
85
+ # The task file name without the extension, e.g. `20190401135040_backfill_users`.
86
+ def task_name
87
+ @recurring ? "r_#{@identifier}_#{title}" : "#{@identifier}_#{title}"
88
+ end
89
+
90
+ def task_path
91
+ "#{DeployPin.tasks_path}/#{task_name}.rb"
92
+ end
93
+
94
+ # The test file in {DeployPin.tests_path}, or in the framework's default directory.
95
+ def test_file_path(framework)
96
+ settings = TEST_FRAMEWORKS.fetch(framework)
97
+ directory = DeployPin.tests_path.presence || settings[:path]
98
+
99
+ File.join(directory.to_s, format(settings[:file], task: task_name))
100
+ end
101
+
102
+ # The --test-framework flag or DeployPin.test_framework, else the detected one.
103
+ #
104
+ # @return [Symbol, false, nil] the framework; false when tests are turned
105
+ # off (--skip-test, `test_framework false`); nil when none is detected
106
+ def test_framework
107
+ return false if options[:skip_test]
108
+
109
+ configured = options[:test_framework].presence || DeployPin.test_framework
110
+ return configured if configured == false
111
+
112
+ configured&.to_sym || detected_test_framework
113
+ end
114
+
115
+ # RSpec is the only supported framework, detected by its constant
116
+ # (no dependency on Rails' generator settings).
117
+ def detected_test_framework
118
+ :rspec if defined?(::RSpec)
119
+ end
120
+
121
+ def validate_test_framework
122
+ framework = test_framework
123
+ return if !framework || TEST_FRAMEWORKS.key?(framework)
124
+
125
+ raise Thor::Error, set_color(
126
+ "Unknown test framework '#{framework}'. Supported: #{TEST_FRAMEWORKS.keys.join(', ')}", :red
127
+ )
128
+ end
44
129
  end
45
130
  end
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'rails_helper'
4
+ require 'rake'
5
+
6
+ # Runs the task end to end, the same way a deploy does: `rake 'deploy_pin:run[<%= @identifier %>]'`.
7
+ RSpec.describe 'DeployPin task <%= task_name %>' do
8
+ subject(:run_task) { Rake::Task['deploy_pin:run'].invoke('<%= @identifier %>') }
9
+
10
+ before(:all) { Rails.application.load_tasks unless Rake::Task.task_defined?('deploy_pin:run') }
11
+
12
+ before do
13
+ Rake::Task['deploy_pin:run'].reenable
14
+ # A failing task must fail the spec, even if continue_on_error is enabled in this environment.
15
+ allow(DeployPin).to receive(:continue_on_error).and_return(false)
16
+ end
17
+
18
+ it 'runs without errors' do
19
+ expect { run_task }.not_to raise_error
20
+ end
21
+ <% unless @recurring -%>
22
+
23
+ it 'is marked as done' do
24
+ run_task
25
+
26
+ expect(DeployPin::Storage.record_class.find_by(uuid: <%= @identifier %>)&.completed_at).to be_present
27
+ end
28
+ <% end -%>
29
+
30
+ # Describe what the task changes, for example:
31
+ #
32
+ # it 'backfills user names' do
33
+ # user = User.create!(email: 'user@example.com', name: nil)
34
+ #
35
+ # expect { run_task }.to change { user.reload.name }.to('user@example.com')
36
+ # end
37
+ end