Class: PreCommit::MigrationCheck

Inherits:
Object
  • Object
show all
Defined in:
lib/pre-commit/checks/migration_check.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#error_messageObject

Returns the value of attribute error_message.



4
5
6
# File 'lib/pre-commit/checks/migration_check.rb', line 4

def error_message
  @error_message
end

Instance Method Details

#callObject



6
7
8
9
10
11
12
13
14
15
# File 'lib/pre-commit/checks/migration_check.rb', line 6

def call
  staged_files = load_staged_files
  run(staged_files)

  if !passed? && error_message
    $stderr.puts "pre-commit: #{error_message}"
  end

  passed?
end

#load_staged_filesObject



50
51
52
# File 'lib/pre-commit/checks/migration_check.rb', line 50

def load_staged_files
  Utils.staged_files('.').split(" ")
end

#migration_file_present?(staged_files) ⇒ Boolean

Returns:

  • (Boolean)


32
33
34
# File 'lib/pre-commit/checks/migration_check.rb', line 32

def migration_file_present?(staged_files)
  staged_files.any? { |file| file =~ /db\/migrate\/.*\.rb/ }
end

#passed?Boolean

Returns:

  • (Boolean)


46
47
48
# File 'lib/pre-commit/checks/migration_check.rb', line 46

def passed?
  @passed
end

#run(staged_files) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/pre-commit/checks/migration_check.rb', line 17

def run(staged_files)
  migration_present = migration_file_present?(staged_files)
  schema_change = schema_file_present?(staged_files)

  if migration_present && !schema_change
    @error_message = "It looks like you're adding a migration, but did not update the schema file"
    @passed = false
  elsif schema_change && !migration_present
    @error_message = "You're trying to change the schema without adding a migration file"
    @passed = false
  else
    @passed = true
  end
end

#schema_file_present?(staged_files) ⇒ Boolean

Returns:

  • (Boolean)


36
37
38
39
40
41
42
43
44
# File 'lib/pre-commit/checks/migration_check.rb', line 36

def schema_file_present?(staged_files)
  staged_files.any? do |file|
    basename = File.basename(file)

    [/schema\.rb/i, /structure.*\.sql/].any? do |regex|
      basename =~ regex
    end
  end
end