|
3 | 3 | module PreCommit |
4 | 4 | module Checks |
5 | 5 | class Migration < Plugin |
| 6 | + VERSION_PATTERN = /(\d{14})/ |
| 7 | + |
| 8 | + self::VersionedFile = Struct.new(:file, :version) do |
| 9 | + alias_method :to_s, :file |
| 10 | + end |
| 11 | + |
6 | 12 | def self.aliases |
7 | 13 | [:migrations] |
8 | 14 | end |
9 | 15 |
|
10 | 16 | def call(staged_files) |
11 | | - migration_files = migration_files(staged_files) |
12 | | - schema_files = schema_files(staged_files) |
| 17 | + migration_files = versioned_migration_files(staged_files) |
| 18 | + schema_files = versioned_schema_files(staged_files) |
13 | 19 |
|
14 | 20 | if migration_files.any? && schema_files.none? |
15 | 21 | "It looks like you're adding a migration, but did not update the schema file" |
16 | 22 | elsif migration_files.none? && schema_files.any? |
17 | 23 | "You're trying to change the schema without adding a migration file" |
18 | 24 | elsif migration_files.any? && schema_files.any? |
19 | | - versions = migration_files.map { |f| f[/\d+/] } |
20 | | - schema = schema_files.map { |f| File.read(f) }.join |
21 | | - missing_versions = versions.select { |version| !schema.include?(version) } |
| 25 | + migration_versions = migration_files.map(&:version) |
| 26 | + missing_versions = migration_versions - schema_files.map(&:version) |
22 | 27 | if missing_versions.any? |
23 | | - "You did not add the schema versions for #{versions.join(', ')} to #{schema_files.join(' or ')}" |
| 28 | + "You did not add the schema versions for "\ |
| 29 | + "#{migration_versions.join(', ')} to #{schema_files.join(' or ')}" |
24 | 30 | end |
25 | 31 | end |
26 | 32 | end |
27 | 33 |
|
28 | 34 | private |
29 | 35 |
|
30 | | - def migration_files(staged_files) |
31 | | - staged_files.grep(/db\/migrate\/.*\.rb/) |
| 36 | + def versioned_migration_files(staged_files) |
| 37 | + files = staged_files.grep(/db\/migrate\/.*\.rb/) |
| 38 | + |
| 39 | + files.each_with_object([]) do |f, result| |
| 40 | + if f =~ VERSION_PATTERN |
| 41 | + result << VersionedFile.new(f, $1) |
| 42 | + end |
| 43 | + end |
32 | 44 | end |
33 | 45 |
|
34 | | - def schema_files(staged_files) |
35 | | - staged_files.select { |f| File.basename(f) =~ /schema\.rb|structure.*\.sql/ } |
| 46 | + def versioned_schema_files(staged_files) |
| 47 | + files = staged_files.select do |f| |
| 48 | + File.basename(f) =~ /schema\.rb|structure.*\.sql/ |
| 49 | + end |
| 50 | + |
| 51 | + files.each_with_object([]) do |f, result| |
| 52 | + if IO.read(f) =~ VERSION_PATTERN |
| 53 | + result << VersionedFile.new(f, $1) |
| 54 | + end |
| 55 | + end |
36 | 56 | end |
37 | 57 |
|
38 | 58 | def self.description |
|
0 commit comments