deploy_pin 1.10.0 → 2.0.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.
Files changed (30) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +77 -9
  3. data/Rakefile +16 -0
  4. data/exe/deploy_pin +8 -0
  5. data/lib/deploy_pin/cli.rb +83 -0
  6. data/lib/deploy_pin/database.rb +6 -1
  7. data/lib/deploy_pin/database_engine.rb +2 -2
  8. data/lib/deploy_pin/engine.rb +2 -1
  9. data/lib/deploy_pin/generators/base.rb +96 -0
  10. data/lib/deploy_pin/generators/install.rb +65 -0
  11. data/lib/deploy_pin/generators/rails_generator.rb +79 -0
  12. data/lib/deploy_pin/generators/task.rb +150 -0
  13. data/lib/{generators/deploy_pin/task/templates → deploy_pin/generators/templates/task}/rspec/task_spec.rb.erb +2 -2
  14. data/lib/deploy_pin/generators/upgrade.rb +23 -0
  15. data/lib/deploy_pin/generators.rb +6 -0
  16. data/lib/deploy_pin/runner.rb +15 -1
  17. data/lib/deploy_pin/storage.rb +11 -3
  18. data/lib/deploy_pin/version.rb +1 -1
  19. data/lib/deploy_pin.rb +62 -8
  20. data/lib/generators/deploy_pin/install/install_generator.rb +10 -2
  21. data/lib/generators/deploy_pin/task/USAGE +1 -1
  22. data/lib/generators/deploy_pin/task/task_generator.rb +8 -123
  23. data/lib/generators/deploy_pin/upgrade/upgrade_generator.rb +8 -1
  24. data/lib/tasks/deploy_pin_tasks.rake +39 -17
  25. metadata +117 -19
  26. /data/lib/{generators/deploy_pin/install/templates → deploy_pin/generators/templates/install}/create_deploy_pins.rb +0 -0
  27. /data/lib/{generators/deploy_pin/install/templates → deploy_pin/generators/templates/install}/deploy_pin.rb +0 -0
  28. /data/lib/{generators/deploy_pin/task/templates → deploy_pin/generators/templates/task}/parallel_task.rb.erb +0 -0
  29. /data/lib/{generators/deploy_pin/task/templates → deploy_pin/generators/templates/task}/task.rb.erb +0 -0
  30. /data/lib/{generators/deploy_pin/upgrade/templates → deploy_pin/generators/templates/upgrade}/upgrade_deploy_pins.rb +0 -0
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 8b82546e12b8efb37175c7f4715df4dca0e86f3d29f337d7b19e9bf975bec893
4
- data.tar.gz: 817165c4aafef54887c4881727a32000789ee05366d1b528d1a6ca7cda461023
3
+ metadata.gz: 4772a29d151064a13d50d0e40a6b5263c48040970859e5119c9bb423c8ed2a74
4
+ data.tar.gz: a86e02ea0bca94770aab2c3d4478c5e6d214523d6ab2f8f2d005876ada99f470
5
5
  SHA512:
6
- metadata.gz: 642d508e1428b5cfc71451b8f60dd198f2cd8fa6ff1e6c0f33bb66461e8ab5346fa8b1beb7bb1802fe3bf49b8518995762996fea38413b5826e54516bda11dfe
7
- data.tar.gz: 3b4c4686384e1cba64724c56ce3746a8f67e3c4964878299404c091e96b10123f1e75c2bb58fcd092c4a039e73908b8364e8335fd406beeba662692af4998e8a
6
+ metadata.gz: d355867c96cbc4cacff2dbd73b3f2f708e90ddfabc22c654b3136d5c9ae952ee5fc11e313166fc1e844af9066919d8f1a84233b317d9e6a30497e37bcbee5d54
7
+ data.tar.gz: bcd131e59e11667d34af414d4a268f99788a5532a731cf6065fb77b8b8105a26a2ac3dcbbebfbe9c8a244ccc516eff66e06f6e5dbebb030ef1ffea97da006c0a
data/README.md CHANGED
@@ -5,7 +5,7 @@
5
5
  [![CI](https://github.com/skcc321/deploy_pin/actions/workflows/verify.yml/badge.svg)](https://github.com/skcc321/deploy_pin/actions/workflows/verify.yml)
6
6
  [![Docs](https://img.shields.io/badge/docs-rubydoc.info-blue)](https://rubydoc.info/gems/deploy_pin)
7
7
  [![Ruby](https://img.shields.io/badge/ruby-%E2%89%A5%203.1-CC342D)](#requirements)
8
- [![Rails](https://img.shields.io/badge/rails-7.0%20%E2%80%93%208.x-CC0000)](#requirements)
8
+ [![Rails](https://img.shields.io/badge/rails-7.2%20%E2%80%93%208.x%20or%20none-CC0000)](#requirements)
9
9
  [![License: MIT](https://img.shields.io/badge/license-MIT-yellow.svg)](MIT-LICENSE)
10
10
 
11
11
  **Run one-off and recurring tasks around your deployments — data backfills, cache warm-ups, cleanups — in a defined order, exactly once, with database timeouts and resumable progress.**
@@ -17,6 +17,7 @@ Migrations are for schema changes. Everything else you need to run during a rele
17
17
  - [Features](#features)
18
18
  - [Requirements](#requirements)
19
19
  - [Installation](#installation)
20
+ - [Without Rails](#without-rails)
20
21
  - [Quick start](#quick-start)
21
22
  - [How it works](#how-it-works)
22
23
  - [Commands](#commands)
@@ -37,15 +38,16 @@ Migrations are for schema changes. Everything else you need to run during a rele
37
38
  - 🔁 **Resumable:** save progress so a long task continues where it stopped.
38
39
  - ♻️ **Recurring tasks:** tasks that run on every deploy.
39
40
  - 🚦 **Deployment state:** `DeployPin.ongoing_deployment?` lets your app behave differently while a deploy is in progress.
40
- - 🍃 **ActiveRecord or Mongoid** storage.
41
+ - 🍃 **ActiveRecord or Mongoid** storage, or a record class of your own.
42
+ - 🧩 **Rails or plain Ruby:** a Rails engine and `rails g` generators, or the `deploy_pin` command and `DeployPin.load_tasks` in any other Ruby app (Sinatra, Hanami, Roda, scripts…).
41
43
 
42
44
  ## Requirements
43
45
 
44
46
  | | |
45
47
  |---|---|
46
48
  | Ruby | ≥ 3.1 (CI runs 3.3, 3.4 and 4.0) |
47
- | Rails | ≥ 7.0, < 9 (CI runs 8.1) |
48
- | Storage | ActiveRecord (PostgreSQL, MySQL, MariaDB, …) or Mongoid |
49
+ | Rails | Optional. ≥ 7.2, < 9 (CI runs 7.2 and 8.1). Without Rails, ActiveSupport ≥ 7.2 is used. For Rails 7.0 and 7.1, use deploy_pin 1.10 |
50
+ | Storage | ActiveRecord (PostgreSQL, MySQL, MariaDB, …), Mongoid, or your own record class |
49
51
  | Redis | Only for [deployment state](#deployment-state) |
50
52
 
51
53
  Statement timeouts need ActiveRecord with PostgreSQL, MySQL or MariaDB. With other setups, tasks run without a timeout.
@@ -91,6 +93,53 @@ DeployPin.setup do
91
93
  end
92
94
  ```
93
95
 
96
+ ### Without Rails
97
+
98
+ DeployPin works in any Ruby app. Add it together with a storage gem and your database adapter, for example ActiveRecord with SQLite (use `pg` or `mysql2` for other databases, or `mongoid` instead of `activerecord`):
99
+
100
+ ```bash
101
+ bundle add deploy_pin activerecord sqlite3
102
+ ```
103
+
104
+ The `deploy_pin` command runs the same generators as `rails g deploy_pin:*`. Create `config/deploy_pin.rb` and the `deploy_pins` migration (with `--storage=mongoid`, only the configuration):
105
+
106
+ ```bash
107
+ bundle exec deploy_pin install # --config-path and --migrations-path change where the files go
108
+ ```
109
+
110
+ The generated configuration turns on [deployment state](#deployment-state), which needs Redis. Remove `deployment_state_transition` from it if you don't use Redis.
111
+
112
+ Then add the rake tasks to your `Rakefile`. They run your `environment` task first, so define one that loads your app, connects to the database and loads `config/deploy_pin.rb`. Run the migration with your migration tool:
113
+
114
+ ```ruby
115
+ # Rakefile
116
+ require 'deploy_pin'
117
+ DeployPin.load_tasks
118
+
119
+ task :environment do
120
+ require_relative 'config/environment'
121
+ end
122
+ ```
123
+
124
+ ```ruby
125
+ # config/environment.rb
126
+ require 'active_record'
127
+ require 'deploy_pin'
128
+ ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: 'db/app.sqlite3')
129
+ require_relative 'deploy_pin'
130
+ ```
131
+
132
+ Without an `environment` task, the rake tasks only load `config/deploy_pin.rb`.
133
+
134
+ Generate tasks with `deploy_pin task`. It loads `config/deploy_pin.rb` first, or the files given with `--require`. Then run them with rake:
135
+
136
+ ```bash
137
+ bundle exec deploy_pin task backfill_user_names -g I --require config/environment.rb
138
+ bundle exec rake deploy_pin:run
139
+ ```
140
+
141
+ The rest of this README uses the Rails commands. Replace `rails g deploy_pin:<command>` with `deploy_pin <command>`, and `config/initializers/deploy_pin.rb` with `config/deploy_pin.rb`. [`bin/smoke_test_gem`](bin/smoke_test_gem) runs these steps on CI.
142
+
94
143
  ## Quick start
95
144
 
96
145
  ```bash
@@ -169,6 +218,7 @@ rake 'deploy_pin:run[I, !20190401135040]' # group I except one task
169
218
  | Command | Description |
170
219
  |---|---|
171
220
  | `rails g deploy_pin:task <title> -g <group>` | Generate a task and its [test](#testing-tasks). Options: `--parallel`, `--recurring --identifier <n>`, `-a <author>`, `--skip-test`, `--test-framework=rspec` |
221
+ | `deploy_pin install`, `deploy_pin task <title> -g <group>`, `deploy_pin upgrade` | The generators, [without Rails](#without-rails). `--require <file>` loads files first |
172
222
  | `rake deploy_pin:list[...]` | List pending tasks, including their code |
173
223
  | `rake deploy_pin:short_list[...]` | List pending tasks by group, without the code |
174
224
  | `rake deploy_pin:run[...]` | Run pending tasks |
@@ -401,6 +451,8 @@ Task records are kept by a storage provider, set with `storage`:
401
451
  | `:active_record` (default) | `DeployPin::Record` | `deploy_pins` table |
402
452
  | `:mongoid` | `DeployPin::MongoidRecord` | `deploy_pins` collection |
403
453
 
454
+ You can also set `storage` to a class of your own, for example a Sequel or ROM model. It must respond to `.find_by(uuid:)` and `.create(uuid:)`, and its records to `#progress`, `#completed_at`, `#update(attributes)` and `#increment!(attribute, by)`. See the [`DeployPin::Storage` docs](https://rubydoc.info/gems/deploy_pin/DeployPin/Storage).
455
+
404
456
  `DeployPin::Storage.record_class` returns the model of the configured provider. Statement timeouts and the parallel timeout rely on ActiveRecord. Without it, tasks run without a timeout.
405
457
 
406
458
  ### Testing tasks
@@ -424,6 +476,8 @@ end
424
476
 
425
477
  The spec turns off `continue_on_error`, so a failing task always fails its spec.
426
478
 
479
+ The spec requires `rails_helper` in a Rails app, and `spec_helper` otherwise, so make sure that helper loads your app.
480
+
427
481
  RSpec is the only supported framework for now. It is detected automatically when the `RSpec` constant is loaded, which is the case when `rspec-rails` is in the `:development` group, as rspec-rails recommends. If nothing is detected, the generator skips the test and says so. Set the framework and the directory, or turn test generation off, in the initializer:
428
482
 
429
483
  ```ruby
@@ -487,7 +541,7 @@ All options are set in `DeployPin.setup`. See the [API docs](https://rubydoc.inf
487
541
  | `groups` | — | Ordered list of groups |
488
542
  | `fallback_group` | — | Group for `deploy_pin:task` when `-g` is not given |
489
543
  | `statement_timeout` | — | Default database statement timeout |
490
- | `storage` | `:active_record` | `:active_record` or `:mongoid` |
544
+ | `storage` | `:active_record` | `:active_record`, `:mongoid`, or a record class |
491
545
  | `continue_on_error` | `false` | Log failed tasks and continue instead of stopping |
492
546
  | `test_framework` | detected (`:rspec` if `RSpec` is loaded) | Test framework for generated task tests; `false` to skip them. See [Testing tasks](#testing-tasks) |
493
547
  | `tests_path` | `'spec/deploy_pin'` | Directory for generated task tests |
@@ -506,15 +560,29 @@ bundle install
506
560
  # Start the databases (credentials come from .env)
507
561
  docker compose up -d
508
562
  set -a; source .env; set +a
509
- export RAILS_ENV=test
563
+ export APP_ENV=test RAILS_ENV=test
510
564
  ```
511
565
 
512
- Run the tests against one database at a time. `DB_ROLE` is `pg`, `mysql`, `mariadb` or `mongodb`:
566
+ There are two test suites, and CI runs both:
567
+
568
+ - `bin/test` runs DeployPin in a plain Ruby app, [`test/dummy`](test/dummy), without Rails: the library, the `deploy_pin` command, the rake tasks and the generated specs.
569
+ - `bin/test rails` runs it in a Rails app, [`test/rails/dummy`](test/rails/dummy): the engine, `rails g deploy_pin:*`, `bin/rails deploy_pin:run` and the generated specs.
570
+
571
+ Run them against one database at a time. `DB_ROLE` is `pg`, `mysql`, `mariadb` or `mongodb`:
513
572
 
514
573
  ```bash
515
- DB_ROLE=pg bin/rails db:prepare # not needed for mongodb
574
+ DB_ROLE=pg bundle exec rake db:prepare # not needed for mongodb
575
+ DB_ROLE=pg bin/rails db:prepare # the Rails app shares the database
516
576
  DB_ROLE=pg bin/test
517
- DB_ROLE=pg bin/test test/lib/deploy_pin/task_test.rb # a single file
577
+ DB_ROLE=pg bin/test rails
578
+ DB_ROLE=pg bin/test test/lib/deploy_pin/task_test.rb -n /parse/ # a single file
579
+ ```
580
+
581
+ `Gemfile.lock` uses Rails 8.1. To run against Rails 7.2, use its gemfile from [`gemfiles/`](gemfiles):
582
+
583
+ ```bash
584
+ BUNDLE_GEMFILE=gemfiles/rails_7_2.gemfile bundle install
585
+ BUNDLE_GEMFILE=gemfiles/rails_7_2.gemfile DB_ROLE=pg bin/test rails
518
586
  ```
519
587
 
520
588
  Linting and docs, also checked on CI:
data/Rakefile CHANGED
@@ -5,6 +5,22 @@ require 'bundler/setup'
5
5
  require 'bundler/gem_tasks'
6
6
  require 'yard'
7
7
 
8
+ # db:prepare and the deploy_pin:* tasks of the plain Ruby app in test/dummy
8
9
  import 'test/dummy/Rakefile'
9
10
 
10
11
  YARD::Rake::YardocTask.new(:yard)
12
+
13
+ desc 'Run the plain Ruby test suite (test/dummy)'
14
+ task :test do
15
+ sh 'bin/test'
16
+ end
17
+
18
+ namespace :test do
19
+ desc 'Run the Rails test suite (test/rails/dummy)'
20
+ task :rails do
21
+ sh 'bin/test rails'
22
+ end
23
+
24
+ desc 'Run both test suites'
25
+ task all: %i[test test:rails]
26
+ end
data/exe/deploy_pin ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ # Generators for DeployPin tasks, the configuration and the migrations.
5
+ # Run `deploy_pin help` for the commands.
6
+ require 'deploy_pin/cli'
7
+
8
+ DeployPin::CLI.start(ARGV)
@@ -0,0 +1,83 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'thor'
4
+ require 'deploy_pin'
5
+ require 'deploy_pin/generators'
6
+
7
+ module DeployPin
8
+ # The `deploy_pin` command: the generators for any Ruby app. In a Rails
9
+ # app, `rails g deploy_pin:*` runs the same generators.
10
+ #
11
+ # Before a command runs, the configuration is loaded with
12
+ # {DeployPin.load_config}: the files given with `--require`, else
13
+ # `config/deploy_pin.rb` (or `config/initializers/deploy_pin.rb`).
14
+ #
15
+ # @example
16
+ # deploy_pin install
17
+ # deploy_pin task backfill_user_names -g I
18
+ # deploy_pin task backfill_user_names -g I --require config/environment.rb
19
+ class CLI < Thor
20
+ # Option that loads files before the command, e.g. `--require config/environment.rb`.
21
+ REQUIRE_OPTION = '--require'
22
+ # Commands that run without loading the configuration.
23
+ NO_CONFIG_COMMANDS = %w[help -h --help version].freeze
24
+
25
+ package_name 'deploy_pin'
26
+
27
+ # @return [Boolean] true, so errors exit with a non-zero status
28
+ def self.exit_on_failure?
29
+ true
30
+ end
31
+
32
+ # Loads the configuration, then runs the command.
33
+ #
34
+ # @param given_args [Array<String>] command line arguments
35
+ # @param config [Hash] Thor configuration
36
+ # @return [void]
37
+ def self.start(given_args = ARGV, config = {})
38
+ args = given_args.dup
39
+ files = extract_required_files!(args)
40
+ begin
41
+ DeployPin.load_config(files) unless args.empty? || NO_CONFIG_COMMANDS.include?(args.first)
42
+ rescue ArgumentError => e
43
+ (config[:shell] || Thor::Base.shell.new).error(set_color(e.message, :red))
44
+ exit(1)
45
+ end
46
+
47
+ super(args, config)
48
+ end
49
+
50
+ # Removes every `--require FILE` (or `--require=FILE`) from the arguments.
51
+ #
52
+ # @param args [Array<String>] command line arguments, changed in place
53
+ # @return [Array<String>] the files
54
+ def self.extract_required_files!(args)
55
+ files = []
56
+ while (index = args.index { |arg| arg == REQUIRE_OPTION || arg.start_with?("#{REQUIRE_OPTION}=") })
57
+ option = args.delete_at(index)
58
+ files << (option.include?('=') ? option.split('=', 2).last : args.delete_at(index))
59
+ end
60
+ files.compact
61
+ end
62
+
63
+ # Colors a message like Thor's shell does.
64
+ # @return [String]
65
+ def self.set_color(...)
66
+ Thor::Base.shell.new.set_color(...)
67
+ end
68
+
69
+ register Generators::Install, 'install', 'install [--storage=mongoid]',
70
+ 'Create config/deploy_pin.rb and, for ActiveRecord, the deploy_pins migration'
71
+ register Generators::Task, 'task', 'task TITLE -g GROUP [--require config/environment.rb]',
72
+ 'Create a task in DeployPin.tasks_path, and a test for it'
73
+ register Generators::Upgrade, 'upgrade', 'upgrade',
74
+ 'Create the migration that upgrades the deploy_pins table'
75
+
76
+ desc 'version', 'Print the DeployPin version'
77
+ # Prints the DeployPin version.
78
+ # @return [void]
79
+ def version
80
+ puts DeployPin::VERSION
81
+ end
82
+ end
83
+ end
@@ -47,7 +47,7 @@ module DeployPin
47
47
 
48
48
  return call_block_under_timeout(timeout, &blk) unless params.key? :connected_to
49
49
 
50
- klass = params[:connected_to].key?(:database) ? ActiveRecord::Base : ::ApplicationRecord
50
+ klass = params[:connected_to].key?(:database) ? ActiveRecord::Base : application_record
51
51
  klass.connected_to(**params[:connected_to]) do
52
52
  call_block_under_timeout(timeout, &blk)
53
53
  end
@@ -85,6 +85,11 @@ module DeployPin
85
85
  'running without a timeout.'
86
86
  end
87
87
 
88
+ # The app's ApplicationRecord, which holds `connects_to` in Rails apps, or ActiveRecord::Base.
89
+ def application_record
90
+ defined?(::ApplicationRecord) ? ::ApplicationRecord : ActiveRecord::Base
91
+ end
92
+
88
93
  def db_engine
89
94
  @db_engine ||= DeployPin::DatabaseEngine.new(connection).detect
90
95
  end
@@ -18,8 +18,8 @@ module DeployPin
18
18
 
19
19
  # MariaDB settings.
20
20
  module MariaDB
21
- # SQL that sets the timeout, in milliseconds.
22
- TIMEOUT_STATEMENT = 'SET SESSION max_statement_time = %s'
21
+ # SQL that sets the timeout, in milliseconds: `max_statement_time` is in seconds.
22
+ TIMEOUT_STATEMENT = 'SET SESSION max_statement_time = %s / 1000'
23
23
  end
24
24
 
25
25
  # Engine modules by key.
@@ -1,7 +1,8 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module DeployPin
4
- # Rails engine that loads the `deploy_pin:*` rake tasks.
4
+ # Rails engine that loads the `deploy_pin:*` rake tasks. It is only loaded
5
+ # in Rails apps; other apps call {DeployPin.load_tasks} from their Rakefile.
5
6
  class Engine < ::Rails::Engine
6
7
  isolate_namespace DeployPin
7
8
 
@@ -0,0 +1,96 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'thor'
4
+ require 'deploy_pin'
5
+
6
+ module DeployPin
7
+ # Generators for task files, the configuration file and the migrations.
8
+ # They are plain Thor groups, so they run in any Ruby app through the
9
+ # `deploy_pin` command ({CLI}), and in Rails apps through `rails g deploy_pin:*`
10
+ # ({RailsGenerator}).
11
+ module Generators
12
+ # Base class of the DeployPin generators.
13
+ class Base < Thor::Group
14
+ include Thor::Actions
15
+
16
+ # Directory of the generator templates, one subdirectory per generator.
17
+ TEMPLATES_ROOT = File.expand_path('templates', __dir__)
18
+
19
+ add_runtime_options!
20
+
21
+ # @return [Boolean] true, so `deploy_pin` exits with a non-zero status on errors
22
+ def self.exit_on_failure?
23
+ true
24
+ end
25
+
26
+ # Sets the templates directory of a generator.
27
+ #
28
+ # @param name [String] subdirectory of {TEMPLATES_ROOT}
29
+ # @return [void]
30
+ def self.templates(name)
31
+ source_root File.join(TEMPLATES_ROOT, name)
32
+ end
33
+
34
+ protected
35
+
36
+ # Renders a migration template to `<migrations_path>/<timestamp>_<name>.rb`,
37
+ # like `migration_template` of Rails generators. On `revoke` (destroy),
38
+ # removes the existing migration instead.
39
+ #
40
+ # @param source [String] the template
41
+ # @param name [String] the migration name, e.g. `create_deploy_pins`
42
+ # @return [void]
43
+ # @raise [Thor::Error] if a migration with that name exists, unless --force or --skip
44
+ def migration_template(source, name)
45
+ existing = existing_migration(name)
46
+ return delete_migration(existing) if behavior == :revoke
47
+ return if existing && !replace_migration?(existing, name)
48
+
49
+ template source, File.join(migrations_path, "#{next_migration_number}_#{name}.rb")
50
+ end
51
+
52
+ # @return [String] the migrations directory, relative to the destination root
53
+ def migrations_path
54
+ options[:migrations_path].presence || 'db/migrate'
55
+ end
56
+
57
+ private
58
+
59
+ # @return [String, nil] the migration path, relative to the destination root
60
+ def existing_migration(name)
61
+ path = Dir.glob(File.join(destination_root, migrations_path, "*_#{name}.rb")).first
62
+ path&.delete_prefix("#{destination_root}/")
63
+ end
64
+
65
+ def replace_migration?(existing, name)
66
+ if options[:skip]
67
+ say_status :skip, existing, :yellow
68
+ return false
69
+ end
70
+ if options[:force]
71
+ delete_migration(existing)
72
+ return true
73
+ end
74
+
75
+ raise Thor::Error, set_color("Another migration is already named #{name}: #{existing}. " \
76
+ 'Use --force to replace it or --skip to ignore it.', :red)
77
+ end
78
+
79
+ # Thor's remove_file only works on invoke, so this one removes on revoke too.
80
+ def delete_migration(path)
81
+ return unless path
82
+
83
+ say_status :remove, path, :red
84
+ FileUtils.rm_f(File.join(destination_root, path)) unless options[:pretend]
85
+ end
86
+
87
+ # A UTC timestamp, later than every existing migration.
88
+ def next_migration_number
89
+ numbers = Dir.glob(File.join(destination_root, migrations_path, '*.rb')).map do |path|
90
+ File.basename(path)[/\A\d+/].to_i
91
+ end
92
+ [Time.now.utc.strftime('%Y%m%d%H%M%S'), format('%.14d', (numbers.max || 0) + 1)].max
93
+ end
94
+ end
95
+ end
96
+ end
@@ -0,0 +1,65 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'deploy_pin/generators/base'
4
+
5
+ module DeployPin
6
+ module Generators
7
+ # `deploy_pin install [--storage=mongoid]`: creates the configuration file
8
+ # and, for ActiveRecord, the `deploy_pins` migration.
9
+ class Install < Base
10
+ templates 'install'
11
+ desc 'Creates the DeployPin configuration file and, for ActiveRecord, the deploy_pins migration'
12
+
13
+ class_option :storage, type: :string, default: 'active_record', enum: %w[active_record mongoid],
14
+ desc: 'Storage provider for task records'
15
+ class_option :config_path, type: :string, default: 'config/deploy_pin.rb',
16
+ desc: 'Where to create the configuration file'
17
+ class_option :migrations_path, type: :string, default: 'db/migrate',
18
+ desc: 'Directory of the ActiveRecord migrations'
19
+
20
+ # Creates the `deploy_pins` migration, unless the storage is Mongoid.
21
+ # @return [void]
22
+ def copy_migrations
23
+ return if mongoid?
24
+
25
+ # Fail before writing any file: Thor creates the file before rendering the template.
26
+ @activerecord_migration_class = activerecord_migration_class
27
+ migration_template 'create_deploy_pins.rb', 'create_deploy_pins'
28
+ end
29
+
30
+ # Creates the configuration file: `config/deploy_pin.rb`, or
31
+ # `config/initializers/deploy_pin.rb` in a Rails app.
32
+ # @return [void]
33
+ def copy_initializer
34
+ template 'deploy_pin.rb', options[:config_path]
35
+ end
36
+
37
+ # Reminds Mongoid users to create the indexes.
38
+ # @return [void]
39
+ def mongoid_indexes_hint
40
+ return unless mongoid? && behavior == :invoke
41
+
42
+ say 'Create the DeployPin indexes: `rails db:mongoid:create_indexes` in a Rails app, ' \
43
+ 'or `DeployPin::MongoidRecord.create_indexes`.'
44
+ end
45
+
46
+ private
47
+
48
+ # Used by the migration template.
49
+ # @raise [Thor::Error] if ActiveRecord is not installed
50
+ def activerecord_migration_class
51
+ return @activerecord_migration_class if @activerecord_migration_class
52
+
53
+ require 'active_record/version'
54
+ "ActiveRecord::Migration[#{::ActiveRecord::VERSION::STRING.to_f}]"
55
+ rescue LoadError
56
+ raise Thor::Error, set_color('ActiveRecord storage needs the activerecord gem. ' \
57
+ 'Add it to your Gemfile, or use --storage=mongoid.', :red)
58
+ end
59
+
60
+ def mongoid?
61
+ options[:storage] == 'mongoid'
62
+ end
63
+ end
64
+ end
65
+ end
@@ -0,0 +1,79 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'deploy_pin/generators'
4
+
5
+ module DeployPin
6
+ module Generators
7
+ # Runs a DeployPin generator as a Rails generator (`rails g deploy_pin:*`).
8
+ # The Rails generator gets the arguments and options of the DeployPin
9
+ # generator, so both take the same command line.
10
+ #
11
+ # @example
12
+ # class TaskGenerator < Rails::Generators::Base
13
+ # include DeployPin::Generators::RailsGenerator
14
+ # runs DeployPin::Generators::Task
15
+ # end
16
+ module RailsGenerator
17
+ # Settings of Thor arguments and options that are copied to the Rails generator.
18
+ SETTINGS = %i[type default desc banner enum required aliases hide lazy_default repeatable].freeze
19
+
20
+ # @param base [Class] a `Rails::Generators::Base` subclass
21
+ # @return [void]
22
+ def self.included(base)
23
+ base.extend(ClassMethods)
24
+ end
25
+
26
+ # Class methods of the Rails generator.
27
+ module ClassMethods
28
+ # Sets the DeployPin generator to run, and copies its arguments and
29
+ # options. Options the Rails generator already has (e.g. --force) are kept.
30
+ #
31
+ # @param generator [Class, nil] a {Generators::Base} subclass; omit to read it
32
+ # @param defaults [Hash{Symbol => Object}] option defaults that differ in Rails apps
33
+ # @return [Class] the DeployPin generator
34
+ def runs(generator = nil, **defaults)
35
+ return @runs if generator.nil?
36
+
37
+ @runs = generator
38
+ generator.arguments.each { |arg| argument(arg.name.to_sym, **thor_settings(arg)) }
39
+ copy_class_options(generator, defaults)
40
+ # Thor only runs the public methods defined in the generator class itself.
41
+ define_method(:run_deploy_pin) { run_deploy_pin_generator }
42
+ generator
43
+ end
44
+
45
+ private
46
+
47
+ def copy_class_options(generator, defaults)
48
+ generator.class_options.each_value do |option|
49
+ name = option.name.to_sym
50
+ next if class_options.key?(name)
51
+
52
+ overrides = defaults.key?(name) ? { default: defaults[name] } : {}
53
+ class_option(name, **thor_settings(option), **overrides)
54
+ end
55
+ end
56
+
57
+ def thor_settings(thor_argument)
58
+ SETTINGS.each_with_object({}) do |key, settings|
59
+ method = key == :desc ? :description : key
60
+ next unless thor_argument.respond_to?(method)
61
+
62
+ value = thor_argument.public_send(method)
63
+ settings[key] = value unless value.nil? || value == []
64
+ end
65
+ end
66
+ end
67
+
68
+ # Runs the DeployPin generator with this generator's arguments, options,
69
+ # shell, destination and behavior (`rails generate` or `rails destroy`).
70
+ # @return [void]
71
+ def run_deploy_pin_generator
72
+ values = self.class.arguments.map { |arg| public_send(arg.name) }
73
+ config = { destination_root:, shell:, behavior: }
74
+
75
+ self.class.runs.new(values, options, config).invoke_all
76
+ end
77
+ end
78
+ end
79
+ end