agent-lock 3.1.0 → 4.0.0

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.
Files changed (64) hide show
  1. checksums.yaml +4 -4
  2. data/.gitleaks.toml +23 -0
  3. data/AGENTS.md +11 -17
  4. data/CHANGELOG.md +124 -3
  5. data/README.md +496 -100
  6. data/Rakefile +13 -6
  7. data/docs/badges/coverage_badge.svg +21 -0
  8. data/docs/badges/yardoc.svg +1 -0
  9. data/docs/img/alock-sequence.avif +0 -0
  10. data/docs/img/alock-sequence.md +29 -0
  11. data/docs/img/alock-sequence.png +0 -0
  12. data/lefthook.yml +39 -0
  13. data/lib/agent/lock/cli/commands/acquire.rb +25 -19
  14. data/lib/agent/lock/cli/commands/base.rb +59 -23
  15. data/lib/agent/lock/cli/commands/break.rb +12 -7
  16. data/lib/agent/lock/cli/commands/check.rb +10 -9
  17. data/lib/agent/lock/cli/commands/completion.rb +15 -32
  18. data/lib/agent/lock/cli/commands/list.rb +46 -37
  19. data/lib/agent/lock/cli/commands/listing.rb +170 -0
  20. data/lib/agent/lock/cli/commands/mine.rb +7 -5
  21. data/lib/agent/lock/cli/commands/note.rb +13 -9
  22. data/lib/agent/lock/cli/commands/release.rb +10 -7
  23. data/lib/agent/lock/cli/commands/release_all.rb +7 -5
  24. data/lib/agent/lock/cli/commands/resume.rb +13 -7
  25. data/lib/agent/lock/cli/commands/show.rb +172 -0
  26. data/lib/agent/lock/cli/commands/skills.rb +28 -19
  27. data/lib/agent/lock/cli/commands/switch_backend.rb +205 -0
  28. data/lib/agent/lock/cli/commands/tree_command.rb +72 -0
  29. data/lib/agent/lock/cli/commands/version.rb +2 -1
  30. data/lib/agent/lock/cli/commands/whoami.rb +7 -3
  31. data/lib/agent/lock/cli.rb +63 -19
  32. data/lib/agent/lock/error.rb +52 -1
  33. data/lib/agent/lock/facade/async.rb +83 -0
  34. data/lib/agent/lock/facade/backend.rb +133 -0
  35. data/lib/agent/lock/facade/memo.rb +30 -0
  36. data/lib/agent/lock/facade/refusal.rb +78 -0
  37. data/lib/agent/lock/facade/session.rb +142 -0
  38. data/lib/agent/lock/facade/strategies.rb +36 -0
  39. data/lib/agent/lock/facade.rb +369 -0
  40. data/lib/agent/lock/freeze.rb +59 -5
  41. data/lib/agent/lock/identity.rb +63 -5
  42. data/lib/agent/lock/launcher.rb +17 -1
  43. data/lib/agent/lock/manager/enforcement.rb +98 -0
  44. data/lib/agent/lock/manager/switch.rb +91 -0
  45. data/lib/agent/lock/manager/thaw.rb +68 -0
  46. data/lib/agent/lock/manager.rb +176 -79
  47. data/lib/agent/lock/process_info/legacy_start.rb +60 -0
  48. data/lib/agent/lock/process_info.rb +42 -11
  49. data/lib/agent/lock/record.rb +124 -10
  50. data/lib/agent/lock/scope.rb +49 -4
  51. data/lib/agent/lock/skill.rb +14 -10
  52. data/lib/agent/lock/store/backend_name.rb +62 -0
  53. data/lib/agent/lock/store/file_system_store.rb +20 -1
  54. data/lib/agent/lock/store/redis_index.rb +179 -0
  55. data/lib/agent/lock/store/redis_store.rb +191 -33
  56. data/lib/agent/lock/store.rb +180 -19
  57. data/lib/agent/lock/text.rb +62 -0
  58. data/lib/agent/lock/tree.rb +143 -16
  59. data/lib/agent/lock/version.rb +2 -1
  60. data/lib/agent/lock.rb +3 -0
  61. data/skills/agent-lock/SKILL.md +75 -10
  62. metadata +41 -22
  63. data/justfile +0 -127
  64. data/sig/agent/lock.rbs +0 -6
@@ -1,34 +1,35 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require_relative "base"
3
+ require_relative "listing"
4
+ require_relative "tree_command"
4
5
 
5
6
  module Agent
6
7
  module Lock
7
8
  module CLI
8
9
  module Commands
9
- # Everything in this tree's store, worktree siblings included, since
10
- # they share one `.git` and therefore one set of locks.
11
- #
12
- # Live claims and interrupted work are listed apart. An orphan blocks
13
- # nobody, so counting it as held told a reader the tree was busier
14
- # than it was, and gave them no way to see which locks were real.
15
- class List < Base
16
- desc "Every live lock, and any interrupted work"
10
+ # Every lock in this repository. Another repository's locks are not
11
+ # this command's, even when they share a Redis.
12
+ class List < TreeCommand
13
+ desc "Every lock in this repository"
17
14
 
18
- option :json, type: :boolean, default: false, desc: "Machine-readable output"
15
+ option :json, type: :boolean, default: false, desc: "Print every record as JSON, with status and stale"
16
+ option :notes, type: :boolean, default: false,
17
+ desc: "Print each lock's progress notes on the row under it"
19
18
 
20
- example ["", "--json"]
19
+ example ["", "--notes", "--json"]
21
20
 
22
- # @param options [Hash]
21
+ # @param options [Hash] `:dir`, `:locking_strategy`, `:redis_url`, `:json`, `:notes`
23
22
  # @return [Manager::Result]
24
23
  def call(**options)
25
- manager = manager(options[:dir])
24
+ manager = manager(options)
26
25
  result = manager.list
26
+ records = result.records.select { |record| this_repo?(record, manager.tree) }
27
27
 
28
+ name_store(manager.store)
28
29
  if options[:json]
29
- report_records(result.records, json: true, stale_minutes: manager.stale_minutes)
30
+ report_records(records, json: true, stale_minutes: manager.stale_minutes)
30
31
  else
31
- report_listing(result.records, manager.stale_minutes)
32
+ report_listing(records, manager, notes: options[:notes])
32
33
  end
33
34
 
34
35
  finish(result)
@@ -36,33 +37,41 @@ module Agent
36
37
 
37
38
  private
38
39
 
39
- # @param records [Array<Record>]
40
- # @param stale_minutes [Integer]
41
- def report_listing(records, stale_minutes)
42
- held, interrupted = records.partition(&:active?)
40
+ # An empty listing reads the same for "nothing is held" and for "this
41
+ # is not the store the others write to", and a REDIS_URL that does not
42
+ # answer falls back to another Redis without a word. On STDERR, and
43
+ # with `--json` too, so what goes down a pipe is the listing alone and
44
+ # the JSON stays the array it was. The Redis URL is masked by
45
+ # {Store::RedisStore#describe}.
46
+ #
47
+ # @param store [Store::FileSystemStore, Store::RedisStore]
48
+ # @return [void]
49
+ def name_store(store) = warn_("store: #{store.describe}")
43
50
 
44
- if held.empty?
45
- say("No locks held.")
46
- else
47
- say("Locks held (#{held.size}):")
48
- report_records(held, json: false, stale_minutes: stale_minutes)
49
- end
51
+ # A record with no repository recorded was written before that
52
+ # field existed, into this checkout's own store.
53
+ #
54
+ # @param record [Record]
55
+ # @param tree [Tree]
56
+ # @return [Boolean]
57
+ def this_repo?(record, tree) = record.repo.nil? || record.repo == tree.repo
50
58
 
51
- report_interrupted(interrupted, stale_minutes) if interrupted.any?
59
+ # @param records [Array<Record>]
60
+ # @param manager [Manager]
61
+ # @param notes [Boolean]
62
+ # @return [void]
63
+ def report_listing(records, manager, notes:)
64
+ say(file_notice) if records.any? && manager.store.is_a?(Store::FileSystemStore)
65
+ say(Listing.new(records, tree: manager.tree, stale_minutes: manager.stale_minutes, notes: notes).to_s)
66
+ records.select(&:orphaned?).each { |record| advise_interrupted(record) }
52
67
  end
53
68
 
54
- # Each orphan is followed by its two ways out, on STDERR, so what
55
- # goes down a pipe is the listing alone.
69
+ # The namespace column is the Redis label, including for a lock that
70
+ # was written to disk. Without this line, `show repos` looks empty
71
+ # for a lock `ls` just printed.
56
72
  #
57
- # @param records [Array<Record>] orphaned locks
58
- # @param stale_minutes [Integer]
59
- def report_interrupted(records, stale_minutes)
60
- say("Interrupted (#{records.size}):")
61
- records.each do |record|
62
- report_records([record], json: false, stale_minutes: stale_minutes)
63
- advise_interrupted(record)
64
- end
65
- end
73
+ # @return [String]
74
+ def file_notice = "file store: #{program} show reads Redis, not these locks"
66
75
  end
67
76
  end
68
77
  end
@@ -0,0 +1,170 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "dry/cli/ui/duration"
4
+ require "tty-table"
5
+ require_relative "../../record"
6
+ require_relative "../../store/redis_store"
7
+
8
+ module Agent
9
+ module Lock
10
+ module CLI
11
+ module Commands
12
+ # The table `list` prints: one row per lock in this repository.
13
+ #
14
+ # Notes are a second row under that one, and only when asked for.
15
+ # The body of a lock is a progress log, and printing it on every
16
+ # `list` buried the four facts the row is for.
17
+ class Listing
18
+ # Column titles, in the order the row is built.
19
+ HEADERS = %w[Namespace Holder Scope Status Held].freeze
20
+
21
+ # @param records [Array<Record>] already limited to this repository
22
+ # @param tree [Tree] the checkout the command ran in
23
+ # @param stale_minutes [Integer]
24
+ # @param notes [Boolean] print each lock's progress under its row
25
+ def initialize(records, tree:, stale_minutes:, notes:)
26
+ @records = records
27
+ @tree = tree
28
+ @stale_minutes = stale_minutes
29
+ @notes = notes
30
+ end
31
+
32
+ # @return [String] the table, or the empty-store sentence
33
+ def to_s
34
+ return "No locks held." if @records.empty?
35
+
36
+ drawn = TTY::Table.new(header: HEADERS, rows: rows).render(:unicode, padding: [0, 1], width: 1_000_000)
37
+ @notes ? with_notes(drawn) : drawn
38
+ end
39
+
40
+ private
41
+
42
+ # @return [Array<Array<String>>]
43
+ def rows
44
+ @records.map { |record| row(record) }
45
+ end
46
+
47
+ # @param record [Record]
48
+ # @return [Array<String>]
49
+ def row(record)
50
+ [namespace, Text.printable(record.agent_id), Text.printable(record.scope), status(record), held(record)]
51
+ end
52
+
53
+ # The same label a Redis key starts with, brackets aside, so a file
54
+ # store and a Redis store name the repository the same way.
55
+ #
56
+ # @return [String] `alock-v4-kigster/laser-cutter`
57
+ def namespace
58
+ @namespace ||= "alock-#{Store::RedisStore.version_tag}-#{@tree.redis_slug}"
59
+ end
60
+
61
+ # @param record [Record]
62
+ # @return [String] active, stale, or interrupted
63
+ def status(record)
64
+ return "interrupted" if record.orphaned?
65
+ return "stale" if record.stale?(@stale_minutes)
66
+
67
+ "active"
68
+ end
69
+
70
+ # @param record [Record]
71
+ # @return [String]
72
+ def held(record)
73
+ Dry::CLI::UI::Duration.format(Time.now.utc - Time.parse(record.created_at))
74
+ rescue ArgumentError, TypeError
75
+ "unknown"
76
+ end
77
+
78
+ # @param drawn [String] the table, one lock per row
79
+ # @return [String] the same table, with a progress row under each lock that has one
80
+ def with_notes(drawn)
81
+ index = -1
82
+ drawn.each_line(chomp: true).flat_map do |line|
83
+ index, extra = place(line, index)
84
+ extra
85
+ end.join("\n")
86
+ end
87
+
88
+ # A `│` line is a row. The border after a data row is where that
89
+ # row's notes go, so the notes sit under the five columns rather
90
+ # than in one of them.
91
+ #
92
+ # @param line [String]
93
+ # @param index [Integer] -1 before the header, 0 for the header, then the data rows
94
+ # @return [Array(Integer, Array<String>)]
95
+ def place(line, index)
96
+ return [index + 1, [line]] if line.start_with?("│")
97
+
98
+ note = index.positive? ? progress_at(index - 1) : nil
99
+ note ? [index, span(line, note)] : [index, [line]]
100
+ end
101
+
102
+ # @param index [Integer]
103
+ # @return [String, nil]
104
+ def progress_at(index)
105
+ text = progress(@records[index])
106
+ text unless text.nil? || text.empty?
107
+ end
108
+
109
+ # The lines under `## Progress`. The heading itself is how a note
110
+ # is stored, and it is noise in a table.
111
+ #
112
+ # @param record [Record]
113
+ # @return [String, nil]
114
+ def progress(record)
115
+ return unless record.notes?
116
+
117
+ Text.printable(record.intent.split(Record::NOTES_HEADING, 2).last.to_s.strip, lines: true)
118
+ end
119
+
120
+ # @param border [String] the line under the lock row
121
+ # @param note [String]
122
+ # @return [Array<String>]
123
+ def span(border, note)
124
+ width = border.length - 2
125
+ text_width = width - 2
126
+ [rule("├", "┤", width), *note_lines(note, text_width), close(border, width)]
127
+ end
128
+
129
+ # @param note [String]
130
+ # @param width [Integer]
131
+ # @return [Array<String>]
132
+ def note_lines(note, width)
133
+ wrap(note, width).map { |text| "│ #{text.ljust(width)} │" }
134
+ end
135
+
136
+ # @param border [String]
137
+ # @param width [Integer]
138
+ # @return [String] a full-width bottom, or the columns opening again for the next lock
139
+ def close(border, width)
140
+ return rule("└", "┘", width) if border.start_with?("└")
141
+
142
+ border.tr("┼", "┬")
143
+ end
144
+
145
+ # @param left [String]
146
+ # @param right [String]
147
+ # @param width [Integer]
148
+ # @return [String]
149
+ def rule(left, right, width) = "#{left}#{"─" * width}#{right}"
150
+
151
+ # @param text [String]
152
+ # @param width [Integer]
153
+ # @return [Array<String>]
154
+ def wrap(text, width)
155
+ text.lines(chomp: true).flat_map { |line| chunks(line, width) }
156
+ end
157
+
158
+ # @param line [String]
159
+ # @param width [Integer]
160
+ # @return [Array<String>]
161
+ def chunks(line, width)
162
+ return [""] if line.empty?
163
+
164
+ line.chars.each_slice([width, 1].max).map(&:join)
165
+ end
166
+ end
167
+ end
168
+ end
169
+ end
170
+ end
@@ -1,6 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require_relative "base"
3
+ require_relative "tree_command"
4
4
 
5
5
  module Agent
6
6
  module Lock
@@ -9,15 +9,17 @@ module Agent
9
9
  # What this session holds, and what its sub-agents hold, since those
10
10
  # are what its `release-all` would take with it. Never its parent's:
11
11
  # a sub-agent that saw those as its own could release them.
12
- class Mine < Base
12
+ class Mine < TreeCommand
13
13
  desc "Locks held by this session and its sub-agents"
14
14
 
15
- option :json, type: :boolean, default: false, desc: "Machine-readable output"
15
+ option :json, type: :boolean, default: false, desc: "Print the records as a JSON array"
16
16
 
17
- # @param options [Hash]
17
+ example ["", "--json"]
18
+
19
+ # @param options [Hash] `:dir`, `:locking_strategy`, `:redis_url`, `:json`
18
20
  # @return [Manager::Result]
19
21
  def call(**options)
20
- manager = manager(options[:dir])
22
+ manager = manager(options)
21
23
  result = manager.mine
22
24
 
23
25
  if result.records.empty?
@@ -1,6 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require_relative "base"
3
+ require_relative "tree_command"
4
4
 
5
5
  module Agent
6
6
  module Lock
@@ -11,21 +11,25 @@ module Agent
11
11
  # The lock and the notes have one lifespan on purpose. A machine that
12
12
  # reboots loses the session but not the file, so the next run reads one
13
13
  # document and knows what was underway and how far it got.
14
- class Note < Base
15
- desc "Record progress inside a lock you hold"
14
+ class Note < TreeCommand
15
+ desc "Append a timestamped progress note to a lock you hold"
16
16
 
17
- argument :scope, required: true, desc: "The path or glob you locked"
18
- argument :text, required: true, desc: "What just happened"
17
+ argument :scope, required: true, desc: "The scope exactly as you claimed it"
18
+ argument :text, required: true, desc: "What just happened, for whoever resumes the work"
19
19
 
20
- example ["workflow/** 'installer rewritten, specs still red'"]
20
+ example ["'lib/billing/**' 'totals done, specs still red'"]
21
21
 
22
+ # @param scope [String]
23
+ # @param text [String]
24
+ # @param options [Hash] `:dir`, `:locking_strategy`, `:redis_url`
25
+ # @return [Manager::Result] :noted, :not_found or :refused
22
26
  def call(scope:, text:, **options)
23
- result = manager(options[:dir]).note(scope, text)
27
+ result = manager(options).note(scope, text)
24
28
 
25
29
  case result.status
26
- when :noted then say("NOTED #{result.record.scope}")
30
+ when :noted then say("NOTED #{scope_of(result.record)}")
27
31
  when :not_found then warn_("NOT LOCKED #{scope}, take the lock before writing in it")
28
- when :refused then warn_("REFUSED: #{result.record.scope} is held by #{result.record.agent_id}")
32
+ when :refused then warn_("REFUSED: #{scope_of(result.record)} is held by #{holder_of(result.record)}")
29
33
  end
30
34
 
31
35
  finish(result)
@@ -1,27 +1,30 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require_relative "base"
3
+ require_relative "tree_command"
4
4
 
5
5
  module Agent
6
6
  module Lock
7
7
  module CLI
8
8
  module Commands
9
9
  # Give a scope back.
10
- class Release < Base
11
- desc "Release a lock you hold"
10
+ class Release < TreeCommand
11
+ desc "Give back a lock you hold, thawing any files it froze"
12
12
 
13
13
  argument :scope, required: true, desc: "The path or glob you locked"
14
14
 
15
- example ["workflow/**", "lib/agent/lock/cli.rb"]
15
+ example ["'lib/billing/**'", "lib/billing/tax.rb"]
16
16
 
17
+ # @param scope [String] the scope exactly as it was claimed
18
+ # @param options [Hash] `:dir`, `:locking_strategy`, `:redis_url`
19
+ # @return [Manager::Result] :released, :not_found or :refused
17
20
  def call(scope:, **options)
18
- result = manager(options[:dir]).release(scope)
21
+ result = manager(options).release(scope)
19
22
 
20
23
  case result.status
21
- when :released then say("RELEASED #{result.record.scope}")
24
+ when :released then say("RELEASED #{scope_of(result.record)}")
22
25
  when :not_found then say("NOT LOCKED #{scope}")
23
26
  when :refused
24
- warn_("REFUSED: #{result.record.scope} is held by #{result.record.agent_id}, not you")
27
+ warn_("REFUSED: #{scope_of(result.record)} is held by #{holder_of(result.record)}, not you")
25
28
  end
26
29
 
27
30
  finish(result)
@@ -1,6 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require_relative "base"
3
+ require_relative "tree_command"
4
4
 
5
5
  module Agent
6
6
  module Lock
@@ -8,12 +8,14 @@ module Agent
8
8
  module Commands
9
9
  # What a session should run when it finishes, so the next one does not
10
10
  # have to work out whether it crashed.
11
- class ReleaseAll < Base
12
- desc "Release every lock this session holds"
11
+ class ReleaseAll < TreeCommand
12
+ desc "Release all locks of this session and its sub-agents"
13
13
 
14
+ # @param options [Hash] `:dir`, `:locking_strategy`, `:redis_url`
15
+ # @return [Manager::Result] with every record it released
14
16
  def call(**options)
15
- result = manager(options[:dir]).release_all
16
- result.records.each { |record| say("RELEASED #{record.scope}") }
17
+ result = manager(options).release_all
18
+ result.records.each { |record| say("RELEASED #{scope_of(record)}") }
17
19
  say("Released #{result.records.size} lock(s).")
18
20
  finish(result)
19
21
  end
@@ -1,6 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require_relative "base"
3
+ require_relative "tree_command"
4
4
 
5
5
  module Agent
6
6
  module Lock
@@ -11,13 +11,18 @@ module Agent
11
11
  # A lock whose holder died is orphaned rather than deleted when it has
12
12
  # notes in it. This takes it back, prints what the last session wrote,
13
13
  # and makes it a live claim again under the current identity.
14
- class Resume < Base
15
- desc "Take back a lock a crash or a reboot interrupted"
14
+ class Resume < TreeCommand
15
+ desc "Take back work a crash or reboot interrupted, notes and all"
16
16
 
17
- argument :scope, required: true, desc: "The path or glob to pick up"
17
+ argument :scope, required: true, desc: "The scope of the interrupted lock"
18
18
 
19
+ example ["'db/**'"]
20
+
21
+ # @param scope [String]
22
+ # @param options [Hash] `:dir`, `:locking_strategy`, `:redis_url`
23
+ # @return [Manager::Result] :resumed, :not_found, :held or :interrupted
19
24
  def call(scope:, **options)
20
- manager = manager(options[:dir])
25
+ manager = manager(options)
21
26
  result = manager.resume(scope)
22
27
  report(result, scope, manager.stale_minutes)
23
28
  finish(result)
@@ -28,6 +33,7 @@ module Agent
28
33
  # @param result [Manager::Result]
29
34
  # @param scope [String] as typed
30
35
  # @param stale_minutes [Integer]
36
+ # @return [void]
31
37
  def report(result, scope, stale_minutes)
32
38
  case result.status
33
39
  when :not_found then say("NOTHING TO RESUME #{scope}")
@@ -40,9 +46,9 @@ module Agent
40
46
  warn_("REFUSED, #{result.record&.agent_id || "another session"} left interrupted work " \
41
47
  "on #{scope} on this branch; resume or break that first")
42
48
  else
43
- say("RESUMED #{result.record.scope} (holder: #{result.record.agent_id})")
49
+ say("RESUMED #{scope_of(result.record)} (holder: #{holder_of(result.record)})")
44
50
  say("")
45
- say(result.record.intent)
51
+ say(printable(result.record.intent, lines: true))
46
52
  end
47
53
  end
48
54
  end
@@ -0,0 +1,172 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "dry/cli/ui"
4
+ require "shellwords"
5
+ require "socket"
6
+ require_relative "base"
7
+ require_relative "../../store/redis_index"
8
+
9
+ module Agent
10
+ module Lock
11
+ module CLI
12
+ module Commands
13
+ # Redis only. These commands read every repository in one Redis, so
14
+ # `--dir` would name a checkout they never open, and the file store
15
+ # has nothing for them to read.
16
+ #
17
+ # @abstract
18
+ class Show < Base
19
+ include Dry::CLI::UI
20
+
21
+ # @param subclass [Class<Show>]
22
+ # @return [void]
23
+ def self.inherited(subclass)
24
+ super
25
+ subclass.option :redis_url, type: :string, aliases: ["-u"],
26
+ desc: "The one Redis to use, with no fallback " \
27
+ "(env: AGENT_LOCK_REDIS_URL, else REDIS_URL)"
28
+ end
29
+
30
+ private
31
+
32
+ # @param options [Hash]
33
+ # @return [Store::RedisIndex]
34
+ # @raise [Dry::CLI::Error] when `--redis-url` is present and empty
35
+ # @raise [Store::Unreachable] when Redis does not answer
36
+ def index(options)
37
+ url = options[:redis_url]&.strip
38
+ raise Dry::CLI::Error, "--redis-url is empty" if url && url.empty?
39
+
40
+ Store::RedisIndex.open(url || Store.named_redis_url)
41
+ end
42
+
43
+ # @param rows [Array<Array<#to_s>>]
44
+ # @param header [Array<String>]
45
+ # @param empty [String] printed instead of a header when there are no rows
46
+ # @param slug [String, nil] the repository asked for, nil for every repository
47
+ # @return [void]
48
+ def table(rows, header:, empty:, slug: nil)
49
+ return say(empty_notice(empty, slug)) if rows.empty?
50
+
51
+ ui.table(rows, header: header)
52
+ end
53
+
54
+ # `list` prints a namespace for a file-store lock too, and that reads
55
+ # as a Redis key. When Redis has nothing, say where this checkout's
56
+ # locks actually are.
57
+ #
58
+ # @param sentence [String]
59
+ # @param slug [String, nil]
60
+ # @return [String]
61
+ def empty_notice(sentence, slug)
62
+ hint = file_store_hint(slug)
63
+ hint ? "#{sentence} #{hint}" : sentence
64
+ end
65
+
66
+ # Nil whenever the marker cannot be read: a hint must not turn an
67
+ # empty answer into an error.
68
+ #
69
+ # @param slug [String, nil]
70
+ # @return [String, nil] nil unless this checkout is the one asked
71
+ # about and its locks are in the file store
72
+ def file_store_hint(slug)
73
+ tree = Tree.for
74
+ return unless Store.recorded(tree) == "file"
75
+ return if slug && tree.origin_slug != Store::RedisIndex.normalize_slug(slug)
76
+
77
+ "This checkout's locks are in the file store. `#{program} list` prints them."
78
+ rescue Error
79
+ nil
80
+ end
81
+
82
+ # The command that drops this lock. `break`, because `release` only
83
+ # works for the session that holds it. The branch is a comment, so
84
+ # the line still pastes: two branches can hold the same scope.
85
+ #
86
+ # @param record [Record]
87
+ # @return [String]
88
+ def release_command(record)
89
+ branch = shell(record.branch || "detached")
90
+ host = record.host && record.host != Socket.gethostname ? " on #{shell(record.host)}" : ""
91
+ "#{program} break --dir #{shell(record.tree)} #{shell(record.scope)} # #{branch}#{host}"
92
+ end
93
+
94
+ # @param record [Record]
95
+ # @return [String]
96
+ def held_for(record)
97
+ Dry::CLI::UI::Duration.format(Time.now.utc - Time.parse(record.created_at))
98
+ rescue ArgumentError, TypeError
99
+ "unknown"
100
+ end
101
+ end
102
+
103
+ # `alock show repos`.
104
+ class ShowRepos < Show
105
+ desc "Redis: every repository, how many locks it holds, and the memory they use"
106
+
107
+ example ["", "-u redis://127.0.0.1:6379/0"]
108
+
109
+ # @param options [Hash] `:redis_url`
110
+ # @return [void]
111
+ def call(**options)
112
+ found = index(options)
113
+ rows = found.repos.map { |repo| row(repo) }
114
+ table(rows, header: %w[Namespace Locks Memory], empty: "No locks in Redis.")
115
+ warn_legacy(found.legacy_count)
116
+ end
117
+
118
+ private
119
+
120
+ # @param repo [Store::RedisIndex::Repo]
121
+ # @return [Array<String, Integer>]
122
+ def row(repo) = [printable(repo.namespace), repo.count, Store::RedisIndex.format_bytes(repo.bytes)]
123
+
124
+ # Locks an older gem wrote are in no table above and stop nobody.
125
+ # Saying nothing would let them pass for an empty Redis.
126
+ #
127
+ # @param count [Integer]
128
+ # @return [void]
129
+ def warn_legacy(count)
130
+ return if count.zero?
131
+
132
+ keys = count == 1 ? "1 key" : "#{count} keys"
133
+ warn_("#{keys} under the old `#{Store::RedisIndex::LEGACY_PREFIX}` prefix are not read by this version " \
134
+ "and block nobody. Delete them once their holders are done.")
135
+ end
136
+ end
137
+
138
+ # `alock show repo [owner/name]`.
139
+ class ShowRepo < Show
140
+ desc "Redis: the locks held on one repository"
141
+
142
+ argument :repo, required: false,
143
+ desc: "owner/name on GitHub, host/owner/name on any other forge " \
144
+ "(default: the origin remote of the checkout you are in)"
145
+
146
+ example ["", "kigster/laser-cutter", "gitlab.com/kigster/laser-cutter"]
147
+
148
+ # @param repo [String, nil] nil or blank for the checkout this runs in
149
+ # @param options [Hash] `:redis_url`
150
+ # @return [void]
151
+ # @raise [Error] when no repository is named and the current
152
+ # directory is in no checkout with an origin remote
153
+ def call(repo: nil, **options)
154
+ repo = Store::RedisIndex.slug_for if repo.to_s.strip.empty?
155
+ locks = index(options).locks(repo)
156
+ rows = locks.map { |lock| row(lock.record) }
157
+ table(rows, header: %w[Scope Holder Held Alive Release], empty: "No locks for #{repo}.", slug: repo)
158
+ end
159
+
160
+ private
161
+
162
+ # @param record [Record]
163
+ # @return [Array<String>]
164
+ def row(record)
165
+ [scope_of(record), holder_of(record), held_for(record),
166
+ Store::RedisIndex.alive(record), release_command(record)]
167
+ end
168
+ end
169
+ end
170
+ end
171
+ end
172
+ end