From 76c79acbf80635e412aea38e38684c30463dbbca Mon Sep 17 00:00:00 2001 From: Theodor Tonum Date: Sun, 25 Feb 2024 13:13:28 +0100 Subject: [PATCH] initial commit --- .gitignore | 10 + Appraisals | 3 + Gemfile | 16 ++ Gemfile.lock | 258 ++++++++++++++++++ Guardfile | 42 +++ LICENSE.md | 20 ++ README.md | 63 +++++ Rakefile | 3 + bin/test | 5 + bin/veksel | 7 + docker-compose.yml | 9 + gemfiles/rails_6.gemfile | 12 + gemfiles/rails_6.gemfile.lock | 223 +++++++++++++++ lib/tasks/veksel_tasks.rake | 69 +++++ lib/veksel.rb | 29 ++ lib/veksel/commands/clean.rb | 33 +++ lib/veksel/commands/fork.rb | 24 ++ lib/veksel/pg_cluster.rb | 60 ++++ lib/veksel/railtie.rb | 7 + lib/veksel/suffix.rb | 18 ++ lib/veksel/version.rb | 3 + test/dummy/Rakefile | 6 + test/dummy/app/assets/images/.keep | 0 .../app/assets/stylesheets/application.css | 1 + .../app/channels/application_cable/channel.rb | 4 + .../channels/application_cable/connection.rb | 4 + .../app/controllers/application_controller.rb | 2 + test/dummy/app/controllers/concerns/.keep | 0 test/dummy/app/helpers/application_helper.rb | 2 + test/dummy/app/jobs/application_job.rb | 7 + test/dummy/app/mailers/application_mailer.rb | 4 + test/dummy/app/models/application_record.rb | 5 + test/dummy/app/models/concerns/.keep | 0 .../app/views/layouts/application.html.erb | 15 + test/dummy/app/views/layouts/mailer.html.erb | 13 + test/dummy/app/views/layouts/mailer.text.erb | 1 + test/dummy/bin/rails | 4 + test/dummy/bin/rake | 4 + test/dummy/bin/setup | 33 +++ test/dummy/config.ru | 6 + test/dummy/config/application.rb | 40 +++ test/dummy/config/boot.rb | 5 + test/dummy/config/cable.yml | 10 + test/dummy/config/database.yml | 23 ++ test/dummy/config/environment.rb | 5 + test/dummy/config/environments/development.rb | 74 +++++ test/dummy/config/environments/production.rb | 91 ++++++ test/dummy/config/environments/test.rb | 64 +++++ .../initializers/content_security_policy.rb | 25 ++ .../initializers/filter_parameter_logging.rb | 8 + test/dummy/config/initializers/inflections.rb | 16 ++ .../config/initializers/permissions_policy.rb | 13 + test/dummy/config/locales/en.yml | 31 +++ test/dummy/config/puma.rb | 35 +++ test/dummy/config/routes.rb | 10 + test/dummy/config/storage.yml | 34 +++ test/dummy/db/schema.rb | 24 ++ test/dummy/lib/assets/.keep | 0 test/dummy/log/.keep | 0 test/dummy/public/404.html | 67 +++++ test/dummy/public/422.html | 67 +++++ test/dummy/public/500.html | 66 +++++ .../public/apple-touch-icon-precomposed.png | 0 test/dummy/public/apple-touch-icon.png | 0 test/dummy/public/favicon.ico | 0 test/test_helper.rb | 21 ++ test/veksel_test.rb | 66 +++++ veksel.gemspec | 30 ++ 68 files changed, 1850 insertions(+) create mode 100644 .gitignore create mode 100644 Appraisals create mode 100644 Gemfile create mode 100644 Gemfile.lock create mode 100644 Guardfile create mode 100644 LICENSE.md create mode 100644 README.md create mode 100644 Rakefile create mode 100755 bin/test create mode 100755 bin/veksel create mode 100644 docker-compose.yml create mode 100644 gemfiles/rails_6.gemfile create mode 100644 gemfiles/rails_6.gemfile.lock create mode 100644 lib/tasks/veksel_tasks.rake create mode 100644 lib/veksel.rb create mode 100644 lib/veksel/commands/clean.rb create mode 100644 lib/veksel/commands/fork.rb create mode 100644 lib/veksel/pg_cluster.rb create mode 100644 lib/veksel/railtie.rb create mode 100644 lib/veksel/suffix.rb create mode 100644 lib/veksel/version.rb create mode 100644 test/dummy/Rakefile create mode 100644 test/dummy/app/assets/images/.keep create mode 100644 test/dummy/app/assets/stylesheets/application.css create mode 100644 test/dummy/app/channels/application_cable/channel.rb create mode 100644 test/dummy/app/channels/application_cable/connection.rb create mode 100644 test/dummy/app/controllers/application_controller.rb create mode 100644 test/dummy/app/controllers/concerns/.keep create mode 100644 test/dummy/app/helpers/application_helper.rb create mode 100644 test/dummy/app/jobs/application_job.rb create mode 100644 test/dummy/app/mailers/application_mailer.rb create mode 100644 test/dummy/app/models/application_record.rb create mode 100644 test/dummy/app/models/concerns/.keep create mode 100644 test/dummy/app/views/layouts/application.html.erb create mode 100644 test/dummy/app/views/layouts/mailer.html.erb create mode 100644 test/dummy/app/views/layouts/mailer.text.erb create mode 100755 test/dummy/bin/rails create mode 100755 test/dummy/bin/rake create mode 100755 test/dummy/bin/setup create mode 100644 test/dummy/config.ru create mode 100644 test/dummy/config/application.rb create mode 100644 test/dummy/config/boot.rb create mode 100644 test/dummy/config/cable.yml create mode 100644 test/dummy/config/database.yml create mode 100644 test/dummy/config/environment.rb create mode 100644 test/dummy/config/environments/development.rb create mode 100644 test/dummy/config/environments/production.rb create mode 100644 test/dummy/config/environments/test.rb create mode 100644 test/dummy/config/initializers/content_security_policy.rb create mode 100644 test/dummy/config/initializers/filter_parameter_logging.rb create mode 100644 test/dummy/config/initializers/inflections.rb create mode 100644 test/dummy/config/initializers/permissions_policy.rb create mode 100644 test/dummy/config/locales/en.yml create mode 100644 test/dummy/config/puma.rb create mode 100644 test/dummy/config/routes.rb create mode 100644 test/dummy/config/storage.yml create mode 100644 test/dummy/db/schema.rb create mode 100644 test/dummy/lib/assets/.keep create mode 100644 test/dummy/log/.keep create mode 100644 test/dummy/public/404.html create mode 100644 test/dummy/public/422.html create mode 100644 test/dummy/public/500.html create mode 100644 test/dummy/public/apple-touch-icon-precomposed.png create mode 100644 test/dummy/public/apple-touch-icon.png create mode 100644 test/dummy/public/favicon.ico create mode 100644 test/test_helper.rb create mode 100644 test/veksel_test.rb create mode 100644 veksel.gemspec diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a3ee5aa --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +/.bundle/ +/doc/ +/log/*.log +/pkg/ +/tmp/ +/test/dummy/db/*.sqlite3 +/test/dummy/db/*.sqlite3-* +/test/dummy/log/*.log +/test/dummy/storage/ +/test/dummy/tmp/ diff --git a/Appraisals b/Appraisals new file mode 100644 index 0000000..bd8bc85 --- /dev/null +++ b/Appraisals @@ -0,0 +1,3 @@ +appraise "rails-6" do + gem "rails", "~> 6" +end diff --git a/Gemfile b/Gemfile new file mode 100644 index 0000000..a0ce7ee --- /dev/null +++ b/Gemfile @@ -0,0 +1,16 @@ +source "https://rubygems.org" +git_source(:github) { |repo| "https://github.com/#{repo}.git" } + +# Specify your gem's dependencies in veksel.gemspec. +gemspec + +gem "puma" + +gem "sqlite3" +gem "pg" + +# Start debugger with binding.b [https://github.com/ruby/debug] +# gem "debug", ">= 1.0.0" + +gem "guard", "~> 2.18" +gem "guard-minitest", "~> 2.4" diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 0000000..2012f1e --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,258 @@ +PATH + remote: . + specs: + veksel (0.1.0) + activerecord + pg + rails (>= 6, < 8) + +GEM + remote: https://rubygems.org/ + specs: + actioncable (7.1.3.2) + actionpack (= 7.1.3.2) + activesupport (= 7.1.3.2) + nio4r (~> 2.0) + websocket-driver (>= 0.6.1) + zeitwerk (~> 2.6) + actionmailbox (7.1.3.2) + actionpack (= 7.1.3.2) + activejob (= 7.1.3.2) + activerecord (= 7.1.3.2) + activestorage (= 7.1.3.2) + activesupport (= 7.1.3.2) + mail (>= 2.7.1) + net-imap + net-pop + net-smtp + actionmailer (7.1.3.2) + actionpack (= 7.1.3.2) + actionview (= 7.1.3.2) + activejob (= 7.1.3.2) + activesupport (= 7.1.3.2) + mail (~> 2.5, >= 2.5.4) + net-imap + net-pop + net-smtp + rails-dom-testing (~> 2.2) + actionpack (7.1.3.2) + actionview (= 7.1.3.2) + activesupport (= 7.1.3.2) + nokogiri (>= 1.8.5) + racc + rack (>= 2.2.4) + rack-session (>= 1.0.1) + rack-test (>= 0.6.3) + rails-dom-testing (~> 2.2) + rails-html-sanitizer (~> 1.6) + actiontext (7.1.3.2) + actionpack (= 7.1.3.2) + activerecord (= 7.1.3.2) + activestorage (= 7.1.3.2) + activesupport (= 7.1.3.2) + globalid (>= 0.6.0) + nokogiri (>= 1.8.5) + actionview (7.1.3.2) + activesupport (= 7.1.3.2) + builder (~> 3.1) + erubi (~> 1.11) + rails-dom-testing (~> 2.2) + rails-html-sanitizer (~> 1.6) + activejob (7.1.3.2) + activesupport (= 7.1.3.2) + globalid (>= 0.3.6) + activemodel (7.1.3.2) + activesupport (= 7.1.3.2) + activerecord (7.1.3.2) + activemodel (= 7.1.3.2) + activesupport (= 7.1.3.2) + timeout (>= 0.4.0) + activestorage (7.1.3.2) + actionpack (= 7.1.3.2) + activejob (= 7.1.3.2) + activerecord (= 7.1.3.2) + activesupport (= 7.1.3.2) + marcel (~> 1.0) + activesupport (7.1.3.2) + base64 + bigdecimal + concurrent-ruby (~> 1.0, >= 1.0.2) + connection_pool (>= 2.2.5) + drb + i18n (>= 1.6, < 2) + minitest (>= 5.1) + mutex_m + tzinfo (~> 2.0) + appraisal (2.5.0) + bundler + rake + thor (>= 0.14.0) + base64 (0.2.0) + bigdecimal (3.1.6) + builder (3.2.4) + coderay (1.1.3) + concurrent-ruby (1.2.3) + connection_pool (2.4.1) + crass (1.0.6) + date (3.3.4) + drb (2.2.0) + ruby2_keywords + erubi (1.12.0) + ffi (1.16.3) + formatador (1.1.0) + globalid (1.2.1) + activesupport (>= 6.1) + guard (2.18.1) + formatador (>= 0.2.4) + listen (>= 2.7, < 4.0) + lumberjack (>= 1.0.12, < 2.0) + nenv (~> 0.1) + notiffany (~> 0.0) + pry (>= 0.13.0) + shellany (~> 0.0) + thor (>= 0.18.1) + guard-compat (1.2.1) + guard-minitest (2.4.6) + guard-compat (~> 1.2) + minitest (>= 3.0) + i18n (1.14.1) + concurrent-ruby (~> 1.0) + io-console (0.7.2) + irb (1.11.2) + rdoc + reline (>= 0.4.2) + listen (3.9.0) + rb-fsevent (~> 0.10, >= 0.10.3) + rb-inotify (~> 0.9, >= 0.9.10) + loofah (2.22.0) + crass (~> 1.0.2) + nokogiri (>= 1.12.0) + lumberjack (1.2.10) + mail (2.8.1) + mini_mime (>= 0.1.1) + net-imap + net-pop + net-smtp + marcel (1.0.2) + method_source (1.0.0) + mini_mime (1.1.5) + minitest (5.22.2) + mutex_m (0.2.0) + nenv (0.3.0) + net-imap (0.4.10) + date + net-protocol + net-pop (0.1.2) + net-protocol + net-protocol (0.2.2) + timeout + net-smtp (0.4.0.1) + net-protocol + nio4r (2.7.0) + nokogiri (1.16.2-aarch64-linux) + racc (~> 1.4) + nokogiri (1.16.2-arm-linux) + racc (~> 1.4) + nokogiri (1.16.2-arm64-darwin) + racc (~> 1.4) + nokogiri (1.16.2-x86-linux) + racc (~> 1.4) + nokogiri (1.16.2-x86_64-darwin) + racc (~> 1.4) + nokogiri (1.16.2-x86_64-linux) + racc (~> 1.4) + notiffany (0.1.3) + nenv (~> 0.1) + shellany (~> 0.0) + pg (1.5.5) + pry (0.14.2) + coderay (~> 1.1) + method_source (~> 1.0) + psych (5.1.2) + stringio + puma (6.4.2) + nio4r (~> 2.0) + racc (1.7.3) + rack (3.0.9.1) + rack-session (2.0.0) + rack (>= 3.0.0) + rack-test (2.1.0) + rack (>= 1.3) + rackup (2.1.0) + rack (>= 3) + webrick (~> 1.8) + rails (7.1.3.2) + actioncable (= 7.1.3.2) + actionmailbox (= 7.1.3.2) + actionmailer (= 7.1.3.2) + actionpack (= 7.1.3.2) + actiontext (= 7.1.3.2) + actionview (= 7.1.3.2) + activejob (= 7.1.3.2) + activemodel (= 7.1.3.2) + activerecord (= 7.1.3.2) + activestorage (= 7.1.3.2) + activesupport (= 7.1.3.2) + bundler (>= 1.15.0) + railties (= 7.1.3.2) + rails-dom-testing (2.2.0) + activesupport (>= 5.0.0) + minitest + nokogiri (>= 1.6) + rails-html-sanitizer (1.6.0) + loofah (~> 2.21) + nokogiri (~> 1.14) + railties (7.1.3.2) + actionpack (= 7.1.3.2) + activesupport (= 7.1.3.2) + irb + rackup (>= 1.0.0) + rake (>= 12.2) + thor (~> 1.0, >= 1.2.2) + zeitwerk (~> 2.6) + rake (13.1.0) + rb-fsevent (0.11.2) + rb-inotify (0.10.1) + ffi (~> 1.0) + rdoc (6.6.2) + psych (>= 4.0.0) + reline (0.4.3) + io-console (~> 0.5) + ruby2_keywords (0.0.5) + shellany (0.0.1) + sqlite3 (1.7.2-aarch64-linux) + sqlite3 (1.7.2-arm-linux) + sqlite3 (1.7.2-arm64-darwin) + sqlite3 (1.7.2-x86-linux) + sqlite3 (1.7.2-x86_64-darwin) + sqlite3 (1.7.2-x86_64-linux) + stringio (3.1.0) + thor (1.3.0) + timeout (0.4.1) + tzinfo (2.0.6) + concurrent-ruby (~> 1.0) + webrick (1.8.1) + websocket-driver (0.7.6) + websocket-extensions (>= 0.1.0) + websocket-extensions (0.1.5) + zeitwerk (2.6.13) + +PLATFORMS + aarch64-linux + arm-linux + arm64-darwin + x86-linux + x86_64-darwin + x86_64-linux + +DEPENDENCIES + appraisal + guard (~> 2.18) + guard-minitest (~> 2.4) + pg + puma + sqlite3 + veksel! + +BUNDLED WITH + 2.5.5 diff --git a/Guardfile b/Guardfile new file mode 100644 index 0000000..194b69c --- /dev/null +++ b/Guardfile @@ -0,0 +1,42 @@ +# A sample Guardfile +# More info at https://github.com/guard/guard#readme + +## Uncomment and set this to only include directories you want to watch +# directories %w(app lib config test spec features) \ +# .select{|d| Dir.exist?(d) ? d : UI.warning("Directory #{d} does not exist")} + +## Note: if you are using the `directories` clause above and you are not +## watching the project directory ('.'), then you will want to move +## the Guardfile to a watched dir and symlink it back, e.g. +# +# $ mkdir config +# $ mv Guardfile config/ +# $ ln -s config/Guardfile . +# +# and, you'll have to watch "config/Guardfile" instead of "Guardfile" + +guard :minitest do + # with Minitest::Unit + watch(%r{^test/(.*)\/?test_(.*)\.rb$}) + watch(%r{^lib/(.*/)?([^/]+)\.rb$}) { 'test' } + watch(%r{^test/test_helper\.rb$}) { 'test' } + + # with Minitest::Spec + # watch(%r{^spec/(.*)_spec\.rb$}) + # watch(%r{^lib/(.+)\.rb$}) { |m| "spec/#{m[1]}_spec.rb" } + # watch(%r{^spec/spec_helper\.rb$}) { 'spec' } + + # Rails 4 + # watch(%r{^app/(.+)\.rb$}) { |m| "test/#{m[1]}_test.rb" } + # watch(%r{^app/controllers/application_controller\.rb$}) { 'test/controllers' } + # watch(%r{^app/controllers/(.+)_controller\.rb$}) { |m| "test/integration/#{m[1]}_test.rb" } + # watch(%r{^app/views/(.+)_mailer/.+}) { |m| "test/mailers/#{m[1]}_mailer_test.rb" } + # watch(%r{^lib/(.+)\.rb$}) { |m| "test/lib/#{m[1]}_test.rb" } + # watch(%r{^test/.+_test\.rb$}) + # watch(%r{^test/test_helper\.rb$}) { 'test' } + + # Rails < 4 + # watch(%r{^app/controllers/(.*)\.rb$}) { |m| "test/functional/#{m[1]}_test.rb" } + # watch(%r{^app/helpers/(.*)\.rb$}) { |m| "test/helpers/#{m[1]}_test.rb" } + # watch(%r{^app/models/(.*)\.rb$}) { |m| "test/unit/#{m[1]}_test.rb" } +end diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..4867432 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,20 @@ +Copyright Theodor Tonum + +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/README.md b/README.md new file mode 100644 index 0000000..1336617 --- /dev/null +++ b/README.md @@ -0,0 +1,63 @@ +# Veksel: Database branching for Rails + +Veksel keeps seperate databases for every branch in your development environment. This makes it easy to experiment with schema changes and data with less risk and avoid conflicting changes to `schema.rb` when branches have different sets of migrations. The inspiration for the gem came from [branch support in Neon](https://neon.tech/docs/manage/branches). + +Postgresql is currently the only supported database driver. + +## Usage + +Change the following line in `config/database.yml` + +```yaml +development: + database: your_app_development<%= `bundle exec veksel suffix` %> +``` + +Checkout a new branch and run `bin/rails veksel:fork`. A new database with a suffix matching your branch name will be created. + +### Veksel tasks + +``` +veksel:clean Delete forked databases +veksel:fork Fork the database from the main branch +veksel:list List forked databases +``` + +## Git hook + +Add the following to `.git/hooks/post-checkout` to automatically fork your database when checking out a branch: + +``` +#!/bin/sh +bin/rails veksel:fork +``` + +## Installation + +Add this line to your application's Gemfile: + +```ruby +gem "veksel", group: :development +``` + +And then execute: + +```bash +$ bundle +``` + +Or install it yourself as: + +```bash +$ gem install veksel +``` + +## Roadmap + +- Promote a forked database to main +- Explicit/optional branching +- Other database drivers + +## License + +Veksel is licensed under MIT. diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..7ca8948 --- /dev/null +++ b/Rakefile @@ -0,0 +1,3 @@ +require "bundler/setup" + +require "bundler/gem_tasks" diff --git a/bin/test b/bin/test new file mode 100755 index 0000000..5516a12 --- /dev/null +++ b/bin/test @@ -0,0 +1,5 @@ +#!/usr/bin/env ruby +$: << File.expand_path("../test", __dir__) + +require "bundler/setup" +require "rails/plugin/test" diff --git a/bin/veksel b/bin/veksel new file mode 100755 index 0000000..adbbef0 --- /dev/null +++ b/bin/veksel @@ -0,0 +1,7 @@ +#!/usr/bin/env ruby +require 'veksel' + +case ARGV[0] +when 'suffix' + print Veksel.suffix +end diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..02a569d --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,9 @@ +# Start postgres on port 5555 mapped to localhost +services: + postgres16: + image: "postgres:16" + ports: + - "5555:5432" + environment: + POSTGRES_USER: veksel + POSTGRES_PASSWORD: foobar diff --git a/gemfiles/rails_6.gemfile b/gemfiles/rails_6.gemfile new file mode 100644 index 0000000..f34e24f --- /dev/null +++ b/gemfiles/rails_6.gemfile @@ -0,0 +1,12 @@ +# This file was generated by Appraisal + +source "https://rubygems.org" + +gem "puma" +gem "sqlite3" +gem "pg" +gem "guard", "~> 2.18" +gem "guard-minitest", "~> 2.4" +gem "rails", "~> 6" + +gemspec path: "../" diff --git a/gemfiles/rails_6.gemfile.lock b/gemfiles/rails_6.gemfile.lock new file mode 100644 index 0000000..1f30d06 --- /dev/null +++ b/gemfiles/rails_6.gemfile.lock @@ -0,0 +1,223 @@ +PATH + remote: .. + specs: + veksel (0.1.0) + +GEM + remote: https://rubygems.org/ + specs: + actioncable (6.1.7.7) + actionpack (= 6.1.7.7) + activesupport (= 6.1.7.7) + nio4r (~> 2.0) + websocket-driver (>= 0.6.1) + actionmailbox (6.1.7.7) + actionpack (= 6.1.7.7) + activejob (= 6.1.7.7) + activerecord (= 6.1.7.7) + activestorage (= 6.1.7.7) + activesupport (= 6.1.7.7) + mail (>= 2.7.1) + actionmailer (6.1.7.7) + actionpack (= 6.1.7.7) + actionview (= 6.1.7.7) + activejob (= 6.1.7.7) + activesupport (= 6.1.7.7) + mail (~> 2.5, >= 2.5.4) + rails-dom-testing (~> 2.0) + actionpack (6.1.7.7) + actionview (= 6.1.7.7) + activesupport (= 6.1.7.7) + rack (~> 2.0, >= 2.0.9) + rack-test (>= 0.6.3) + rails-dom-testing (~> 2.0) + rails-html-sanitizer (~> 1.0, >= 1.2.0) + actiontext (6.1.7.7) + actionpack (= 6.1.7.7) + activerecord (= 6.1.7.7) + activestorage (= 6.1.7.7) + activesupport (= 6.1.7.7) + nokogiri (>= 1.8.5) + actionview (6.1.7.7) + activesupport (= 6.1.7.7) + builder (~> 3.1) + erubi (~> 1.4) + rails-dom-testing (~> 2.0) + rails-html-sanitizer (~> 1.1, >= 1.2.0) + activejob (6.1.7.7) + activesupport (= 6.1.7.7) + globalid (>= 0.3.6) + activemodel (6.1.7.7) + activesupport (= 6.1.7.7) + activerecord (6.1.7.7) + activemodel (= 6.1.7.7) + activesupport (= 6.1.7.7) + activestorage (6.1.7.7) + actionpack (= 6.1.7.7) + activejob (= 6.1.7.7) + activerecord (= 6.1.7.7) + activesupport (= 6.1.7.7) + marcel (~> 1.0) + mini_mime (>= 1.1.0) + activesupport (6.1.7.7) + concurrent-ruby (~> 1.0, >= 1.0.2) + i18n (>= 1.6, < 2) + minitest (>= 5.1) + tzinfo (~> 2.0) + zeitwerk (~> 2.3) + appraisal (2.5.0) + bundler + rake + thor (>= 0.14.0) + builder (3.2.4) + coderay (1.1.3) + concurrent-ruby (1.2.3) + crass (1.0.6) + date (3.3.4) + erubi (1.12.0) + ffi (1.16.3) + formatador (1.1.0) + globalid (1.2.1) + activesupport (>= 6.1) + guard (2.18.1) + formatador (>= 0.2.4) + listen (>= 2.7, < 4.0) + lumberjack (>= 1.0.12, < 2.0) + nenv (~> 0.1) + notiffany (~> 0.0) + pry (>= 0.13.0) + shellany (~> 0.0) + thor (>= 0.18.1) + guard-compat (1.2.1) + guard-minitest (2.4.6) + guard-compat (~> 1.2) + minitest (>= 3.0) + i18n (1.14.1) + concurrent-ruby (~> 1.0) + listen (3.9.0) + rb-fsevent (~> 0.10, >= 0.10.3) + rb-inotify (~> 0.9, >= 0.9.10) + loofah (2.22.0) + crass (~> 1.0.2) + nokogiri (>= 1.12.0) + lumberjack (1.2.10) + mail (2.8.1) + mini_mime (>= 0.1.1) + net-imap + net-pop + net-smtp + marcel (1.0.2) + method_source (1.0.0) + mini_mime (1.1.5) + minitest (5.22.2) + nenv (0.3.0) + net-imap (0.4.10) + date + net-protocol + net-pop (0.1.2) + net-protocol + net-protocol (0.2.2) + timeout + net-smtp (0.4.0.1) + net-protocol + nio4r (2.7.0) + nokogiri (1.16.2-aarch64-linux) + racc (~> 1.4) + nokogiri (1.16.2-arm-linux) + racc (~> 1.4) + nokogiri (1.16.2-arm64-darwin) + racc (~> 1.4) + nokogiri (1.16.2-x86-linux) + racc (~> 1.4) + nokogiri (1.16.2-x86_64-darwin) + racc (~> 1.4) + nokogiri (1.16.2-x86_64-linux) + racc (~> 1.4) + notiffany (0.1.3) + nenv (~> 0.1) + shellany (~> 0.0) + pg (1.5.5) + pry (0.14.2) + coderay (~> 1.1) + method_source (~> 1.0) + puma (6.4.2) + nio4r (~> 2.0) + racc (1.7.3) + rack (2.2.8.1) + rack-test (2.1.0) + rack (>= 1.3) + rails (6.1.7.7) + actioncable (= 6.1.7.7) + actionmailbox (= 6.1.7.7) + actionmailer (= 6.1.7.7) + actionpack (= 6.1.7.7) + actiontext (= 6.1.7.7) + actionview (= 6.1.7.7) + activejob (= 6.1.7.7) + activemodel (= 6.1.7.7) + activerecord (= 6.1.7.7) + activestorage (= 6.1.7.7) + activesupport (= 6.1.7.7) + bundler (>= 1.15.0) + railties (= 6.1.7.7) + sprockets-rails (>= 2.0.0) + rails-dom-testing (2.2.0) + activesupport (>= 5.0.0) + minitest + nokogiri (>= 1.6) + rails-html-sanitizer (1.6.0) + loofah (~> 2.21) + nokogiri (~> 1.14) + railties (6.1.7.7) + actionpack (= 6.1.7.7) + activesupport (= 6.1.7.7) + method_source + rake (>= 12.2) + thor (~> 1.0) + rake (13.1.0) + rb-fsevent (0.11.2) + rb-inotify (0.10.1) + ffi (~> 1.0) + shellany (0.0.1) + sprockets (4.2.1) + concurrent-ruby (~> 1.0) + rack (>= 2.2.4, < 4) + sprockets-rails (3.4.2) + actionpack (>= 5.2) + activesupport (>= 5.2) + sprockets (>= 3.0.0) + sqlite3 (1.7.2-aarch64-linux) + sqlite3 (1.7.2-arm-linux) + sqlite3 (1.7.2-arm64-darwin) + sqlite3 (1.7.2-x86-linux) + sqlite3 (1.7.2-x86_64-darwin) + sqlite3 (1.7.2-x86_64-linux) + thor (1.3.1) + timeout (0.4.1) + tzinfo (2.0.6) + concurrent-ruby (~> 1.0) + websocket-driver (0.7.6) + websocket-extensions (>= 0.1.0) + websocket-extensions (0.1.5) + zeitwerk (2.6.13) + +PLATFORMS + aarch64-linux + arm-linux + arm64-darwin + x86-linux + x86_64-darwin + x86_64-linux + +DEPENDENCIES + appraisal + guard (~> 2.18) + guard-minitest (~> 2.4) + pg + puma + rails (~> 6) + sqlite3 + veksel! + +BUNDLED WITH + 2.5.5 diff --git a/lib/tasks/veksel_tasks.rake b/lib/tasks/veksel_tasks.rake new file mode 100644 index 0000000..fa242f3 --- /dev/null +++ b/lib/tasks/veksel_tasks.rake @@ -0,0 +1,69 @@ +namespace :veksel do + task :precreate do + ActiveSupport::Notifications.subscribe "veksel.fork" do |*args| + event = ActiveSupport::Notifications::Event.new(*args) + puts "Forked database in #{event.duration.to_i}ms" + File.open("log/veksel.log", "a") do |f| + f.puts("Forked database in #{event.duration.to_i}ms") + f.puts(" Source: #{event.payload[:source]}") + f.puts(" Target: #{event.payload[:target]}") + end + end + end + + desc "Fork the database from the main branch" + task fork: ['db:create', 'veksel:precreate'] do + next if Veksel.skip_fork? + require 'veksel/commands/fork' + + db = ActiveRecord::Base.configurations.find_db_config('development') + Veksel::Commands::Fork.new(db).perform + end + + desc "List forked databases" + task list: 'db:load_config' do + require 'veksel/commands/clean' + + db = ActiveRecord::Base.configurations.find_db_config('development') + command = Veksel::Commands::Clean.new(db) + databases = command.all_databases + active_branches = command.active_branches + + if databases.empty? + puts "No databases created by Veksel" + next + end + + hash = {} + databases.each do |database| + branch = database.sub(command.prefix, '') + hash[branch] = database + end + + longest_branch_name = hash.keys.max_by(&:length).length + longest_database_name = hash.values.max_by(&:length).length + puts "Databases created by Veksel:" + puts "" + puts "#{'Branch'.ljust(longest_branch_name)} #{'Database'.ljust(longest_database_name)} Active" + inactive_count = 0 + hash.each do |branch, database| + # Print a formatted string padded to fit the longest branch name + active = active_branches.include?(branch) ? 'Yes' : 'No' + inactive_count += 1 if active == 'No' + puts "#{branch.ljust(longest_branch_name)} #{database.ljust(longest_database_name)} #{active}" + end + + if inactive_count > 0 + puts "" + puts "Clean inactive databases with bin/rails veksel:clean" + end + end + + desc "Delete forked databases" + task clean: 'db:load_config' do + require 'veksel/commands/clean' + + db = ActiveRecord::Base.configurations.find_db_config('development') + Veksel::Commands::Clean.new(db).perform + end +end diff --git a/lib/veksel.rb b/lib/veksel.rb new file mode 100644 index 0000000..f9a2d1d --- /dev/null +++ b/lib/veksel.rb @@ -0,0 +1,29 @@ +if defined?(Rails::VERSION) + if Rails::VERSION::MAJOR < 6 + raise "Veksel requires Rails 6 or later" + end +end + +require "veksel/version" +require "veksel/railtie" if defined?(Rails::Railtie) +require "veksel/suffix" + +module Veksel + class << self + def current_branch + `git rev-parse --abbrev-ref HEAD`.strip + end + + def skip_fork? + suffix.blank? + end + + def suffix + Suffix.new(current_branch).to_s + end + + def prefix(dbname) + dbname.sub(%r[#{Veksel.suffix}$], '_') + end + end +end diff --git a/lib/veksel/commands/clean.rb b/lib/veksel/commands/clean.rb new file mode 100644 index 0000000..4ff64da --- /dev/null +++ b/lib/veksel/commands/clean.rb @@ -0,0 +1,33 @@ +require_relative '../pg_cluster' + +module Veksel + module Commands + class Clean + attr_reader :prefix + + def initialize(db, dry_run: false) + @pg_cluster = PgCluster.new(db.configuration_hash) + @prefix = Veksel.prefix(db.configuration_hash[:database]) + @dry_run = dry_run + end + + def perform + all_databases = @pg_cluster.list_databases(prefix: @prefix) + stale_databases = all_databases.filter do |database| + active_branches.none? { |branch| database.end_with?("_#{branch}") } + end + stale_databases.each do |database| + @pg_cluster.drop_database(database, dry_run: @dry_run) + end + end + + def active_branches + `git for-each-ref 'refs/heads/' --format '%(refname)'`.split("\n").map { |ref| ref.sub('refs/heads/', '') } + end + + def all_databases + @pg_cluster.list_databases(prefix: @prefix) + end + end + end +end diff --git a/lib/veksel/commands/fork.rb b/lib/veksel/commands/fork.rb new file mode 100644 index 0000000..7b931bf --- /dev/null +++ b/lib/veksel/commands/fork.rb @@ -0,0 +1,24 @@ +require_relative '../pg_cluster' + +module Veksel + module Commands + class Fork + attr_reader :pg_cluster, :source_db, :target_db + + def initialize(db) + @pg_cluster = PgCluster.new(db.configuration_hash) + @source_db = db.database.sub(%r[#{Veksel.suffix}$], '') + @target_db = db.database + raise "Source and target databases cannot be the same" if source_db == target_db + end + + def perform + return if pg_cluster.target_populated?(target_db) + + ActiveSupport::Notifications.instrument "veksel.fork", source: source_db, target: target_db do + pg_cluster.transfer(from: source_db, to: target_db) + end + end + end + end +end diff --git a/lib/veksel/pg_cluster.rb b/lib/veksel/pg_cluster.rb new file mode 100644 index 0000000..05f8c12 --- /dev/null +++ b/lib/veksel/pg_cluster.rb @@ -0,0 +1,60 @@ +module Veksel + class PgCluster + attr_reader :configuration_hash + + def initialize(configuration_hash) + @configuration_hash = configuration_hash + end + + def target_populated?(dbname) + IO.pipe do |r, w| + spawn(pg_env, %[psql -t #{pg_connection_args(dbname)} -c "SELECT 'ok' FROM ar_internal_metadata LIMIT 1;"], out: w, err: '/dev/null') + pid_grep = spawn(pg_env, %[grep -qw ok], in: r, err: '/dev/null') + w.close + Process::Status.wait(pid_grep).success? + end + end + + def transfer(from:, to:) + r, w = IO.pipe(autoclose: true) + spawn(pg_env, "pg_dump #{pg_connection_args(from)} --format=c", out: w) + pid_psql = spawn(pg_env, "pg_restore --single-transaction --exit-on-error #{pg_connection_args(to)}", in: r) + unless Process::Status.wait(pid_psql).success? + # TODO: Write error log to a tempfile inside the tmp directory of the current directory + raise "pg_restore failed with status #{status.exitstatus}" + end + end + + def list_databases(prefix:) + IO.pipe(autoclose: true) do |r, w| + sql = %[SELECT datname FROM pg_database WHERE datname LIKE '#{prefix}%']; + psql = spawn(pg_env, %[psql -t #{pg_connection_args('postgres')} -c "#{sql}"], out: w, err: '/dev/null') + w.close + Process::Status.wait(psql) + r.read.split("\n").map(&:strip) + end + end + + def drop_database(dbname, dry_run: false) + if dry_run + puts "[Veksel] Would drop database #{dbname}" + end + spawn(pg_env, %[dropdb --no-password #{dbname}]) + end + + private + + def pg_connection_args(dbname) + "-d #{dbname} --no-password" + end + + def pg_env + { + 'PGHOST' => configuration_hash[:host], + 'PGPORT' => configuration_hash[:port]&.to_s, + 'PGUSER' => configuration_hash[:username], + 'PGPASSWORD' => configuration_hash[:password], + }.compact + end + end +end diff --git a/lib/veksel/railtie.rb b/lib/veksel/railtie.rb new file mode 100644 index 0000000..fea4158 --- /dev/null +++ b/lib/veksel/railtie.rb @@ -0,0 +1,7 @@ +module Veksel + class Railtie < ::Rails::Railtie + rake_tasks do + load "tasks/veksel_tasks.rake" + end + end +end diff --git a/lib/veksel/suffix.rb b/lib/veksel/suffix.rb new file mode 100644 index 0000000..5a6d9dc --- /dev/null +++ b/lib/veksel/suffix.rb @@ -0,0 +1,18 @@ +module Veksel + PROTECTED_BRANCHES = %w[master main HEAD].freeze + + class Suffix + def initialize(branch_name) + @branch_name = branch_name + end + + def to_s + case @branch_name + when *PROTECTED_BRANCHES + "" + else + "_#{@branch_name}" + end + end + end +end diff --git a/lib/veksel/version.rb b/lib/veksel/version.rb new file mode 100644 index 0000000..2962724 --- /dev/null +++ b/lib/veksel/version.rb @@ -0,0 +1,3 @@ +module Veksel + VERSION = "0.1.0" +end diff --git a/test/dummy/Rakefile b/test/dummy/Rakefile new file mode 100644 index 0000000..9a5ea73 --- /dev/null +++ b/test/dummy/Rakefile @@ -0,0 +1,6 @@ +# Add your own tasks in files placed in lib/tasks ending in .rake, +# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. + +require_relative "config/application" + +Rails.application.load_tasks diff --git a/test/dummy/app/assets/images/.keep b/test/dummy/app/assets/images/.keep new file mode 100644 index 0000000..e69de29 diff --git a/test/dummy/app/assets/stylesheets/application.css b/test/dummy/app/assets/stylesheets/application.css new file mode 100644 index 0000000..dcd7273 --- /dev/null +++ b/test/dummy/app/assets/stylesheets/application.css @@ -0,0 +1 @@ +/* Application styles */ diff --git a/test/dummy/app/channels/application_cable/channel.rb b/test/dummy/app/channels/application_cable/channel.rb new file mode 100644 index 0000000..d672697 --- /dev/null +++ b/test/dummy/app/channels/application_cable/channel.rb @@ -0,0 +1,4 @@ +module ApplicationCable + class Channel < ActionCable::Channel::Base + end +end diff --git a/test/dummy/app/channels/application_cable/connection.rb b/test/dummy/app/channels/application_cable/connection.rb new file mode 100644 index 0000000..0ff5442 --- /dev/null +++ b/test/dummy/app/channels/application_cable/connection.rb @@ -0,0 +1,4 @@ +module ApplicationCable + class Connection < ActionCable::Connection::Base + end +end diff --git a/test/dummy/app/controllers/application_controller.rb b/test/dummy/app/controllers/application_controller.rb new file mode 100644 index 0000000..09705d1 --- /dev/null +++ b/test/dummy/app/controllers/application_controller.rb @@ -0,0 +1,2 @@ +class ApplicationController < ActionController::Base +end diff --git a/test/dummy/app/controllers/concerns/.keep b/test/dummy/app/controllers/concerns/.keep new file mode 100644 index 0000000..e69de29 diff --git a/test/dummy/app/helpers/application_helper.rb b/test/dummy/app/helpers/application_helper.rb new file mode 100644 index 0000000..de6be79 --- /dev/null +++ b/test/dummy/app/helpers/application_helper.rb @@ -0,0 +1,2 @@ +module ApplicationHelper +end diff --git a/test/dummy/app/jobs/application_job.rb b/test/dummy/app/jobs/application_job.rb new file mode 100644 index 0000000..d394c3d --- /dev/null +++ b/test/dummy/app/jobs/application_job.rb @@ -0,0 +1,7 @@ +class ApplicationJob < ActiveJob::Base + # Automatically retry jobs that encountered a deadlock + # retry_on ActiveRecord::Deadlocked + + # Most jobs are safe to ignore if the underlying records are no longer available + # discard_on ActiveJob::DeserializationError +end diff --git a/test/dummy/app/mailers/application_mailer.rb b/test/dummy/app/mailers/application_mailer.rb new file mode 100644 index 0000000..3c34c81 --- /dev/null +++ b/test/dummy/app/mailers/application_mailer.rb @@ -0,0 +1,4 @@ +class ApplicationMailer < ActionMailer::Base + default from: "from@example.com" + layout "mailer" +end diff --git a/test/dummy/app/models/application_record.rb b/test/dummy/app/models/application_record.rb new file mode 100644 index 0000000..19dda7a --- /dev/null +++ b/test/dummy/app/models/application_record.rb @@ -0,0 +1,5 @@ +class ApplicationRecord < ActiveRecord::Base + if Rails::VERSION::MAJOR >= 7 + primary_abstract_class + end +end diff --git a/test/dummy/app/models/concerns/.keep b/test/dummy/app/models/concerns/.keep new file mode 100644 index 0000000..e69de29 diff --git a/test/dummy/app/views/layouts/application.html.erb b/test/dummy/app/views/layouts/application.html.erb new file mode 100644 index 0000000..f72b4ef --- /dev/null +++ b/test/dummy/app/views/layouts/application.html.erb @@ -0,0 +1,15 @@ + + + + Dummy + + <%= csrf_meta_tags %> + <%= csp_meta_tag %> + + <%= stylesheet_link_tag "application" %> + + + + <%= yield %> + + diff --git a/test/dummy/app/views/layouts/mailer.html.erb b/test/dummy/app/views/layouts/mailer.html.erb new file mode 100644 index 0000000..3aac900 --- /dev/null +++ b/test/dummy/app/views/layouts/mailer.html.erb @@ -0,0 +1,13 @@ + + + + + + + + + <%= yield %> + + diff --git a/test/dummy/app/views/layouts/mailer.text.erb b/test/dummy/app/views/layouts/mailer.text.erb new file mode 100644 index 0000000..37f0bdd --- /dev/null +++ b/test/dummy/app/views/layouts/mailer.text.erb @@ -0,0 +1 @@ +<%= yield %> diff --git a/test/dummy/bin/rails b/test/dummy/bin/rails new file mode 100755 index 0000000..efc0377 --- /dev/null +++ b/test/dummy/bin/rails @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +APP_PATH = File.expand_path("../config/application", __dir__) +require_relative "../config/boot" +require "rails/commands" diff --git a/test/dummy/bin/rake b/test/dummy/bin/rake new file mode 100755 index 0000000..4fbf10b --- /dev/null +++ b/test/dummy/bin/rake @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +require_relative "../config/boot" +require "rake" +Rake.application.run diff --git a/test/dummy/bin/setup b/test/dummy/bin/setup new file mode 100755 index 0000000..3cd5a9d --- /dev/null +++ b/test/dummy/bin/setup @@ -0,0 +1,33 @@ +#!/usr/bin/env ruby +require "fileutils" + +# path to your application root. +APP_ROOT = File.expand_path("..", __dir__) + +def system!(*args) + system(*args, exception: true) +end + +FileUtils.chdir APP_ROOT do + # This script is a way to set up or update your development environment automatically. + # This script is idempotent, so that you can run it at any time and get an expectable outcome. + # Add necessary setup steps to this file. + + puts "== Installing dependencies ==" + system! "gem install bundler --conservative" + system("bundle check") || system!("bundle install") + + # puts "\n== Copying sample files ==" + # unless File.exist?("config/database.yml") + # FileUtils.cp "config/database.yml.sample", "config/database.yml" + # end + + puts "\n== Preparing database ==" + system! "bin/rails db:prepare" + + puts "\n== Removing old logs and tempfiles ==" + system! "bin/rails log:clear tmp:clear" + + puts "\n== Restarting application server ==" + system! "bin/rails restart" +end diff --git a/test/dummy/config.ru b/test/dummy/config.ru new file mode 100644 index 0000000..4a3c09a --- /dev/null +++ b/test/dummy/config.ru @@ -0,0 +1,6 @@ +# This file is used by Rack-based servers to start the application. + +require_relative "config/environment" + +run Rails.application +Rails.application.load_server diff --git a/test/dummy/config/application.rb b/test/dummy/config/application.rb new file mode 100644 index 0000000..7e20b39 --- /dev/null +++ b/test/dummy/config/application.rb @@ -0,0 +1,40 @@ +require_relative "boot" + +require "rails" +# Pick the frameworks you want: +# require "active_model/railtie" +# require "active_job/railtie" +require "active_record/railtie" +# require "active_storage/engine" +# require "action_controller/railtie" +# require "action_mailer/railtie" +# require "action_mailbox/engine" +# require "action_text/engine" +# require "action_view/railtie" +# require "action_cable/engine" +# require "rails/test_unit/railtie" + +# Require the gems listed in Gemfile, including any gems +# you've limited to :test, :development, or :production. +Bundler.require(*Rails.groups) + +module Dummy + class Application < Rails::Application + config.load_defaults Rails::VERSION::STRING.to_f + + # Please, add to the `ignore` list any other `lib` subdirectories that do + # not contain `.rb` files, or that should not be reloaded or eager loaded. + # Common ones are `templates`, `generators`, or `middleware`, for example. + if Rails::VERSION::MAJOR >= 7 + config.autoload_lib(ignore: %w(assets tasks)) + end + + # Configuration for the application, engines, and railties goes here. + # + # These settings can be overridden in specific environments using the files + # in config/environments, which are processed later. + # + # config.time_zone = "Central Time (US & Canada)" + # config.eager_load_paths << Rails.root.join("extras") + end +end diff --git a/test/dummy/config/boot.rb b/test/dummy/config/boot.rb new file mode 100644 index 0000000..116591a --- /dev/null +++ b/test/dummy/config/boot.rb @@ -0,0 +1,5 @@ +# Set up gems listed in the Gemfile. +ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../../Gemfile", __dir__) + +require "bundler/setup" if File.exist?(ENV["BUNDLE_GEMFILE"]) +$LOAD_PATH.unshift File.expand_path("../../../lib", __dir__) diff --git a/test/dummy/config/cable.yml b/test/dummy/config/cable.yml new file mode 100644 index 0000000..98367f8 --- /dev/null +++ b/test/dummy/config/cable.yml @@ -0,0 +1,10 @@ +development: + adapter: async + +test: + adapter: test + +production: + adapter: redis + url: <%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" } %> + channel_prefix: dummy_production diff --git a/test/dummy/config/database.yml b/test/dummy/config/database.yml new file mode 100644 index 0000000..1ee3ab6 --- /dev/null +++ b/test/dummy/config/database.yml @@ -0,0 +1,23 @@ +# SQLite. Versions 3.8.0 and up are supported. +# gem install sqlite3 +# +# Ensure the SQLite 3 gem is defined in your Gemfile +# gem "sqlite3" +# +development: + adapter: postgresql + encoding: unicode + database: veksel_dummy_development<%= `bundle exec veksel suffix` %> + port: 5555 + host: localhost + username: veksel + password: foobar + +test: + adapter: postgresql + encoding: unicode + database: veksel_dummy_test + port: 5555 + host: localhost + username: veksel + password: foobar diff --git a/test/dummy/config/environment.rb b/test/dummy/config/environment.rb new file mode 100644 index 0000000..cac5315 --- /dev/null +++ b/test/dummy/config/environment.rb @@ -0,0 +1,5 @@ +# Load the Rails application. +require_relative "application" + +# Initialize the Rails application. +Rails.application.initialize! diff --git a/test/dummy/config/environments/development.rb b/test/dummy/config/environments/development.rb new file mode 100644 index 0000000..862a6cf --- /dev/null +++ b/test/dummy/config/environments/development.rb @@ -0,0 +1,74 @@ +require "active_support/core_ext/integer/time" + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # In the development environment your application's code is reloaded any time + # it changes. This slows down response time but is perfect for development + # since you don't have to restart the web server when you make code changes. + config.enable_reloading = true + + # Do not eager load code on boot. + config.eager_load = false + + # Show full error reports. + config.consider_all_requests_local = true + + # Enable server timing + config.server_timing = true + + # Enable/disable caching. By default caching is disabled. + # Run rails dev:cache to toggle caching. + if Rails.root.join("tmp/caching-dev.txt").exist? + config.action_controller.perform_caching = true + config.action_controller.enable_fragment_cache_logging = true + + config.cache_store = :memory_store + config.public_file_server.headers = { + "Cache-Control" => "public, max-age=#{2.days.to_i}" + } + else + config.action_controller.perform_caching = false + + config.cache_store = :null_store + end + + # Store uploaded files on the local file system (see config/storage.yml for options). + # config.active_storage.service = :local + + # Don't care if the mailer can't send. + # config.action_mailer.raise_delivery_errors = false + + # config.action_mailer.perform_caching = false + + # Print deprecation notices to the Rails logger. + config.active_support.deprecation = :log + + # Raise exceptions for disallowed deprecations. + config.active_support.disallowed_deprecation = :raise + + # Tell Active Support which deprecation messages to disallow. + config.active_support.disallowed_deprecation_warnings = [] + + # Raise an error on page load if there are pending migrations. + config.active_record.migration_error = :page_load + + # Highlight code that triggered database queries in logs. + config.active_record.verbose_query_logs = true + + # Highlight code that enqueued background job in logs. + # config.active_job.verbose_enqueue_logs = true + + + # Raises error for missing translations. + # config.i18n.raise_on_missing_translations = true + + # Annotate rendered view with file names. + # config.action_view.annotate_rendered_view_with_filenames = true + + # Uncomment if you wish to allow Action Cable access from any origin. + # config.action_cable.disable_request_forgery_protection = true + + # Raise error when a before_action's only/except options reference missing actions + config.action_controller.raise_on_missing_callback_actions = true +end diff --git a/test/dummy/config/environments/production.rb b/test/dummy/config/environments/production.rb new file mode 100644 index 0000000..3597e53 --- /dev/null +++ b/test/dummy/config/environments/production.rb @@ -0,0 +1,91 @@ +require "active_support/core_ext/integer/time" + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # Code is not reloaded between requests. + config.enable_reloading = false + + # Eager load code on boot. This eager loads most of Rails and + # your application in memory, allowing both threaded web servers + # and those relying on copy on write to perform better. + # Rake tasks automatically ignore this option for performance. + config.eager_load = true + + # Full error reports are disabled and caching is turned on. + config.consider_all_requests_local = false + config.action_controller.perform_caching = true + + # Ensures that a master key has been made available in ENV["RAILS_MASTER_KEY"], config/master.key, or an environment + # key such as config/credentials/production.key. This key is used to decrypt credentials (and other encrypted files). + # config.require_master_key = true + + # Disable serving static files from `public/`, relying on NGINX/Apache to do so instead. + # config.public_file_server.enabled = false + + # Enable serving of images, stylesheets, and JavaScripts from an asset server. + # config.asset_host = "http://assets.example.com" + + # Specifies the header that your server uses for sending files. + # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for Apache + # config.action_dispatch.x_sendfile_header = "X-Accel-Redirect" # for NGINX + + # Store uploaded files on the local file system (see config/storage.yml for options). + # config.active_storage.service = :local + + # Mount Action Cable outside main process or domain. + # config.action_cable.mount_path = nil + # config.action_cable.url = "wss://example.com/cable" + # config.action_cable.allowed_request_origins = [ "http://example.com", /http:\/\/example.*/ ] + + # Assume all access to the app is happening through a SSL-terminating reverse proxy. + # Can be used together with config.force_ssl for Strict-Transport-Security and secure cookies. + # config.assume_ssl = true + + # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. + config.force_ssl = true + + # Log to STDOUT by default + config.logger = ActiveSupport::Logger.new(STDOUT) + .tap { |logger| logger.formatter = ::Logger::Formatter.new } + .then { |logger| ActiveSupport::TaggedLogging.new(logger) } + + # Prepend all log lines with the following tags. + config.log_tags = [ :request_id ] + + # "info" includes generic and useful information about system operation, but avoids logging too much + # information to avoid inadvertent exposure of personally identifiable information (PII). If you + # want to log everything, set the level to "debug". + config.log_level = ENV.fetch("RAILS_LOG_LEVEL", "info") + + # Use a different cache store in production. + # config.cache_store = :mem_cache_store + + # Use a real queuing backend for Active Job (and separate queues per environment). + # config.active_job.queue_adapter = :resque + # config.active_job.queue_name_prefix = "dummy_production" + + # config.action_mailer.perform_caching = false + + # Ignore bad email addresses and do not raise email delivery errors. + # Set this to true and configure the email server for immediate delivery to raise delivery errors. + # config.action_mailer.raise_delivery_errors = false + + # Enable locale fallbacks for I18n (makes lookups for any locale fall back to + # the I18n.default_locale when a translation cannot be found). + config.i18n.fallbacks = true + + # Don't log any deprecations. + config.active_support.report_deprecations = false + + # Do not dump schema after migrations. + config.active_record.dump_schema_after_migration = false + + # Enable DNS rebinding protection and other `Host` header attacks. + # config.hosts = [ + # "example.com", # Allow requests from example.com + # /.*\.example\.com/ # Allow requests from subdomains like `www.example.com` + # ] + # Skip DNS rebinding protection for the default health check endpoint. + # config.host_authorization = { exclude: ->(request) { request.path == "/up" } } +end diff --git a/test/dummy/config/environments/test.rb b/test/dummy/config/environments/test.rb new file mode 100644 index 0000000..41b37df --- /dev/null +++ b/test/dummy/config/environments/test.rb @@ -0,0 +1,64 @@ +require "active_support/core_ext/integer/time" + +# The test environment is used exclusively to run your application's +# test suite. You never need to work with it otherwise. Remember that +# your test database is "scratch space" for the test suite and is wiped +# and recreated between test runs. Don't rely on the data there! + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # While tests run files are not watched, reloading is not necessary. + config.enable_reloading = false + + # Eager loading loads your entire application. When running a single test locally, + # this is usually not necessary, and can slow down your test suite. However, it's + # recommended that you enable it in continuous integration systems to ensure eager + # loading is working properly before deploying your code. + config.eager_load = ENV["CI"].present? + + # Configure public file server for tests with Cache-Control for performance. + config.public_file_server.enabled = true + config.public_file_server.headers = { + "Cache-Control" => "public, max-age=#{1.hour.to_i}" + } + + # Show full error reports and disable caching. + config.consider_all_requests_local = true + config.action_controller.perform_caching = false + config.cache_store = :null_store + + # Render exception templates for rescuable exceptions and raise for other exceptions. + config.action_dispatch.show_exceptions = :rescuable + + # Disable request forgery protection in test environment. + config.action_controller.allow_forgery_protection = false + + # Store uploaded files on the local file system in a temporary directory. + # config.active_storage.service = :test + + # config.action_mailer.perform_caching = false + + # Tell Action Mailer not to deliver emails to the real world. + # The :test delivery method accumulates sent emails in the + # ActionMailer::Base.deliveries array. + # config.action_mailer.delivery_method = :test + + # Print deprecation notices to the stderr. + config.active_support.deprecation = :stderr + + # Raise exceptions for disallowed deprecations. + config.active_support.disallowed_deprecation = :raise + + # Tell Active Support which deprecation messages to disallow. + config.active_support.disallowed_deprecation_warnings = [] + + # Raises error for missing translations. + # config.i18n.raise_on_missing_translations = true + + # Annotate rendered view with file names. + # config.action_view.annotate_rendered_view_with_filenames = true + + # Raise error when a before_action's only/except options reference missing actions + config.action_controller.raise_on_missing_callback_actions = true +end diff --git a/test/dummy/config/initializers/content_security_policy.rb b/test/dummy/config/initializers/content_security_policy.rb new file mode 100644 index 0000000..b3076b3 --- /dev/null +++ b/test/dummy/config/initializers/content_security_policy.rb @@ -0,0 +1,25 @@ +# Be sure to restart your server when you modify this file. + +# Define an application-wide content security policy. +# See the Securing Rails Applications Guide for more information: +# https://guides.rubyonrails.org/security.html#content-security-policy-header + +# Rails.application.configure do +# config.content_security_policy do |policy| +# policy.default_src :self, :https +# policy.font_src :self, :https, :data +# policy.img_src :self, :https, :data +# policy.object_src :none +# policy.script_src :self, :https +# policy.style_src :self, :https +# # Specify URI for violation reports +# # policy.report_uri "/csp-violation-report-endpoint" +# end +# +# # Generate session nonces for permitted importmap, inline scripts, and inline styles. +# config.content_security_policy_nonce_generator = ->(request) { request.session.id.to_s } +# config.content_security_policy_nonce_directives = %w(script-src style-src) +# +# # Report violations without enforcing the policy. +# # config.content_security_policy_report_only = true +# end diff --git a/test/dummy/config/initializers/filter_parameter_logging.rb b/test/dummy/config/initializers/filter_parameter_logging.rb new file mode 100644 index 0000000..c2d89e2 --- /dev/null +++ b/test/dummy/config/initializers/filter_parameter_logging.rb @@ -0,0 +1,8 @@ +# Be sure to restart your server when you modify this file. + +# Configure parameters to be partially matched (e.g. passw matches password) and filtered from the log file. +# Use this to limit dissemination of sensitive information. +# See the ActiveSupport::ParameterFilter documentation for supported notations and behaviors. +Rails.application.config.filter_parameters += [ + :passw, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn +] diff --git a/test/dummy/config/initializers/inflections.rb b/test/dummy/config/initializers/inflections.rb new file mode 100644 index 0000000..3860f65 --- /dev/null +++ b/test/dummy/config/initializers/inflections.rb @@ -0,0 +1,16 @@ +# Be sure to restart your server when you modify this file. + +# Add new inflection rules using the following format. Inflections +# are locale specific, and you may define rules for as many different +# locales as you wish. All of these examples are active by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.plural /^(ox)$/i, "\\1en" +# inflect.singular /^(ox)en/i, "\\1" +# inflect.irregular "person", "people" +# inflect.uncountable %w( fish sheep ) +# end + +# These inflection rules are supported but not enabled by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.acronym "RESTful" +# end diff --git a/test/dummy/config/initializers/permissions_policy.rb b/test/dummy/config/initializers/permissions_policy.rb new file mode 100644 index 0000000..7db3b95 --- /dev/null +++ b/test/dummy/config/initializers/permissions_policy.rb @@ -0,0 +1,13 @@ +# Be sure to restart your server when you modify this file. + +# Define an application-wide HTTP permissions policy. For further +# information see: https://developers.google.com/web/updates/2018/06/feature-policy + +# Rails.application.config.permissions_policy do |policy| +# policy.camera :none +# policy.gyroscope :none +# policy.microphone :none +# policy.usb :none +# policy.fullscreen :self +# policy.payment :self, "https://secure.example.com" +# end diff --git a/test/dummy/config/locales/en.yml b/test/dummy/config/locales/en.yml new file mode 100644 index 0000000..6c349ae --- /dev/null +++ b/test/dummy/config/locales/en.yml @@ -0,0 +1,31 @@ +# Files in the config/locales directory are used for internationalization and +# are automatically loaded by Rails. If you want to use locales other than +# English, add the necessary files in this directory. +# +# To use the locales, use `I18n.t`: +# +# I18n.t "hello" +# +# In views, this is aliased to just `t`: +# +# <%= t("hello") %> +# +# To use a different locale, set it with `I18n.locale`: +# +# I18n.locale = :es +# +# This would use the information in config/locales/es.yml. +# +# To learn more about the API, please read the Rails Internationalization guide +# at https://guides.rubyonrails.org/i18n.html. +# +# Be aware that YAML interprets the following case-insensitive strings as +# booleans: `true`, `false`, `on`, `off`, `yes`, `no`. Therefore, these strings +# must be quoted to be interpreted as strings. For example: +# +# en: +# "yes": yup +# enabled: "ON" + +en: + hello: "Hello world" diff --git a/test/dummy/config/puma.rb b/test/dummy/config/puma.rb new file mode 100644 index 0000000..afa809b --- /dev/null +++ b/test/dummy/config/puma.rb @@ -0,0 +1,35 @@ +# This configuration file will be evaluated by Puma. The top-level methods that +# are invoked here are part of Puma's configuration DSL. For more information +# about methods provided by the DSL, see https://puma.io/puma/Puma/DSL.html. + +# Puma can serve each request in a thread from an internal thread pool. +# The `threads` method setting takes two numbers: a minimum and maximum. +# Any libraries that use thread pools should be configured to match +# the maximum value specified for Puma. Default is set to 5 threads for minimum +# and maximum; this matches the default thread size of Active Record. +max_threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 } +min_threads_count = ENV.fetch("RAILS_MIN_THREADS") { max_threads_count } +threads min_threads_count, max_threads_count + +# Specifies that the worker count should equal the number of processors in production. +if ENV["RAILS_ENV"] == "production" + require "concurrent-ruby" + worker_count = Integer(ENV.fetch("WEB_CONCURRENCY") { Concurrent.physical_processor_count }) + workers worker_count if worker_count > 1 +end + +# Specifies the `worker_timeout` threshold that Puma will use to wait before +# terminating a worker in development environments. +worker_timeout 3600 if ENV.fetch("RAILS_ENV", "development") == "development" + +# Specifies the `port` that Puma will listen on to receive requests; default is 3000. +port ENV.fetch("PORT") { 3000 } + +# Specifies the `environment` that Puma will run in. +environment ENV.fetch("RAILS_ENV") { "development" } + +# Specifies the `pidfile` that Puma will use. +pidfile ENV.fetch("PIDFILE") { "tmp/pids/server.pid" } + +# Allow puma to be restarted by `bin/rails restart` command. +plugin :tmp_restart diff --git a/test/dummy/config/routes.rb b/test/dummy/config/routes.rb new file mode 100644 index 0000000..a125ef0 --- /dev/null +++ b/test/dummy/config/routes.rb @@ -0,0 +1,10 @@ +Rails.application.routes.draw do + # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html + + # Reveal health status on /up that returns 200 if the app boots with no exceptions, otherwise 500. + # Can be used by load balancers and uptime monitors to verify that the app is live. + get "up" => "rails/health#show", as: :rails_health_check + + # Defines the root path route ("/") + # root "posts#index" +end diff --git a/test/dummy/config/storage.yml b/test/dummy/config/storage.yml new file mode 100644 index 0000000..4942ab6 --- /dev/null +++ b/test/dummy/config/storage.yml @@ -0,0 +1,34 @@ +test: + service: Disk + root: <%= Rails.root.join("tmp/storage") %> + +local: + service: Disk + root: <%= Rails.root.join("storage") %> + +# Use bin/rails credentials:edit to set the AWS secrets (as aws:access_key_id|secret_access_key) +# amazon: +# service: S3 +# access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %> +# secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %> +# region: us-east-1 +# bucket: your_own_bucket-<%= Rails.env %> + +# Remember not to checkin your GCS keyfile to a repository +# google: +# service: GCS +# project: your_project +# credentials: <%= Rails.root.join("path/to/gcs.keyfile") %> +# bucket: your_own_bucket-<%= Rails.env %> + +# Use bin/rails credentials:edit to set the Azure Storage secret (as azure_storage:storage_access_key) +# microsoft: +# service: AzureStorage +# storage_account_name: your_account_name +# storage_access_key: <%= Rails.application.credentials.dig(:azure_storage, :storage_access_key) %> +# container: your_container_name-<%= Rails.env %> + +# mirror: +# service: Mirror +# primary: local +# mirrors: [ amazon, google, microsoft ] diff --git a/test/dummy/db/schema.rb b/test/dummy/db/schema.rb new file mode 100644 index 0000000..9622409 --- /dev/null +++ b/test/dummy/db/schema.rb @@ -0,0 +1,24 @@ +# This file is auto-generated from the current state of the database. Instead +# of editing this file, please use the migrations feature of Active Record to +# incrementally modify your database, and then regenerate this schema definition. +# +# This file is the source Rails uses to define your schema when running `bin/rails +# db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to +# be faster and is potentially less error prone than running all of your +# migrations from scratch. Old migrations may fail to apply correctly if those +# migrations use external dependencies or application code. +# +# It's strongly recommended that you check this file into your version control system. + +ActiveRecord::Schema.define(version: 2024_02_25_092447) do + # These are extensions that must be enabled in order to support this database + enable_extension "plpgsql" + + create_table "dummy_models", force: :cascade do |t| + t.string "foo" + t.string "bar" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + end + +end diff --git a/test/dummy/lib/assets/.keep b/test/dummy/lib/assets/.keep new file mode 100644 index 0000000..e69de29 diff --git a/test/dummy/log/.keep b/test/dummy/log/.keep new file mode 100644 index 0000000..e69de29 diff --git a/test/dummy/public/404.html b/test/dummy/public/404.html new file mode 100644 index 0000000..2be3af2 --- /dev/null +++ b/test/dummy/public/404.html @@ -0,0 +1,67 @@ + + + + The page you were looking for doesn't exist (404) + + + + + + +
+
+

The page you were looking for doesn't exist.

+

You may have mistyped the address or the page may have moved.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/test/dummy/public/422.html b/test/dummy/public/422.html new file mode 100644 index 0000000..c08eac0 --- /dev/null +++ b/test/dummy/public/422.html @@ -0,0 +1,67 @@ + + + + The change you wanted was rejected (422) + + + + + + +
+
+

The change you wanted was rejected.

+

Maybe you tried to change something you didn't have access to.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/test/dummy/public/500.html b/test/dummy/public/500.html new file mode 100644 index 0000000..78a030a --- /dev/null +++ b/test/dummy/public/500.html @@ -0,0 +1,66 @@ + + + + We're sorry, but something went wrong (500) + + + + + + +
+
+

We're sorry, but something went wrong.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/test/dummy/public/apple-touch-icon-precomposed.png b/test/dummy/public/apple-touch-icon-precomposed.png new file mode 100644 index 0000000..e69de29 diff --git a/test/dummy/public/apple-touch-icon.png b/test/dummy/public/apple-touch-icon.png new file mode 100644 index 0000000..e69de29 diff --git a/test/dummy/public/favicon.ico b/test/dummy/public/favicon.ico new file mode 100644 index 0000000..e69de29 diff --git a/test/test_helper.rb b/test/test_helper.rb new file mode 100644 index 0000000..6a9bb5b --- /dev/null +++ b/test/test_helper.rb @@ -0,0 +1,21 @@ +# Configure Rails Environment +ENV["RAILS_ENV"] = "development" +Dir.chdir('test/dummy') do + # Make sure the database is setup in main + system('bin/rails db:setup') || raise("Failed to setup database") +end + +ENV["RAILS_ENV"] = "test" + +require_relative "../test/dummy/config/environment" + +ActiveRecord::Migrator.migrations_paths = [File.expand_path("../test/dummy/db/migrate", __dir__)] +require "rails/test_help" + +# Load fixtures from the engine +if ActiveSupport::TestCase.respond_to?(:fixture_paths=) + ActiveSupport::TestCase.fixture_paths = [File.expand_path("fixtures", __dir__)] + ActionDispatch::IntegrationTest.fixture_paths = ActiveSupport::TestCase.fixture_paths + ActiveSupport::TestCase.file_fixture_path = File.expand_path("fixtures", __dir__) + "/files" + ActiveSupport::TestCase.fixtures :all +end diff --git a/test/veksel_test.rb b/test/veksel_test.rb new file mode 100644 index 0000000..176beb1 --- /dev/null +++ b/test/veksel_test.rb @@ -0,0 +1,66 @@ +require "test_helper" + +class VekselTest < ActiveSupport::TestCase + test "it has a version number" do + assert Veksel::VERSION + end + + def git_checkout(branch, &blk) + system!("git checkout -B #{branch}") + blk.call + ensure + system!("git checkout main") + end + + def system!(command, options = {}) + system(command, { + exception: true, + out: '/dev/null', + err: '/dev/null', + }.merge(options)) + end + + def setup + ENV['RAILS_ENV'] = 'development' + system!("git checkout main") + system!("git branch -D somebranch", { exception: false }) + system!("git branch -D some_branch", { exception: false }) + Dir.chdir('test/dummy') do + system!('bin/rails veksel:clean') + end + end + + test "integration" do + Dir.chdir('test/dummy') do + git_checkout('somebranch') do + system!('bin/rails veksel:fork') + current_db = `bin/rails runner "print ApplicationRecord.connection.execute('SELECT current_database();')[0]['current_database']"`.chomp + assert_equal 'veksel_dummy_development_somebranch', current_db + assert_equal `PGPASSWORD=foobar pg_dump -s -h localhost -p 5555 -U veksel veksel_dummy_development`, `PGPASSWORD=foobar pg_dump -s -h localhost -p 5555 -U veksel veksel_dummy_development_somebranch` + end + end + end + + test "db:create should be idempotent and not fail on subsequent checkouts" do + Dir.chdir('test/dummy') do + git_checkout('somebranch') do + system!('bin/rails veksel:fork') + end + + git_checkout('somebranch') do + system!('bin/rails veksel:fork') + end + end + end + + test "branch names with underscore should work fine" do + Dir.chdir('test/dummy') do + git_checkout('some_branch') do + system!('bin/rails veksel:fork') + current_db = `bin/rails runner "print ApplicationRecord.connection.execute('SELECT current_database();')[0]['current_database']"`.chomp + assert_equal 'veksel_dummy_development_some_branch', current_db + assert_equal `PGPASSWORD=foobar pg_dump -s -h localhost -p 5555 -U veksel veksel_dummy_development`, `PGPASSWORD=foobar pg_dump -s -h localhost -p 5555 -U veksel veksel_dummy_development_some_branch` + end + end + end +end diff --git a/veksel.gemspec b/veksel.gemspec new file mode 100644 index 0000000..530a9a9 --- /dev/null +++ b/veksel.gemspec @@ -0,0 +1,30 @@ +require_relative "lib/veksel/version" + +Gem::Specification.new do |spec| + spec.name = "veksel" + spec.version = Veksel::VERSION + spec.authors = ["Theodor Tonum"] + spec.email = ["theodor@tonum.no"] + spec.homepage = "https://github.com/theodorton/veksel" + spec.summary = "Veksel keeps seperate databases for every branch in your development environment. This makes it easy to experiment with schema changes and data with less risk and schema.rb headache when switching branches that has different sets of migrations. The inspiration for the gem came from neons branch support." + spec.description = "Seperate databases for every branch in your development environment" + spec.license = "MIT" + + spec.metadata["allowed_push_host"] = 'https://rubygems.org' + + spec.metadata["homepage_uri"] = spec.homepage + spec.metadata["source_code_uri"] = "https://github.com/theodorton/veksel" + spec.metadata["changelog_uri"] = "https://github.com/theodorton/veksel/blob/main/CHANGELOG.md" + + spec.files = Dir.chdir(File.expand_path(__dir__)) do + Dir["{lib}/**/*", "LICENSE.md", "Rakefile", "README.md"] + end + + spec.executables << 'veksel' + + spec.add_dependency "rails", ">= 6", "< 8" + spec.add_dependency "activerecord" + spec.add_dependency "pg" + + spec.add_development_dependency "appraisal" +end