railbow 0.7.0 → 0.8.1

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: cdfe578f284175c30e3b9f4c77a83f62b8e63b8019e575590f8ad471e5639efb
4
- data.tar.gz: 5874946340d18626a566b0190f734f6a94a55a3d40dfb0777760ab377b9d295d
3
+ metadata.gz: 713d22cda25eb21afdfb4ac61e708e969afbc280c18512524e84a1f40a1c72ee
4
+ data.tar.gz: 17129635e6ee556a82f60c2089892de13f9bc26833db3f8ad932056f572d943c
5
5
  SHA512:
6
- metadata.gz: 3fc62787e1bfd0913be00ca297c5c9210a312b067c68960c13699298a3a064e396a20bc952e65544d19059a03c02454c99413b8f59fd84e6890d9145e8ba03c1
7
- data.tar.gz: e2253cf2117f5ed4a6702f9500774789d05007876f09ad043b014f9e7b0d53f9616ea21fc32247463081e131aa533b2bf149cb65be99f8f08b37478a281e22ee
6
+ metadata.gz: 78029054749a650f9ac6317cc9bddd164c16ae75f5f8db65805731ba8431abe50750feb5113e120226bf60a114b80596afa1d41b6caef518e42180787b31f132
7
+ data.tar.gz: 77dd5665755697e5f8008300d65385adb0ca65f21aa916b5ace0aa216e43953cacf19248d9c4e1683a50cb09135795caea69177c74f4d8db498948f4d1dbf094
data/CHANGELOG.md CHANGED
@@ -5,6 +5,45 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [0.8.1] - 2026-11-11
9
+
10
+ ### Fixed
11
+
12
+ - The `⎇` branch badge in `db:migrate:status` no longer appears on a
13
+ base-branch migration while a rename of it is staged, for example one
14
+ renamed back to its original timestamp after a merge. An uncommitted new
15
+ file, staged or not, now counts as the branch's only when the merge-base
16
+ does not already hold it, so the uncommitted state and the committed state
17
+ agree. The same rule keeps such a migration out of a summarized database's
18
+ "on this branch" table.
19
+ - The Tables column shows a schema-qualified table as `reporting.events`
20
+ instead of just the schema, in the migration DSL (single-quoted strings
21
+ too) and in raw SQL, quoted parts included. A table in `public` shows by its bare name.
22
+ - Table detection now reads `CREATE INDEX ... ON [ONLY] <table>`,
23
+ `CREATE [MATERIALIZED] VIEW <name>` and `ALTER TABLE [IF EXISTS] [ONLY]
24
+ <table>` in raw SQL, so a migration made only of those no longer shows an
25
+ empty Tables column.
26
+
27
+ ## [0.8.0] - 2026-11-11
28
+
29
+ ### Added
30
+
31
+ - In a multi-database `db:migrate:status`, the migrations your branch adds
32
+ always show, whichever database they target and even outside the time
33
+ window. A drawn table gains the ones the window left out. A database that
34
+ would collapse to a summary line (summarized by `focus`, or quiet) shows a
35
+ table of just those, with a header like `1 on this branch of 40` that still
36
+ counts the pending and ghost migrations it hides. "Your branch" means added
37
+ since the merge-base with the base branch, or added and not committed yet,
38
+ and needs `diff` in `RBW_GIT` (on by default).
39
+
40
+ ### Fixed
41
+
42
+ - The `⎇` branch badge in `db:migrate:status` now appears for a migration
43
+ whose filename was introduced in a merge commit, for example one
44
+ re-timestamped while merging the base branch in. The origin lookup falls
45
+ back to a merge-aware `git log` when the plain one finds nothing.
46
+
8
47
  ## [0.7.0] - 2026-10-09
9
48
 
10
49
  ### Added
data/README.md CHANGED
@@ -103,7 +103,7 @@ Out of the box you get:
103
103
  - **Created At** - timestamp parsed from the migration ID
104
104
  - **Landing dates** - `⤻ Mar 04` badge when a migration was merged to main after its creation
105
105
  - **Branch badges** - `⎇ PS-142` showing the source branch/ticket
106
- - **Affected tables** - color-coded table names extracted from migration files
106
+ - **Affected tables** - color-coded table names extracted from migration files (a schema-qualified one shows as `schema.table`)
107
107
  - **Time filtering** - only the last 90 days shown by default (`since: 90d`), as a soft limit: never fewer than 10 migrations, however old (`since_min: 10`)
108
108
  - **Your migrations highlighted** - rows authored by you are visually distinct
109
109
  - **Pending migrations greyed out** - a `down` row keeps its status glyph but loses its colors
@@ -171,6 +171,23 @@ in full and every other one is summarized in a line each (`db: focus`).
171
171
  run is. The summary exists to hide what needs no action, and pending work is
172
172
  the opposite of that.
173
173
 
174
+ **Your branch's migrations always show**, whichever database they target and
175
+ however old they are. These are the migrations the checked-out branch adds:
176
+ committed since the merge-base with the base branch, or added and not committed
177
+ yet. A drawn table gains the ones the time window left out, and a database that
178
+ would be summarized keeps a table of just those. Its header still counts the
179
+ pending and ghost migrations the summary line would have named:
180
+
181
+ ```
182
+ ──── primary · myapp_development ──── 12 of 240 ────────────────────────
183
+ ↑↑ │ 20260721130000 │ 2026-07-21 13:00:00 │ Partition visit reminders ● visit_reminders
184
+
185
+ ──── log · log_development ──── 1 on this branch of 40 ──── 2 pending outside the 90d window - RBW_SINCE=all ────
186
+ ↑↑ │ 20260801100000 │ 2026-08-01 10:00:00 │ Add source to visit logs ● visit_logs
187
+ ```
188
+
189
+ This needs `diff` in `RBW_GIT`, which the default has.
190
+
174
191
  Setting `db` to an empty value expands every database that has recent activity,
175
192
  each as its own section with column widths shared so the tables line up:
176
193
 
data/lib/railbow/init.rb CHANGED
@@ -67,6 +67,8 @@ module Railbow
67
67
  # Multi-database runs (comma-separated). Leave empty ("") to expand every
68
68
  # database into its own section, in database.yml order; a database with
69
69
  # nothing in the time window collapses to a one-line summary either way.
70
+ # Migrations your branch adds always show, even outside the window, and a
71
+ # database that would be summarized lists just those (git: diff).
70
72
  # focus - expand only the first database, summarizing the rest.
71
73
  # A database with migrations pending is always expanded
72
74
  # only:<name> - render only this database (repeatable)
@@ -18,26 +18,47 @@ module Railbow
18
18
  add_foreign_key remove_foreign_key
19
19
  ].freeze
20
20
 
21
+ # A table name with an optional schema: `events` or `reporting.events`.
22
+ QUALIFIED_NAME = '(?:\w+\.)?\w+'
23
+
24
+ # A table argument: a symbol, or a string that may carry a schema. Two
25
+ # captures, one of them nil.
26
+ TABLE_ARG = /(?::(\w+)|["'](#{QUALIFIED_NAME}))/
27
+
21
28
  # Dual-table methods are included here too: their first argument is always a
22
29
  # table, even when the second is passed as `to_table:` instead of positionally.
23
- SINGLE_TABLE_PATTERN = /\b(?:#{(SINGLE_TABLE_METHODS + DUAL_TABLE_METHODS).join("|")})\s+[:"](\w+)/
24
- DUAL_TABLE_PATTERN = /\b(?:#{DUAL_TABLE_METHODS.join("|")})\s+[:"](\w+)["\s,]+[:"](\w+)/
30
+ SINGLE_TABLE_PATTERN = /\b(?:#{(SINGLE_TABLE_METHODS + DUAL_TABLE_METHODS).join("|")})\s+#{TABLE_ARG}/
31
+ DUAL_TABLE_PATTERN = /\b(?:#{DUAL_TABLE_METHODS.join("|")})\s+#{TABLE_ARG}["'\s,]+#{TABLE_ARG}/
32
+
33
+ # One part of a SQL name, quoted or bare. The backslash is the one a Ruby
34
+ # string puts before an inner quote. A closing quote is only taken with its
35
+ # opening one, so `"... FROM events".squish` does not read as a schema.
36
+ SQL_NAME_PART = /(?:\\?["'`]\w+\\?["'`]|\\?["'`]?\w+)/
37
+ SQL_TABLE = /(#{SQL_NAME_PART}(?:\.#{SQL_NAME_PART})?)/
38
+ SQL_QUOTING = "\\\\\"'`"
25
39
 
26
40
  SQL_TABLE_PATTERNS = [
27
- /\bUPDATE\s+["']?(\w+)["']?/i,
28
- /\bINSERT\s+INTO\s+["']?(\w+)["']?/i,
29
- /\bDELETE\s+FROM\s+["']?(\w+)["']?/i,
30
- /\bALTER\s+TABLE\s+["']?(\w+)["']?/i,
31
- /\bTRUNCATE\s+(?:TABLE\s+)?["']?(\w+)["']?/i,
32
- /\bDROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?["']?(\w+)["']?/i,
33
- /\bCREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?["']?(\w+)["']?/i
41
+ /\bUPDATE\s+#{SQL_TABLE}/i,
42
+ /\bINSERT\s+INTO\s+#{SQL_TABLE}/i,
43
+ /\bDELETE\s+FROM\s+#{SQL_TABLE}/i,
44
+ /\bALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?#{SQL_TABLE}/i,
45
+ /\bTRUNCATE\s+(?:TABLE\s+)?#{SQL_TABLE}/i,
46
+ /\bDROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?#{SQL_TABLE}/i,
47
+ /\bCREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?#{SQL_TABLE}/i,
48
+ # The index name is optional in Postgres, hence the optional word before ON.
49
+ /\bCREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:CONCURRENTLY\s+)?(?:IF\s+NOT\s+EXISTS\s+)?(?:\S+\s+)?ON\s+(?:ONLY\s+)?#{SQL_TABLE}/i,
50
+ /\bCREATE\s+(?:OR\s+REPLACE\s+)?(?:TEMP(?:ORARY)?\s+)?(?:MATERIALIZED\s+)?VIEW\s+(?:IF\s+NOT\s+EXISTS\s+)?#{SQL_TABLE}/i
34
51
  ].freeze
35
52
 
36
53
  # A table named by keyword argument, which catches project-level helpers
37
54
  # such as `convert_to_monthly_partitions(table: :apples)` whatever their
38
55
  # name. Not bare `from:`/`to:`: `change_column_default :users, :status,
39
- # from: nil, to: "active"` would yield phantom tables.
40
- KEYWORD_TABLE_PATTERN = /\b(?:table|to_table|from_table):\s*[:"']?(\w+)/
56
+ # from: nil, to: "active"` would yield phantom tables. Only a quoted value
57
+ # may carry a schema, so `table: apples.to_s` still reads as `apples`.
58
+ KEYWORD_TABLE_PATTERN = /\b(?:table|to_table|from_table):\s*(?:["'](#{QUALIFIED_NAME})|:?(\w+))/
59
+
60
+ # Postgres resolves a bare name to this schema, so the prefix says nothing.
61
+ DEFAULT_SCHEMA_PREFIX = "public."
41
62
 
42
63
  # Ruby `#` comments up to end of line, but not `#{}` interpolation.
43
64
  COMMENT_PATTERN = /#(?!\{).*/
@@ -75,12 +96,13 @@ module Railbow
75
96
 
76
97
  tables = []
77
98
 
78
- content.scan(SINGLE_TABLE_PATTERN) { |match| tables << match[0] }
79
- content.scan(DUAL_TABLE_PATTERN) { |match| tables.concat(match) }
99
+ content.scan(SINGLE_TABLE_PATTERN) { |match| tables.concat(match.compact) }
100
+ content.scan(DUAL_TABLE_PATTERN) { |match| tables.concat(match.compact) }
80
101
  SQL_TABLE_PATTERNS.each do |pattern|
81
- content.scan(pattern) { |match| tables << match[0] }
102
+ content.scan(pattern) { |match| tables << match[0].delete(SQL_QUOTING) }
82
103
  end
83
- content.scan(KEYWORD_TABLE_PATTERN) { |match| tables << match[0] }
104
+ content.scan(KEYWORD_TABLE_PATTERN) { |match| tables.concat(match.compact) }
105
+ tables.map! { |table| table.delete_prefix(DEFAULT_SCHEMA_PREFIX) }
84
106
  tables.uniq!
85
107
 
86
108
  # Model references are a guess (a constant answering these methods need
@@ -90,7 +112,8 @@ module Railbow
90
112
  content.scan(MODEL_REFERENCE_PATTERN) do |match|
91
113
  break if tables.size >= 2
92
114
  table = ActiveSupport::Inflector.tableize(match[0].split("::").last)
93
- tables << table unless tables.include?(table)
115
+ # A model has no schema, so it matches a found table of any schema.
116
+ tables << table unless tables.any? { |found| found.split(".").last == table }
94
117
  end
95
118
  end
96
119
 
@@ -13,6 +13,7 @@ module Railbow
13
13
  # authors, landing dates, originating branches and uncommitted files.
14
14
  class GitData
15
15
  EMPTY_AUTHORS = {names: {}, emails: {}}.freeze
16
+ PORCELAIN_KINDS = {"??" => :untracked, "A " => :added, "AM" => :added, "M " => :edited}.freeze
16
17
 
17
18
  attr_reader :migrate_dir, :author_names, :author_emails, :landed_dates,
18
19
  :git_email, :git_name, :branch_origins, :uncommitted_files,
@@ -43,6 +44,161 @@ module Railbow
43
44
  cache[[migrate_dir, opts]] ||= new(migrate_dir: migrate_dir, **opts)
44
45
  end
45
46
 
47
+ # Basenames of the migrations the checked-out branch adds over its base:
48
+ # committed since the merge-base, or added and not committed yet. Much
49
+ # cheaper than a full instance (no history walk, no origin lookup), so a
50
+ # database that is otherwise only summarized can afford to ask.
51
+ def self.branch_files(paths, base_override: "")
52
+ run_cached([:branch_files, paths, base_override]) do
53
+ files = Set.new(committed_branch_paths(paths, base_override).map { |f| File.basename(f) })
54
+ files.merge(uncommitted_branch_files(paths, base_override: base_override, additions_only: true))
55
+ end
56
+ end
57
+
58
+ # Paths of the migrations committed on this branch since it left its
59
+ # base. Shared with the origin badge, so the badge and the branch rows
60
+ # agree on which migrations are the branch's.
61
+ def self.committed_branch_paths(paths, base_override)
62
+ merge_base = merge_base(base_override)
63
+ return [] unless merge_base
64
+
65
+ diff_out, diff_status = Railbow::GitUtils.capture2(
66
+ "diff", "--name-status", "--diff-filter=AR", merge_base, "HEAD", "--", *paths
67
+ )
68
+ return [] unless diff_status.success?
69
+
70
+ diff_out.each_line.filter_map { |l| name_status_path(l.strip) }
71
+ end
72
+
73
+ def self.merge_base(base_override)
74
+ run_cached([:merge_base, base_override]) do
75
+ out, status = Railbow::GitUtils.capture2("merge-base", "HEAD", default_branch(base_override))
76
+ status.success? ? out.strip : nil
77
+ end
78
+ end
79
+
80
+ # Memoized for the rest of a multi-database run, so per-database calls
81
+ # share what does not depend on the database. Outside a run, no cache.
82
+ def self.run_cached(key)
83
+ cache = Railbow::MultiDb.current&.git_cache
84
+ return yield unless cache
85
+ return cache[key] if cache.key?(key)
86
+
87
+ cache[key] = yield
88
+ end
89
+
90
+ def self.default_branch(override)
91
+ return override if override && !override.empty?
92
+
93
+ run_cached([:default_branch]) { detect_default_branch }
94
+ end
95
+
96
+ def self.detect_default_branch
97
+ output, status = Railbow::GitUtils.capture2("symbolic-ref", "refs/remotes/origin/HEAD")
98
+ if status.success?
99
+ branch = output.strip.sub(%r{^refs/remotes/origin/}, "")
100
+ return branch unless branch.empty?
101
+ end
102
+
103
+ %w[main master].each do |candidate|
104
+ _, st = Railbow::GitUtils.capture2("rev-parse", "--verify", "refs/heads/#{candidate}")
105
+ return candidate if st.success?
106
+ end
107
+
108
+ "main"
109
+ end
110
+
111
+ # --name-status lines are "A\tfilepath" or "Rnnn\told\tnew"; a rename
112
+ # attributes to its destination.
113
+ def self.name_status_path(line)
114
+ cols = line.split("\t")
115
+ filepath = cols[0]&.start_with?("R") ? cols[2] : cols[1]
116
+ (filepath.nil? || filepath.empty?) ? nil : filepath
117
+ end
118
+
119
+ def self.name_status_basename(line)
120
+ filepath = name_status_path(line)
121
+ filepath && File.basename(filepath)
122
+ end
123
+
124
+ # Every migration with an uncommitted change, whoever it belongs to.
125
+ # Files an in-progress merge brings in from MERGE_HEAD show up as staged
126
+ # additions, so they are left out.
127
+ def self.uncommitted_files(paths, entries: porcelain_entries(paths))
128
+ Set.new(entries.map(&:last)) - incoming_merge_files(paths)
129
+ end
130
+
131
+ # The uncommitted migrations that are the branch's own work. A new file,
132
+ # staged or untracked, counts only when the merge-base does not hold it:
133
+ # a base-branch migration renamed back to its own name is new against
134
+ # HEAD, but adds nothing to the branch. A staged edit belongs to the
135
+ # branch for the badge, but with additions_only it is not a migration the
136
+ # branch adds.
137
+ def self.uncommitted_branch_files(paths, base_override: "", additions_only: false, entries: porcelain_entries(paths))
138
+ in_base = base_files(paths, base_override) if entries.any? { |kind, _| kind != :edited }
139
+
140
+ mine = entries.filter_map do |kind, basename|
141
+ keep =
142
+ case kind
143
+ when :edited then !additions_only
144
+ # Without a merge-base there is nothing to compare against.
145
+ else in_base.nil? || !in_base.include?(basename)
146
+ end
147
+ basename if keep
148
+ end
149
+
150
+ Set.new(mine) - incoming_merge_files(paths)
151
+ end
152
+
153
+ # [kind, basename] per `git status --porcelain` line worth knowing about:
154
+ # :untracked, :added (staged addition or rename) or :edited (staged edit).
155
+ def self.porcelain_entries(paths)
156
+ output, status = Railbow::GitUtils.capture2("status", "--porcelain", "--", *paths)
157
+ return [] unless status.success?
158
+
159
+ output.each_line.filter_map do |line|
160
+ code = line[0..1]
161
+
162
+ if code[0] == "R"
163
+ # Rename: "R old -> new". Take the destination.
164
+ parts = line[3..].split(" -> ", 2)
165
+ kind = :added
166
+ filepath = (parts[1] || parts[0]).strip
167
+ else
168
+ kind = PORCELAIN_KINDS[code]
169
+ next unless kind
170
+
171
+ filepath = line[3..].strip
172
+ end
173
+
174
+ [kind, File.basename(filepath)] unless filepath.empty?
175
+ end
176
+ end
177
+
178
+ # Basenames of the migrations the merge-base holds, or nil when there is
179
+ # no merge-base to compare with.
180
+ def self.base_files(paths, base_override)
181
+ merge_base = merge_base(base_override)
182
+ return nil unless merge_base
183
+
184
+ run_cached([:base_files, merge_base, paths]) do
185
+ out, status = Railbow::GitUtils.capture2("ls-tree", "-r", "--name-only", merge_base, "--", *paths)
186
+ status.success? ? Set.new(out.each_line.map { |l| File.basename(l.strip) }) : nil
187
+ end
188
+ end
189
+
190
+ def self.incoming_merge_files(paths)
191
+ merging = run_cached([:merging]) { Railbow::GitUtils.capture3("rev-parse", "MERGE_HEAD")[2].success? }
192
+ return Set.new unless merging
193
+
194
+ output, _, status = Railbow::GitUtils.capture3(
195
+ "diff", "--name-only", "--diff-filter=AR", "HEAD", "MERGE_HEAD", "--", *paths
196
+ )
197
+ return Set.new unless status.success?
198
+
199
+ Set.new(output.each_line.map { |l| File.basename(l.strip) }.reject(&:empty?))
200
+ end
201
+
46
202
  # Extracts a display label from a branch name. "auto" uses the built-in
47
203
  # ticket pattern; anything else is a regex whose first capture wins.
48
204
  def self.apply_branch_mask(branch, branch_mask)
@@ -84,12 +240,16 @@ module Railbow
84
240
  @branch_origins = branch_migration_origins(base_branch, branch_mask)
85
241
  @incoming_merge_files = incoming_merge_files_from_git
86
242
  @merge_source_label = detect_merge_source_label(branch_mask) if @incoming_merge_files.any?
87
- @uncommitted_files = uncommitted_migration_files
243
+ entries = self.class.porcelain_entries([migrate_dir])
244
+ @uncommitted_files = self.class.uncommitted_files([migrate_dir], entries: entries)
245
+
246
+ # The branch's uncommitted files have no commit to attribute, so they
247
+ # belong to whatever branch is checked out right now.
248
+ mine = self.class.uncommitted_branch_files([migrate_dir], base_override: base_branch, entries: entries)
249
+ return if mine.empty?
88
250
 
89
- # Uncommitted files have no commit to attribute, so they belong to
90
- # whatever branch is checked out right now.
91
251
  current_branch = current_branch_name(branch_mask)
92
- @uncommitted_files.each { |f| @branch_origins[f] ||= current_branch }
252
+ mine.each { |f| @branch_origins[f] ||= current_branch }
93
253
  end
94
254
 
95
255
  def migration_authors
@@ -145,12 +305,8 @@ module Railbow
145
305
  dates
146
306
  end
147
307
 
148
- # --name-status lines are "A\tfilepath" or "Rnnn\told\tnew"; a rename
149
- # attributes to its destination.
150
308
  def name_status_basename(line)
151
- cols = line.split("\t")
152
- filepath = cols[0]&.start_with?("R") ? cols[2] : cols[1]
153
- filepath ? File.basename(filepath) : nil
309
+ self.class.name_status_basename(line)
154
310
  end
155
311
 
156
312
  def current_git_email
@@ -171,36 +327,11 @@ module Railbow
171
327
  end
172
328
 
173
329
  def detect_default_branch(override)
174
- return override if override && !override.empty?
175
-
176
- output, status = Railbow::GitUtils.capture2("symbolic-ref", "refs/remotes/origin/HEAD")
177
- if status.success?
178
- branch = output.strip.sub(%r{^refs/remotes/origin/}, "")
179
- return branch unless branch.empty?
180
- end
181
-
182
- %w[main master].each do |candidate|
183
- _, st = Railbow::GitUtils.capture2("rev-parse", "--verify", "refs/heads/#{candidate}")
184
- return candidate if st.success?
185
- end
186
-
187
- "main"
330
+ self.class.default_branch(override)
188
331
  end
189
332
 
190
333
  def branch_migration_origins(base_branch, branch_mask)
191
- merge_base_out, mb_status = Railbow::GitUtils.capture2("merge-base", "HEAD", base_branch)
192
- return {} unless mb_status.success?
193
-
194
- merge_base = merge_base_out.strip
195
- diff_out, diff_status = Railbow::GitUtils.capture2(
196
- "diff", "--name-status", "--diff-filter=AR", merge_base, "HEAD", "--", migrate_dir
197
- )
198
- return {} unless diff_status.success?
199
-
200
- files = diff_out.each_line.map { |l|
201
- cols = l.strip.split("\t")
202
- cols[0]&.start_with?("R") ? cols[2] : cols[1]
203
- }.compact.reject(&:empty?)
334
+ files = self.class.committed_branch_paths([migrate_dir], base_branch)
204
335
  origins = {}
205
336
 
206
337
  files.each do |filepath|
@@ -218,14 +349,27 @@ module Railbow
218
349
  origins
219
350
  end
220
351
 
352
+ # The commit that first produced this filename. A plain log shows no diff
353
+ # for a merge commit, so a file named inside one (a migration
354
+ # re-timestamped while merging the base branch in) needs the -m form,
355
+ # oldest match first. -m stays a fallback: a later "merge main into
356
+ # feature" commit lists every main migration as added against one parent,
357
+ # and pick_origin_branch would then label those with the base branch.
221
358
  def adding_commit(filepath)
222
- commit_out, cs = Railbow::GitUtils.capture2(
223
- "log", "--diff-filter=AR", "--format=%H", "-1", "--", filepath
359
+ commits = commits_touching(filepath, "-1")
360
+ return nil if commits.nil?
361
+ return commits.first if commits.any?
362
+
363
+ commits_touching(filepath, "-m")&.last
364
+ end
365
+
366
+ def commits_touching(filepath, *flags)
367
+ out, status = Railbow::GitUtils.capture2(
368
+ "log", "--diff-filter=AR", "--format=%H", *flags, "--", filepath
224
369
  )
225
- return nil unless cs.success?
370
+ return nil unless status.success?
226
371
 
227
- commit = commit_out.strip
228
- commit.empty? ? nil : commit
372
+ out.each_line.map(&:strip).reject(&:empty?)
229
373
  end
230
374
 
231
375
  def branches_containing(commit)
@@ -259,32 +403,6 @@ module Railbow
259
403
  end
260
404
  end
261
405
 
262
- def uncommitted_migration_files
263
- output, status = Railbow::GitUtils.capture2("status", "--porcelain", "--", migrate_dir)
264
- return Set.new unless status.success?
265
-
266
- result = Set.new
267
- output.each_line do |line|
268
- code = line[0..1]
269
-
270
- if code[0] == "R"
271
- # Rename: "R old -> new" or "R100 old -> new". Take the destination.
272
- parts = line[3..].split(" -> ", 2)
273
- filepath = (parts[1] || parts[0]).strip
274
- elsif ["??", "A ", "AM", "M "].include?(code)
275
- filepath = line[3..].strip
276
- else
277
- next
278
- end
279
-
280
- result << File.basename(filepath) unless filepath.empty?
281
- end
282
-
283
- # During an in-progress merge, files from MERGE_HEAD (e.g. main) show up
284
- # as staged additions. Exclude them so they are not tagged as ours.
285
- result - incoming_merge_files_from_git
286
- end
287
-
288
406
  def detect_merge_source_label(branch_mask)
289
407
  merge_head, _, status = Railbow::GitUtils.capture3("rev-parse", "MERGE_HEAD")
290
408
  return nil unless status.success?
@@ -305,15 +423,7 @@ module Railbow
305
423
  end
306
424
 
307
425
  def incoming_merge_files_from_git
308
- _, _, mh_status = Railbow::GitUtils.capture3("rev-parse", "MERGE_HEAD")
309
- return Set.new unless mh_status.success?
310
-
311
- output, _, status = Railbow::GitUtils.capture3(
312
- "diff", "--name-only", "--diff-filter=AR", "HEAD", "MERGE_HEAD", "--", migrate_dir
313
- )
314
- return Set.new unless status.success?
315
-
316
- Set.new(output.each_line.map { |l| File.basename(l.strip) }.reject(&:empty?))
426
+ self.class.incoming_merge_files([migrate_dir])
317
427
  end
318
428
  end
319
429
  end
@@ -69,7 +69,10 @@ module Railbow
69
69
  with column widths shared so the tables
70
70
  line up. Databases sharing a migrations
71
71
  path (shards) merge into one table with a
72
- status per database.
72
+ status per database. Migrations your branch
73
+ adds always show, even outside the window,
74
+ and a summarized database lists just those
75
+ (needs RBW_GIT=diff).
73
76
  focus - expand only the first
74
77
  database, summarizing the
75
78
  rest in a line each. A
@@ -29,6 +29,7 @@ module Railbow
29
29
  def print
30
30
  return print_solo(sections.first) if solo?
31
31
 
32
+ apply_branch_rows
32
33
  print_overview
33
34
  Railbow::Params.db_inline? ? print_inline : print_sections
34
35
  print_skipped
@@ -202,11 +203,22 @@ module Railbow
202
203
  puts formatter.dim("#{COLLAPSED} #{count_label(skipped.size, "database")} hidden: #{skipped.join(", ")}")
203
204
  end
204
205
 
206
+ # Your own migrations show up whichever database they target and however
207
+ # old they are: a drawn table gains the ones the time window left out, and
208
+ # a database that would collapse keeps a table of just those.
209
+ def apply_branch_rows
210
+ sections.each do |section|
211
+ next if section.branch_versions.empty?
212
+
213
+ collapse?(section) ? section.narrow_to_branch! : section.include_branch!
214
+ end
215
+ end
216
+
205
217
  # A quiet database has no table to draw, so one line says it all.
206
218
  # RBW_DB=focus collapses all but the first database too, unless one has
207
219
  # migrations pending.
208
220
  def collapse?(section)
209
- return false if Railbow::Params.db_full?
221
+ return false if Railbow::Params.db_full? || section.branch_only?
210
222
  return true if section.quiet?
211
223
  # Focus would empty the inline table of every database but the first.
212
224
  return false if Railbow::Params.db_inline?
@@ -241,13 +253,29 @@ module Railbow
241
253
  end
242
254
  end
243
255
 
256
+ # What a narrowed section's summary line would have warned about: pending
257
+ # or ghost migrations among the rows it does not draw.
258
+ def hidden_outside(section)
259
+ parts = []
260
+ parts << "#{section.hidden_pending_count} pending" if section.hidden_pending_count > 0
261
+ parts << count_label(section.hidden_ghost_count, "ghost") if section.hidden_ghost_count > 0
262
+ return nil if parts.empty?
263
+
264
+ "#{parts.join(", ")} outside the #{section.since_value} window - RBW_SINCE=all"
265
+ end
266
+
244
267
  # "──── primary · pawshop-dev ──── 12 of 240 ────", ruled out to where
245
268
  # the last column starts so it frames the table rather than floating.
246
269
  def section_header(section, rule_width)
247
270
  label = section.db_names.join(" + ")
248
271
  detail = section.sharded? ? shared_path(section) : section.database
249
272
  head = "#{RULE * 4} #{label} · #{detail} "
250
- head += "#{RULE * 4} #{shown_count(section)} of #{section.total_count} " if section.hidden_count > 0
273
+ if section.branch_only?
274
+ head += "#{RULE * 4} #{section.rows.size} on this branch of #{section.total_count} "
275
+ head += "#{RULE * 4} #{hidden_outside(section)} " if hidden_outside(section)
276
+ elsif section.hidden_count > 0
277
+ head += "#{RULE * 4} #{shown_count(section)} of #{section.total_count} "
278
+ end
251
279
 
252
280
  width = (rule_width > 0) ? rule_width : DEFAULT_RULE_WIDTH
253
281
  if (term = terminal_width)
@@ -52,6 +52,8 @@ module Railbow
52
52
  @databases = [{name: pool.db_config.name, database: pool.db_config.database}]
53
53
  @migrations_key = migrations_key_for(pool)
54
54
  @entries = {}
55
+ @all_entries = {}
56
+ @version_to_file = {}
55
57
  @ghosts = {}
56
58
  @hidden_count = 0
57
59
  @total_count = 0
@@ -82,11 +84,9 @@ module Railbow
82
84
  # Folds in another database running the same migration files. Anything
83
85
  # already built is discarded.
84
86
  def merge!(other)
85
- other.entries.each do |version, entry|
86
- mine = (@entries[version] ||= {name: entry[:name], statuses: {}})
87
- mine[:name] = entry[:name] if mine[:name].include?(NO_FILE)
88
- mine[:statuses].merge!(entry[:statuses])
89
- end
87
+ merge_entries(@entries, other.entries)
88
+ merge_entries(@all_entries, other.all_entries)
89
+ @version_to_file = other.version_to_file.merge(@version_to_file)
90
90
  @databases.concat(other.databases)
91
91
  @fallback_output = [fallback_output, other.fallback_output].compact.join
92
92
  @ghosts = other.ghosts.merge(@ghosts)
@@ -104,6 +104,57 @@ module Railbow
104
104
  databases.size > 1
105
105
  end
106
106
 
107
+ # Versions the checked-out branch adds to this database, wherever they
108
+ # fall relative to the time window. Needs RBW_GIT=diff, which is what
109
+ # already makes railbow branch-aware.
110
+ def branch_versions
111
+ return @branch_versions if @branch_versions
112
+ return @branch_versions = [] unless Railbow::Params.git_diff?
113
+
114
+ files = GitData.branch_files(migrations_key, base_override: Railbow::Params.git_base)
115
+ @branch_versions = @all_entries.keys.select do |version|
116
+ file = version_to_file[version]
117
+ file && files.include?(File.basename(file))
118
+ end.sort
119
+ end
120
+
121
+ # Adds the branch's migrations the time window left out, so a drawn
122
+ # table never hides your own work.
123
+ def include_branch!
124
+ missing = branch_versions - @entries.keys
125
+ return self if missing.empty?
126
+
127
+ @entries = @entries.merge(@all_entries.slice(*missing))
128
+ @hidden_count -= missing.size
129
+ reset_built
130
+ self
131
+ end
132
+
133
+ # Keeps only the branch's migrations, for a database that would otherwise
134
+ # collapse to a summary line.
135
+ def narrow_to_branch!
136
+ @entries = @all_entries.slice(*branch_versions)
137
+ @hidden_count = total_count - @entries.size
138
+ @floor_applied = false
139
+ @branch_only = true
140
+ reset_built
141
+ self
142
+ end
143
+
144
+ def branch_only?
145
+ @branch_only == true
146
+ end
147
+
148
+ # Pending migrations not among the rows drawn. A narrowed section still
149
+ # owes the reader what its summary line would have said.
150
+ def hidden_pending_count
151
+ pending_count - entries.count { |_, e| e[:statuses].value?("down") }
152
+ end
153
+
154
+ def hidden_ghost_count
155
+ ghost_count - entries.count { |_, e| e[:name].to_s.include?(NO_FILE) }
156
+ end
157
+
107
158
  # Answered from collected entries, so it costs no git work: it is asked
108
159
  # to decide whether to build the rows at all.
109
160
  def pending_in_view?
@@ -130,6 +181,12 @@ module Railbow
130
181
 
131
182
  attr_reader :latest_applied_version
132
183
 
184
+ protected
185
+
186
+ attr_reader :all_entries, :version_to_file
187
+
188
+ public
189
+
133
190
  def latest_applied_date
134
191
  version_date(latest_applied_version) if latest_applied_version
135
192
  end
@@ -166,7 +223,7 @@ module Railbow
166
223
 
167
224
  private
168
225
 
169
- attr_reader :formatter, :git, :version_to_file
226
+ attr_reader :formatter, :git
170
227
 
171
228
  def migrations_key_for(pool)
172
229
  paths = Array(pool.migration_context.migrations_paths)
@@ -181,6 +238,20 @@ module Railbow
181
238
  @built = false
182
239
  end
183
240
 
241
+ def merge_entries(into, from)
242
+ from.each do |version, entry|
243
+ mine = (into[version] ||= {name: entry[:name], statuses: {}})
244
+ mine[:name] = entry[:name] if mine[:name].include?(NO_FILE)
245
+ mine[:statuses].merge!(entry[:statuses])
246
+ end
247
+ end
248
+
249
+ def entries_for(db_list)
250
+ db_list.to_h do |status, version, name|
251
+ [version.to_s, {name: name, statuses: {db_name => status}}]
252
+ end
253
+ end
254
+
184
255
  def collect(pool)
185
256
  db_list = pool.migration_context.migrations_status
186
257
  @total_count = db_list.size
@@ -191,22 +262,20 @@ module Railbow
191
262
  return
192
263
  end
193
264
 
265
+ # The whole list, unfiltered: a summarized database can still show the
266
+ # branch's migrations, and those may sit outside the window.
267
+ @all_entries = entries_for(db_list)
268
+ pool.migration_context.migrations.each do |m|
269
+ @version_to_file[m.version.to_s] = m.filename
270
+ end
271
+
194
272
  db_list = apply_since_filter(db_list)
195
273
 
196
274
  # State tracks recency, not row count: a section whose only rows were
197
275
  # pulled in by the floor still has nothing recent to say, and should
198
276
  # still collapse in a multi-database run.
199
277
  @state = @window_count.zero? ? :none_in_period : :ok
200
- return if db_list.empty?
201
-
202
- @entries = db_list.to_h do |status, version, name|
203
- [version.to_s, {name: name, statuses: {db_name => status}}]
204
- end
205
-
206
- @version_to_file = {}
207
- pool.migration_context.migrations.each do |m|
208
- @version_to_file[m.version.to_s] = m.filename
209
- end
278
+ @entries = entries_for(db_list)
210
279
  end
211
280
 
212
281
  # Counted over every migration, not just the ones in the window, so a
@@ -287,8 +356,9 @@ module Railbow
287
356
  @tables_enabled = Railbow::Params.view_tables?
288
357
  end
289
358
 
290
- # Git lookups and ghost recovery happen here rather than during collect,
291
- # so a section that ends up collapsed never pays for them.
359
+ # Git history lookups and ghost recovery happen here rather than during
360
+ # collect, so a section that ends up collapsed never pays for them. It
361
+ # pays only the cheap branch lookup (#branch_versions).
292
362
  def build!
293
363
  @built = true
294
364
  @columns = []
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Railbow
4
- VERSION = "0.7.0"
4
+ VERSION = "0.8.1"
5
5
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: railbow
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.7.0
4
+ version: 0.8.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Eugene M