Class: ActualDbSchema::GitHooks

Inherits:
Object
  • Object
show all
Includes:
OutputFormatter
Defined in:
lib/actual_db_schema/git_hooks.rb

Overview

Handles the installation of a git post-checkout hook that rolls back phantom migrations when switching branches

Constant Summary collapse

POST_CHECKOUT_MARKER_START =
"# >>> BEGIN ACTUAL_DB_SCHEMA"
POST_CHECKOUT_MARKER_END =
"# <<< END ACTUAL_DB_SCHEMA"
POST_CHECKOUT_HOOK_ROLLBACK =
<<~BASH
  #{POST_CHECKOUT_MARKER_START}
  # ActualDbSchema post-checkout hook (ROLLBACK)
  # Runs db:rollback_branches on branch checkout.

  # Check if this is a file checkout or creating a new branch
  if [ "$3" == "0" ] || [ "$1" == "$2" ]; then
    exit 0
  fi

  if [ -f ./bin/rails ]; then
    if [ -n "$ACTUAL_DB_SCHEMA_GIT_HOOKS_ENABLED" ]; then
      GIT_HOOKS_ENABLED="$ACTUAL_DB_SCHEMA_GIT_HOOKS_ENABLED"
    else
      GIT_HOOKS_ENABLED=$(./bin/rails runner "puts ActualDbSchema.config[:git_hooks_enabled]" 2>/dev/null)
    fi

    if [ "$GIT_HOOKS_ENABLED" == "true" ]; then
      ./bin/rails db:rollback_branches
    fi
  fi
  #{POST_CHECKOUT_MARKER_END}
BASH
POST_CHECKOUT_HOOK_MIGRATE =
<<~BASH
  #{POST_CHECKOUT_MARKER_START}
  # ActualDbSchema post-checkout hook (MIGRATE)
  # Runs db:migrate on branch checkout.

  # Check if this is a file checkout or creating a new branch
  if [ "$3" == "0" ] || [ "$1" == "$2" ]; then
    exit 0
  fi

  if [ -f ./bin/rails ]; then
    if [ -n "$ACTUAL_DB_SCHEMA_GIT_HOOKS_ENABLED" ]; then
      GIT_HOOKS_ENABLED="$ACTUAL_DB_SCHEMA_GIT_HOOKS_ENABLED"
    else
      GIT_HOOKS_ENABLED=$(./bin/rails runner "puts ActualDbSchema.config[:git_hooks_enabled]" 2>/dev/null)
    fi

    if [ "$GIT_HOOKS_ENABLED" == "true" ]; then
      ./bin/rails db:migrate
    fi
  fi
  #{POST_CHECKOUT_MARKER_END}
BASH

Constants included from OutputFormatter

OutputFormatter::UNICODE_COLORS

Instance Method Summary collapse

Methods included from OutputFormatter

#colorize

Constructor Details

#initialize(strategy: :rollback) ⇒ GitHooks

Returns a new instance of GitHooks.



61
62
63
# File 'lib/actual_db_schema/git_hooks.rb', line 61

def initialize(strategy: :rollback)
  @strategy = strategy
end

Instance Method Details

#install_post_checkout_hookObject



65
66
67
68
69
70
71
72
73
74
# File 'lib/actual_db_schema/git_hooks.rb', line 65

def install_post_checkout_hook
  return unless git_hooks_enabled?
  return unless hooks_directory_present?

  if File.exist?(hook_path)
    handle_existing_hook
  else
    create_new_hook
  end
end