brunch 1.2.1 → 1.3.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: dc8f19df002e2038e829f654597c0ee97cfff295d76d8e7ca71ae90baa12017c
4
- data.tar.gz: 02e7071d611d6991d9290a1f7a03300604d0c52c61d5dfad43597965c3377857
3
+ metadata.gz: d02383013ca05f606950ff18ac0efaff33278bdde1b01f9e685546477af92aa9
4
+ data.tar.gz: '0418ab4f15ed45a39924a2cad12a6edf4e264801dc640ef3c4f5e156c2f15ee7'
5
5
  SHA512:
6
- metadata.gz: eb187424ec41095d0498d47a1ad683a7be6c256f9f38b74fd04579d680401adbfdd85ceaf1c5706d365c8c2c1f519c26b4babc0832ca3777713d1b9e2b43ee22
7
- data.tar.gz: 7063df6e4c2767d53e861f0b8d2bdb44233fc9bd03cafe8eb0a709e233c9b367f97424c79150627fe7d8db70c0c0af7805134481726271d1b757fedbf460c8fe
6
+ metadata.gz: 5ab4d0d9cce0786032967666454bde866f205cd895e70ebcd5964b2ab22ce8292b4ab026f101569ece9b18aa8eee8f6f2f2f19298170430521c0fbbd1af7b215
7
+ data.tar.gz: 955b5f4795789cba7271f2a6b09a143d7ab5fe4e209f8c6f375319a8c7828d9cfe32436436aa57f143051c3ca27c2d19f8777f111347617fcc75332cae700b0d
data/CHANGELOG.md CHANGED
@@ -1,5 +1,24 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.3.0 - 2026-12-04
4
+
5
+ - Handle `brunch --version` outside Git repositories and return a failure code
6
+ when manager logs or a system operation fails.
7
+ - Reject invalid configuration roots and malformed or incomplete saved state
8
+ without replacing the state file.
9
+ - Treat uncertain manager status conservatively, avoiding duplicate starts and
10
+ distinguishing observed status from saved status.
11
+ - Recover activation, stop, restart, removal, and worktree move after interrupted
12
+ operations; checkpoint completed changes so retries do not repeat them.
13
+ - Release the global state lock during manager operations and port availability
14
+ checks; reconcile concurrent reservations before saving them.
15
+ - Recheck saved ports against external listeners while preserving ports owned by
16
+ running environments.
17
+ - Stream the last 100 local-process log lines and strengthen atomic state writes
18
+ against concurrent writers and interrupted power loss.
19
+ - Introduce state objects for environment transitions and worktree records, and
20
+ document lifecycle, concurrency, and port allocation guarantees.
21
+
3
22
  ## 1.2.1 - 2026-12-04
4
23
 
5
24
  - Fail activation when a manager cannot prepare its environment, leaving state
data/README.md CHANGED
@@ -352,6 +352,16 @@ commands:
352
352
 
353
353
  These power the corresponding Brunch operations.
354
354
 
355
+ Manager status has four meanings: `running` confirms a live environment,
356
+ `stopped` confirms it is stopped, `unknown` means the manager cannot verify it,
357
+ and `unavailable` means the manager cannot be used. The custom command manager
358
+ reports `unknown` unless a `status` command is configured. For a saved running
359
+ environment with unknown status, another activation leaves it alone rather than
360
+ starting a possible duplicate. A saved stopped environment may be resumed.
361
+ Compose reports `unknown` if its container status query fails; a successful
362
+ `start` means the manager accepted the start command, while `resume` also checks
363
+ that the container stays running briefly.
364
+
355
365
  ## Worktree lifecycle
356
366
 
357
367
  A branch checkout stops the previous environment in that worktree and starts the new one on the same host port.
@@ -363,11 +373,30 @@ Removing a worktree removes its Brunch environments. Brunch keeps the informatio
363
373
  If cleanup fails partway through multiple branch environments, Brunch records
364
374
  each successful removal. Running cleanup again processes only those still
365
375
  present in state.
376
+ Moving a worktree also records each environment after a successful stop, so a
377
+ retry skips environments already stopped before a later stop failed.
378
+
379
+ Brunch writes activation checkpoints to `.git/brunch/state.json`. After an
380
+ interrupted start, the next activation checks the manager: a confirmed running
381
+ environment is recorded as running without starting it again. A confirmed
382
+ stopped environment can be retried. If status cannot be established, Brunch
383
+ avoids starting a second copy automatically. An invalid state file is rejected
384
+ and left intact for inspection.
366
385
 
367
386
  If a custom `remove` command depends on project files, those files must be committed because cleanup after worktree removal uses the last committed state.
368
387
 
369
388
  `brunch cleanup` removes environments belonging to worktrees that no longer exist.
370
389
 
390
+ Port assignments stay associated with a worktree and are checked against other
391
+ Brunch reservations and visible listeners when first allocated. For a worktree
392
+ without an active environment, Brunch also checks a saved Compose port before
393
+ reusing it and selects another port if an unrelated process has claimed it.
394
+ Saved ports of active environments stay reserved to avoid changing their
395
+ published addresses during activation. An unrelated process can still claim a
396
+ port between that check and manager startup; Brunch's
397
+ file locks cannot prevent that external race. In that case, stop the conflicting
398
+ process and retry activation.
399
+
371
400
  With `git-hooks-ext` 0.6.0+, deleting a local branch queues its Brunch
372
401
  environments for removal. A detached worker waits for the Git process that
373
402
  triggered the hook to exit, then checks the final refs and reflogs. A rename
@@ -440,6 +469,8 @@ brunch logs --follow
440
469
  ```
441
470
 
442
471
  Show environment logs.
472
+ For a local process, the default command prints the last 100 lines without
473
+ loading the whole log into memory.
443
474
 
444
475
  ```bash
445
476
  brunch run -- bin/rails console
@@ -476,6 +507,12 @@ activation and maintenance, while `BranchReconciler` handles branch events.
476
507
  manager-specific configuration validation. Operations acquire locks in this order:
477
508
  branch, worktree, then state. Never acquire an earlier lock while holding a
478
509
  later one.
510
+ The state lock protects short read-modify-write transactions; manager stop
511
+ commands and port availability probes run while holding the relevant worktree
512
+ lock, outside the global state lock. Port reservations are checked again against
513
+ the latest state before committing, and a conflicting new reservation is retried.
514
+ State writes use a unique temporary file, synchronize its contents, rename
515
+ it atomically, and synchronize the containing directory where supported.
479
516
 
480
517
  ```bash
481
518
  bundle install
@@ -10,15 +10,19 @@ module Brunch
10
10
  end
11
11
 
12
12
  def update(record)
13
- return unless record
13
+ return unless applicable?(record)
14
14
 
15
- environments = record.fetch("environments", {})
16
- return unless environments.key?(old_ref) && !environments.key?(new_ref)
17
-
18
- rename_entry(environments)
15
+ rename_entry(record.fetch("environments"))
19
16
  record["current"] = new_ref if record["current"] == old_ref
20
17
  end
21
18
 
19
+ def applicable?(record)
20
+ return false unless record
21
+
22
+ environments = record.fetch("environments", {})
23
+ environments.key?(old_ref) && !environments.key?(new_ref)
24
+ end
25
+
22
26
  def rename_entry(environments)
23
27
  entry = environments.delete(old_ref)
24
28
  entry["ref"] = new_ref
@@ -38,29 +42,31 @@ module Brunch
38
42
  data.fetch("worktrees", {}).values.any? { |record| record.fetch("environments", {}).key?(ref) }
39
43
  end
40
44
 
45
+ # The snapshot is read once so unaffected worktrees are not written.
46
+ # :reek:TooManyStatements
41
47
  def rename(old_ref, new_ref, replace_existing: false)
42
- return unless self.class.any?(state, old_ref)
48
+ snapshot = @state_repository.read
49
+ return unless self.class.any?(snapshot, old_ref)
43
50
 
44
51
  request = Rename.new(old_ref, new_ref, replace_existing)
45
52
  request.prepare(self)
46
- state.fetch("worktrees", {}).each_key { |id| rename_worktree(id, request) }
53
+ snapshot.fetch("worktrees", {}).each_key { |id| rename_worktree(id, request) }
47
54
  end
48
55
 
49
56
  def remove(ref)
50
- state.fetch("worktrees", {}).each_key { |id| remove_worktree_branch(Branch.new(id, ref)) }
57
+ @state_repository.read.fetch("worktrees", {}).each_key { |id| remove_worktree_branch(Branch.new(id, ref)) }
51
58
  end
52
59
 
53
60
  def self.remove_record_entry(record, ref)
54
- environments = record.fetch("environments")
55
- environments.delete(ref)
56
- record["current"] = nil if record["current"] == ref
57
- environments.empty?
61
+ Brunch::State::WorktreeRecord.new(record).remove_environment!(ref)
58
62
  end
59
63
 
60
64
  private
61
65
 
62
66
  def rename_worktree(id, request)
63
67
  with_worktree_lock(id) do
68
+ next unless request.applicable?(@state_repository.read.fetch("worktrees", {})[id])
69
+
64
70
  @state_repository.with_state_lock { |data| request.update(data.fetch("worktrees", {})[id]) }
65
71
  end
66
72
  end
@@ -92,7 +98,7 @@ module Brunch
92
98
 
93
99
  def branch_entry(branch)
94
100
  id, ref = branch.to_h.fetch_values(:id, :ref)
95
- record = state.fetch("worktrees", {})[id]
101
+ record = @state_repository.read.fetch("worktrees", {})[id]
96
102
  record && record.fetch("environments", {})[ref]
97
103
  end
98
104
 
@@ -103,8 +109,6 @@ module Brunch
103
109
  worktrees.delete(id) if self.class.remove_record_entry(record, ref)
104
110
  end
105
111
 
106
- def state = @state_repository.read
107
-
108
112
  def with_worktree_lock(id, &) = @state_repository.with_worktree_lock(id, &)
109
113
  end
110
114
  end
@@ -143,7 +143,9 @@ module Brunch
143
143
 
144
144
  def worktree_logs(arguments)
145
145
  entry = current_entry!
146
- worktree_manager(entry).logs(entry, *arguments)
146
+ return true if worktree_manager(entry).logs(entry, *arguments)
147
+
148
+ raise Brunch::Runtime::Errors::OperationError, "Could not read logs for #{entry.fetch('ref')}."
147
149
  end
148
150
 
149
151
  def worktree_run(command)
data/lib/brunch/cli.rb CHANGED
@@ -22,15 +22,25 @@ module Brunch
22
22
 
23
23
  def self.start(arguments) = new.start(arguments)
24
24
 
25
+ # :reek:TooManyStatements
25
26
  def start(arguments)
27
+ return print_version if arguments.one? && %w[version --version -v].include?(arguments.first)
28
+
26
29
  ensure_repository_directory
27
30
  dispatch(arguments)
28
31
  rescue ConfigurationError, OperationError => error
29
32
  reporter.exit_status(error)
33
+ rescue SystemCallError, IOError => error
34
+ reporter.exit_status(OperationError.new("System operation failed: #{error.message}"))
30
35
  end
31
36
 
32
37
  private
33
38
 
39
+ def print_version
40
+ puts Brunch::VERSION
41
+ 0
42
+ end
43
+
34
44
  def ensure_repository_directory
35
45
  Dir.chdir(repo_root) unless Dir.pwd == repo_root
36
46
  end
@@ -38,7 +48,6 @@ module Brunch
38
48
  def dispatch(arguments)
39
49
  case arguments
40
50
  in ["install"] then Brunch::Git::Hooks.install
41
- in ["version"] | ["--version"] | ["-v"] then puts Brunch::VERSION
42
51
  else
43
52
  reconcile_before_command(arguments)
44
53
  return worktree_command(arguments)
@@ -113,7 +122,7 @@ module Brunch
113
122
  end
114
123
 
115
124
  def compose_renderer
116
- @compose_renderer ||= Brunch::Managers::Compose::Renderer.new(state_repository, port_allocator, git_repository)
125
+ @compose_renderer ||= Brunch::Managers::Compose::Renderer.new(state_repository, port_allocator, git_repository, @manager_factory)
117
126
  end
118
127
 
119
128
  def branch_reconciler
@@ -38,9 +38,15 @@ module Brunch
38
38
  def status(entry)
39
39
  return "unavailable" unless available?
40
40
 
41
- healthy?(entry) ? "running" : "stopped"
41
+ case observed_running(entry)
42
+ when true then "running"
43
+ when false then "stopped"
44
+ else "unknown"
45
+ end
42
46
  end
43
47
 
48
+ def observed_running(entry) = healthy?(entry)
49
+
44
50
  def logs(entry, *arguments)
45
51
  arguments = ["--tail", "100"] if arguments.empty?
46
52
  compose(entry, "logs", *arguments)
@@ -11,8 +11,14 @@ module Brunch
11
11
  def healthy?(entry)
12
12
  return false unless available?
13
13
 
14
+ observed_running(entry) == true
15
+ end
16
+
17
+ def observed_running(entry)
14
18
  output, status = Open3.capture2(*self.class.compose_commands(entry).command("ps", "--status", "running", "--quiet"))
15
- status.success? && !output.strip.empty?
19
+ return unless status.success?
20
+
21
+ !output.strip.empty?
16
22
  end
17
23
 
18
24
  def self.compose_commands(entry) = ComposeCommands::Docker.new(entry)
@@ -11,9 +11,17 @@ module Brunch
11
11
  def healthy?(entry)
12
12
  return false unless available?
13
13
 
14
+ observed_running(entry) == true
15
+ end
16
+
17
+ # This implements the shared instance status contract for Compose managers.
18
+ # :reek:UtilityFunction
19
+ def observed_running(entry)
14
20
  output, status = Open3.capture2("podman", "ps", "--filter",
15
21
  "label=com.docker.compose.project=#{entry.fetch('project')}", "--quiet")
16
- status.success? && !output.strip.empty?
22
+ return unless status.success?
23
+
24
+ !output.strip.empty?
17
25
  end
18
26
 
19
27
  def self.compose_commands(entry) = ComposeCommands::Podman.new(entry)
@@ -10,10 +10,11 @@ module Brunch
10
10
  # Rendering passes three ordinary arguments; a wrapper would carry no behavior.
11
11
  # :reek:DataClump
12
12
  class Renderer
13
- def initialize(state_repository, port_allocator, git_repository)
13
+ def initialize(state_repository, port_allocator, git_repository, manager_factory = Brunch::Managers)
14
14
  @state_repository = state_repository
15
15
  @port_allocator = port_allocator
16
16
  @git_repository = git_repository
17
+ @manager_factory = manager_factory
17
18
  end
18
19
 
19
20
  def render(path, entry, manager)
@@ -42,11 +43,42 @@ module Brunch
42
43
  end
43
44
 
44
45
  def assign_ports(path, manager, document)
45
- mappings = Brunch::Ports::ComposeMappings.extract(document)
46
- @state_repository.with_state_lock do |data|
47
- id = @git_repository.worktree_identity(path)
48
- reservation = Brunch::Ports::Allocator::Reservation.new(id: id, data: data, manager: manager, mappings: mappings)
49
- @port_allocator.reserve_compose_ports(reservation)
46
+ reservation = reservation_for(path, manager, document)
47
+ loop do
48
+ result = reserve_snapshot(reservation)
49
+ return result unless result.equal?(Brunch::State::Repository::NO_WRITE)
50
+ end
51
+ end
52
+
53
+ def reserve_snapshot(reservation)
54
+ reservation.data = @state_repository.read
55
+ assignments = @port_allocator.reserve_compose_ports(reservation)
56
+ @state_repository.with_state_lock { |data| commit_assignments(data, reservation.id, assignments) }
57
+ end
58
+
59
+ # Compare against the latest state under the lock before committing.
60
+ # :reek:FeatureEnvy
61
+ def commit_assignments(data, id, assignments)
62
+ worktrees = data.fetch("worktrees")
63
+ reserved = @port_allocator.reserved_ports("worktrees" => worktrees.except(id))
64
+ return Brunch::State::Repository::NO_WRITE if assignments.any? { |mapping| reserved.include?(mapping.fetch("host")) }
65
+
66
+ Brunch::Ports::Allocator.save_assignments(worktrees.fetch(id), assignments)
67
+ end
68
+
69
+ def reservation_for(path, manager, document)
70
+ id = @git_repository.worktree_identity(path)
71
+ Brunch::Ports::Allocator::Reservation.new(id: id, manager: manager,
72
+ mappings: Brunch::Ports::ComposeMappings.extract(document),
73
+ active_environment: active_environment?(id))
74
+ end
75
+
76
+ def active_environment?(id)
77
+ record = @state_repository.read.fetch("worktrees", {})[id]
78
+ return false unless record
79
+
80
+ record.fetch("environments", {}).values.any? do |entry|
81
+ @manager_factory.build(entry.fetch("configuration")).status(entry) != "stopped"
50
82
  end
51
83
  end
52
84
 
@@ -64,7 +96,8 @@ module Brunch
64
96
  entry
65
97
  end
66
98
 
67
- private :perform_render, :persist_render, :load_document, :assign_ports
99
+ private :perform_render, :persist_render, :load_document, :assign_ports, :reservation_for, :active_environment?,
100
+ :reserve_snapshot, :commit_assignments
68
101
  end
69
102
  end
70
103
  end
@@ -32,14 +32,14 @@ module Brunch
32
32
  end
33
33
 
34
34
  def stop_present_process(identity)
35
- process = identity.to_h.fetch(:process)
35
+ process = identity.process
36
36
  return true if process.fetch(:state).start_with?("Z")
37
37
 
38
38
  stop_verified(identity)
39
39
  end
40
40
 
41
41
  def stop_verified(identity)
42
- pid = identity.to_h.fetch(:pid)
42
+ pid = identity.pid
43
43
  return false unless @entry["process_started"].is_a?(String)
44
44
  return !self.class.group_running?(pid) unless same_identity?(identity)
45
45
 
@@ -24,13 +24,18 @@ module Brunch
24
24
 
25
25
  def healthy?(entry) = Brunch::Managers::LocalProcess::State.new(entry, method(:sleep)).running?
26
26
 
27
+ # :reek:TooManyStatements
27
28
  def logs(entry, *arguments)
28
29
  return super unless arguments.empty?
29
30
 
30
31
  path = entry["log_path"]
31
32
  return super unless path && File.file?(path)
32
33
 
33
- reporter.notice(File.readlines(path).last(100))
34
+ lines = File.foreach(path).each_with_object([]) do |line, tail|
35
+ tail << line
36
+ tail.shift if tail.size > 100
37
+ end
38
+ reporter.notice(lines)
34
39
  true
35
40
  end
36
41
  end
@@ -6,7 +6,14 @@ module Brunch
6
6
  module Ports
7
7
  # Assigns distinct available host ports and preserves Compose mapping identities.
8
8
  class Allocator
9
- Reservation = Struct.new(:id, :data, :manager, :mappings, keyword_init: true)
9
+ Reservation = Struct.new(:id, :data, :manager, :mappings, :active_environment, keyword_init: true) do
10
+ def active?(record)
11
+ observed = active_environment
12
+ return observed unless observed.nil?
13
+
14
+ record.fetch("environments", {}).values.any? { |entry| entry["status"] != "stopped" }
15
+ end
16
+ end
10
17
  ReservationState = Struct.new(:record, :known, :reserved, :used, keyword_init: true)
11
18
 
12
19
  def worktree_port_for(search)
@@ -48,15 +55,18 @@ module Brunch
48
55
  end
49
56
 
50
57
  def assign_mapping(reservation, state, mapping)
51
- host = self.class.reusable_host(state, mapping) || select_host(reservation, state, mapping)
58
+ host = self.class.reusable_host(state, mapping, reservation) || select_host(reservation, state, mapping)
52
59
  state.used.add(host)
53
60
  mapping.merge("host" => host)
54
61
  end
55
62
 
56
- def self.reusable_host(state, mapping)
63
+ def self.reusable_host(state, mapping, reservation)
57
64
  known, reserved, used = state.to_h.fetch_values(:known, :reserved, :used)
58
65
  host = known_host(known, mapping)
59
- host unless used.include?(host) || reserved.include?(host)
66
+ return if host.nil? || used.include?(host) || reserved.include?(host)
67
+
68
+ host if reservation.active?(state.record) || reservation.manager.port_available?(host, protocol: mapping.fetch("protocol"),
69
+ host_ip: mapping.fetch("host_ip"))
60
70
  end
61
71
 
62
72
  def self.known_host(known, mapping)
@@ -26,7 +26,10 @@ module Brunch
26
26
 
27
27
  def self.read_configuration(root)
28
28
  path = File.join(root, "brunch.yml")
29
- File.file?(path) ? YAML.safe_load_file(path, permitted_classes: [], aliases: false) || {} : {}
29
+ return {} unless File.file?(path)
30
+
31
+ value = YAML.safe_load_file(path, permitted_classes: [], aliases: false)
32
+ value.nil? ? {} : value
30
33
  end
31
34
 
32
35
  def validate_configuration!(configured)
@@ -0,0 +1,49 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Brunch
4
+ module State
5
+ # Applies lifecycle changes to an environment stored in the existing JSON shape.
6
+ class Environment
7
+ TRANSITIONS = {
8
+ nil => %w[starting running stopped],
9
+ "starting" => %w[running stopped],
10
+ "running" => %w[starting stopped],
11
+ "stopped" => %w[starting running]
12
+ }.freeze
13
+
14
+ def initialize(data)
15
+ @data = data
16
+ end
17
+
18
+ def mark_running!(updated = nil)
19
+ transition_to!("running")
20
+ @data.update(updated) if updated
21
+ @data["status"] = "running"
22
+ @data
23
+ end
24
+
25
+ def mark_stopped! = transition_to!("stopped")
26
+
27
+ def relocate!(path)
28
+ mark_stopped!
29
+ @data["snapshot"] = path
30
+ @data
31
+ end
32
+
33
+ private
34
+
35
+ def transition_to!(status)
36
+ current = @data["status"]
37
+ return @data if current == status
38
+
39
+ unless TRANSITIONS.fetch(current, []).include?(status)
40
+ raise Brunch::Runtime::Errors::ConfigurationError,
41
+ "Invalid Brunch environment status transition: #{current.inspect} -> #{status}."
42
+ end
43
+
44
+ @data["status"] = status
45
+ @data
46
+ end
47
+ end
48
+ end
49
+ end
@@ -3,12 +3,22 @@
3
3
  require "digest"
4
4
  require "fileutils"
5
5
  require "json"
6
+ require "tempfile"
6
7
 
7
8
  module Brunch
8
9
  module State
9
10
  # Lock order: branch lock, worktree lock, then state lock. Never acquire a
10
11
  # worktree or branch lock while holding the state lock.
11
12
  class Repository
13
+ NO_WRITE = Object.new.freeze
14
+ ENVIRONMENT_FIELDS = {
15
+ "ref" => String, "configuration" => Hash, "snapshot" => String,
16
+ "control" => String, "project" => String, "port" => Integer,
17
+ "ports" => Array, "pid" => Integer, "process_started" => String
18
+ }.freeze
19
+ REQUIRED_ENVIRONMENT_FIELDS = %w[ref configuration snapshot project port status].freeze
20
+ ENVIRONMENT_STATUSES = %w[starting running stopped].freeze
21
+
12
22
  def initialize(root)
13
23
  @root = root
14
24
  end
@@ -43,37 +53,90 @@ module Brunch
43
53
 
44
54
  def validate_state!(data)
45
55
  raise Brunch::Runtime::Errors::ConfigurationError, "Invalid Brunch state: expected a JSON object." unless data.is_a?(Hash)
46
- return unless self.class.legacy_state?(data)
47
56
 
48
- raise Brunch::Runtime::Errors::ConfigurationError, "Legacy branch state found in .git/brunch/state.json; stop old environments before upgrading."
57
+ validator = self.class
58
+ if validator.legacy_state?(data)
59
+ raise Brunch::Runtime::Errors::ConfigurationError, "Legacy branch state found in .git/brunch/state.json; stop old environments before upgrading."
60
+ end
61
+
62
+ return if validator.valid_state?(data)
63
+
64
+ raise Brunch::Runtime::Errors::ConfigurationError, "Invalid Brunch state: malformed worktree or branch data."
49
65
  end
50
66
 
51
67
  def self.legacy_state?(data)
52
- data.fetch("environments", {}).any? || data.key?("active_ref")
68
+ data.key?("environments") || data.key?("active_ref")
69
+ end
70
+
71
+ def self.valid_state?(data)
72
+ worktrees = data["worktrees"]
73
+ deleted = data.fetch("deleted_branches", {})
74
+ worktrees.is_a?(Hash) && worktrees.each_value.all? { |record| valid_worktree?(record) } &&
75
+ deleted.is_a?(Hash) && deleted.each_value.all? { |event| valid_deletion?(event) }
76
+ end
77
+
78
+ def self.valid_worktree?(record)
79
+ return false unless record.is_a?(Hash)
80
+ return false unless valid_environments?(record.fetch("environments", {}))
81
+
82
+ current = record["current"]
83
+ record.fetch("path", "").is_a?(String) && record.fetch("port", 0).is_a?(Integer) &&
84
+ (current.nil? || current.is_a?(String)) && record.fetch("ports", []).is_a?(Array)
85
+ end
86
+
87
+ def self.valid_environments?(environments)
88
+ environments.is_a?(Hash) && environments.each_value.all? { |entry| valid_environment?(entry) }
89
+ end
90
+
91
+ def self.valid_environment?(entry)
92
+ entry.is_a?(Hash) &&
93
+ ENVIRONMENT_FIELDS.all? do |field, type|
94
+ entry[field].is_a?(type) || (!REQUIRED_ENVIRONMENT_FIELDS.include?(field) && !entry.key?(field))
95
+ end &&
96
+ ENVIRONMENT_STATUSES.include?(entry["status"])
97
+ end
98
+
99
+ def self.valid_deletion?(event)
100
+ return true if event.is_a?(String)
101
+ return false unless event.is_a?(Hash)
102
+
103
+ git, token = event.values_at("git", "token")
104
+ event["oid"].is_a?(String) && (git.nil? || valid_git_identity?(git)) &&
105
+ (token.nil? || token.is_a?(String))
106
+ end
107
+
108
+ def self.valid_git_identity?(identity)
109
+ identity.is_a?(Hash) && identity["pid"].is_a?(Integer) && identity["started"].is_a?(String)
53
110
  end
54
111
 
55
112
  def write(value)
56
113
  FileUtils.mkdir_p(@root)
57
- temporary_path = "#{path}.#{Process.pid}.tmp"
58
- write_temporary(temporary_path, value)
59
- File.rename(temporary_path, path)
60
- ensure
61
- FileUtils.rm_f(temporary_path) if temporary_path
114
+ replace_atomically(value)
115
+ sync_directory
62
116
  end
63
117
 
64
- def write_temporary(temporary_path, value)
65
- FileUtils.mkdir_p(@root)
66
- File.open(temporary_path, "w", 0o600) do |file|
118
+ def replace_atomically(value)
119
+ Tempfile.create(["state-", ".tmp"], @root) do |file|
67
120
  self.class.write_and_sync(file, value)
121
+ file.close
122
+ File.rename(file.path, path)
68
123
  end
69
124
  end
70
125
 
126
+ def sync_directory
127
+ File.open(@root, &:fsync)
128
+ rescue Errno::EINVAL, Errno::ENOTSUP
129
+ nil
130
+ end
131
+
71
132
  def self.write_and_sync(file, value)
72
133
  file.write(JSON.pretty_generate(value))
73
134
  file.flush
74
135
  file.fsync
75
136
  end
76
137
 
138
+ private :replace_atomically, :sync_directory
139
+
77
140
  def with_state_lock(&block)
78
141
  FileUtils.mkdir_p(@root)
79
142
  File.open(File.join(@root, "lock"), "w") do |lock|
@@ -85,7 +148,7 @@ module Brunch
85
148
  def update_locked_state
86
149
  data = read
87
150
  result = yield(data)
88
- write(data)
151
+ write(data) unless result.equal?(NO_WRITE)
89
152
  result
90
153
  end
91
154
 
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Brunch
4
+ module State
5
+ # Keeps one worktree's current ref and environment collection consistent.
6
+ class WorktreeRecord
7
+ def initialize(data)
8
+ @data = data
9
+ end
10
+
11
+ def environment(ref)
12
+ entry = @data.fetch("environments").fetch(ref)
13
+ Environment.new(entry)
14
+ end
15
+
16
+ def mark_current!(ref)
17
+ environment(ref)
18
+ @data["current"] = ref
19
+ end
20
+
21
+ def remove_environment!(ref)
22
+ environments = @data.fetch("environments")
23
+ environments.delete(ref)
24
+ @data["current"] = nil if @data["current"] == ref
25
+ environments.empty?
26
+ end
27
+ end
28
+ end
29
+ end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Brunch
4
- VERSION = "1.2.1"
4
+ VERSION = "1.3.0"
5
5
  end
@@ -23,6 +23,27 @@ module Brunch
23
23
  end
24
24
 
25
25
  def resume_existing(activation)
26
+ existing = activation.existing
27
+ return false unless existing && existing["snapshot"] == activation.path
28
+
29
+ status = @manager_factory.build(existing.fetch("configuration")).status(existing)
30
+ resume_observed(activation, status)
31
+ end
32
+
33
+ def resume_observed(activation, status)
34
+ return resume_stopped(activation) if status == "stopped" ||
35
+ (status == "unknown" && activation.existing["status"] == "stopped")
36
+
37
+ unless status == "running"
38
+ raise Brunch::Runtime::Errors::OperationError,
39
+ "Cannot safely activate #{activation.ref}: manager status is #{status}."
40
+ end
41
+
42
+ @store.record_current(activation)
43
+ completed_resume(activation)
44
+ end
45
+
46
+ def resume_stopped(activation)
26
47
  return false unless activation.resumable?
27
48
 
28
49
  @store.record_current(activation)
@@ -49,11 +70,11 @@ module Brunch
49
70
  end
50
71
 
51
72
  def reset_existing(activation)
52
- existing, path = activation.to_h.fetch_values(:existing, :path)
73
+ existing = activation.existing
53
74
  return unless existing
54
75
 
55
76
  manager = @manager_factory.build(existing.fetch("configuration"))
56
- raise Brunch::Runtime::Errors::OperationError, "Could not reset environment for #{path}." unless manager.reset(existing)
77
+ raise Brunch::Runtime::Errors::OperationError, "Could not reset environment for #{activation.path}." unless manager.reset(existing)
57
78
  end
58
79
 
59
80
  def prepare_entry(activation)
@@ -87,8 +108,7 @@ module Brunch
87
108
  end
88
109
 
89
110
  def control_for(activation, project)
90
- existing = activation.to_h.fetch(:existing)
91
- existing&.fetch("control") || File.join(@state_root, "controls", project)
111
+ activation.existing&.fetch("control") || File.join(@state_root, "controls", project)
92
112
  end
93
113
 
94
114
  def start_entry(activation)
@@ -6,8 +6,7 @@ module Brunch
6
6
  # Owns the mutable state for one worktree during activation.
7
7
  class Record
8
8
  def self.reserve_from(data, activation)
9
- id, path = activation.to_h.fetch_values(:id, :path)
10
- record = (data["worktrees"] ||= {})[id] ||= { "path" => path, "environments" => {} }
9
+ record = (data["worktrees"] ||= {})[activation.id] ||= { "path" => activation.path, "environments" => {} }
11
10
  new(record, data, activation)
12
11
  end
13
12
 
@@ -20,10 +19,14 @@ module Brunch
20
19
  end
21
20
 
22
21
  def reserve(port_allocator)
22
+ reserve_with_port(port_for(port_allocator))
23
+ end
24
+
25
+ def reserve_with_port(port)
23
26
  previous = previous_for
24
- port = port_for(port_allocator)
27
+ @record["port"] ||= port
25
28
  @record["path"] = @activation.path
26
- [previous, port]
29
+ [previous, @record.fetch("port")]
27
30
  end
28
31
 
29
32
  def previous_for
@@ -38,8 +41,8 @@ module Brunch
38
41
  end
39
42
 
40
43
  def mark_starting
41
- ref, entry = @activation.to_h.fetch_values(:ref, :entry)
42
- @record.fetch("environments")[ref] = entry
44
+ ref = @activation.ref
45
+ @record.fetch("environments")[ref] = @activation.entry
43
46
  @record["current"] = ref
44
47
  end
45
48
  end
@@ -10,20 +10,40 @@ module Brunch
10
10
  @port_allocator = port_allocator
11
11
  end
12
12
 
13
+ # :reek:FeatureEnvy
13
14
  def state(activation)
14
- id, ref = activation.to_h.fetch_values(:id, :ref)
15
- with_state_lock do |data|
16
- record = data.fetch("worktrees", {})[id]
17
- [record&.fetch("environments", {})&.[](ref), record&.[]("current")]
18
- end
15
+ record = @state_repository.read.fetch("worktrees", {})[activation.id]
16
+ [record&.fetch("environments", {})&.[](activation.ref), record&.[]("current")]
19
17
  end
20
18
 
21
19
  def reserve(activation)
22
- with_state_lock do |data|
23
- Record.reserve_from(data, activation).reserve(@port_allocator)
20
+ loop do
21
+ result = reserve_snapshot(activation)
22
+ return result unless result.equal?(Brunch::State::Repository::NO_WRITE)
24
23
  end
25
24
  end
26
25
 
26
+ def reserve_snapshot(activation)
27
+ snapshot = @state_repository.read
28
+ saved_port = snapshot.fetch("worktrees", {})[activation.id]&.[]("port")
29
+ port = Record.reserve_from(snapshot, activation).port_for(@port_allocator)
30
+ with_state_lock { |data| commit_reservation(data, activation, port, saved_port) }
31
+ end
32
+
33
+ # A saved port conflict is an error; a newly selected port can be retried.
34
+ # :reek:ControlParameter
35
+ # :reek:LongParameterList
36
+ def commit_reservation(data, activation, port, saved_port)
37
+ others = data.fetch("worktrees", {}).except(activation.id)
38
+ if @port_allocator.reserved_ports("worktrees" => others).include?(port)
39
+ raise Brunch::Runtime::Errors::OperationError, "Port #{port} is already reserved by another worktree." if saved_port
40
+
41
+ return Brunch::State::Repository::NO_WRITE
42
+ end
43
+
44
+ Record.reserve_from(data, activation).reserve_with_port(port)
45
+ end
46
+
27
47
  def checkpoint(id, ref, entry)
28
48
  with_state_lock { |data| data.fetch("worktrees").fetch(id).fetch("environments")[ref] = entry }
29
49
  end
@@ -36,26 +56,28 @@ module Brunch
36
56
 
37
57
  def record_running(activation)
38
58
  id, ref, entry = activation.to_h.fetch_values(:id, :ref, :entry)
39
- with_state_lock { |data| data.fetch("worktrees").fetch(id).fetch("environments")[ref] = entry.merge("status" => "running") }
59
+ with_state_lock do |data|
60
+ Brunch::State::WorktreeRecord.new(data.fetch("worktrees").fetch(id)).environment(ref).mark_running!(entry)
61
+ end
40
62
  end
41
63
 
42
64
  def record_current(activation)
43
65
  id, ref = activation.to_h.fetch_values(:id, :ref)
44
- with_state_lock { |data| data.fetch("worktrees").fetch(id)["current"] = ref }
66
+ with_state_lock { |data| Brunch::State::WorktreeRecord.new(data.fetch("worktrees").fetch(id)).mark_current!(ref) }
45
67
  end
46
68
 
47
69
  def record_previous_stopped(activation)
48
70
  previous, id = activation.to_h.fetch_values(:previous, :id)
49
71
  with_state_lock do |data|
50
- data.fetch("worktrees").fetch(id).fetch("environments").fetch(previous.fetch("ref"))["status"] = "stopped"
72
+ Brunch::State::WorktreeRecord.new(data.fetch("worktrees").fetch(id)).environment(previous.fetch("ref")).mark_stopped!
51
73
  end
52
74
  end
53
75
 
54
76
  private
55
77
 
56
- def with_state_lock(&) = @state_repository.with_state_lock(&)
78
+ private :reserve_snapshot, :commit_reservation
57
79
 
58
- def read = @state_repository.read
80
+ def with_state_lock(&) = @state_repository.with_state_lock(&)
59
81
  end
60
82
  end
61
83
  end
@@ -56,8 +56,9 @@ module Brunch
56
56
  return false unless existing
57
57
 
58
58
  snapshot, status, config = existing.values_at("snapshot", "status", "configuration")
59
- !force && snapshot == path && status == "running" &&
60
- current_ref == ref && @manager_factory.build(config).status(existing) != "stopped"
59
+ return false if force || snapshot != path || status != "running" || current_ref != ref
60
+
61
+ %w[running unknown].include?(@manager_factory.build(config).status(existing))
61
62
  end
62
63
 
63
64
  attr_reader :activation_store, :activation_flow
@@ -18,22 +18,27 @@ module Brunch
18
18
 
19
19
  def stop(path)
20
20
  id = @git_repository.worktree_identity(path)
21
- @state_repository.with_worktree_lock(id) { @state_repository.with_state_lock { |data| stop_current(data, id) } }
21
+ @state_repository.with_worktree_lock(id) { stop_current(id) }
22
22
  end
23
23
 
24
- def stop_current(data, id)
25
- _record, entry = @state_repository.current_worktree_entry(id, data)
24
+ def stop_current(id)
25
+ _record, entry = @state_repository.current_worktree_entry(id)
26
26
  raise Brunch::Runtime::Errors::OperationError, "No Brunch environment in this worktree." unless entry
27
27
 
28
28
  stop_entry!(entry)
29
+ record_stopped(id, entry)
30
+ @reporter.notice("Stopped #{entry.fetch('project')}.")
31
+ end
32
+
33
+ def record_stopped(id, entry)
34
+ @state_repository.with_state_lock do |data|
35
+ Brunch::State::WorktreeRecord.new(data.fetch("worktrees").fetch(id)).environment(entry.fetch("ref")).mark_stopped!
36
+ end
29
37
  end
30
38
 
31
39
  def stop_entry!(entry)
32
40
  project = entry.fetch("project")
33
41
  raise Brunch::Runtime::Errors::OperationError, "Could not stop #{project}." unless @manager_factory.build(entry.fetch("configuration")).stop(entry)
34
-
35
- entry["status"] = "stopped"
36
- @reporter.notice("Stopped #{project}.")
37
42
  end
38
43
 
39
44
  def remove(path)
@@ -63,7 +68,9 @@ module Brunch
63
68
  "Could not remove environment #{ref}."
64
69
  end
65
70
 
66
- @state_repository.with_state_lock { |locked| locked.fetch("worktrees").fetch(id).fetch("environments").delete(ref) }
71
+ @state_repository.with_state_lock do |locked|
72
+ Brunch::State::WorktreeRecord.new(locked.fetch("worktrees").fetch(id)).remove_environment!(ref)
73
+ end
67
74
  end
68
75
 
69
76
  def move(old_path, new_path)
@@ -82,17 +89,21 @@ module Brunch
82
89
 
83
90
  def move_locked(move)
84
91
  record = @state_repository.read.fetch("worktrees").fetch(move.id)
85
- record.fetch("environments").each_value { |entry| stop_for_move(entry) }
92
+ record.fetch("environments").each { |ref, entry| stop_for_move(move, ref, entry) }
86
93
  @state_repository.with_state_lock { |locked| move.update_record(locked) }
87
94
  end
88
95
 
89
- def stop_for_move(entry)
96
+ def stop_for_move(move, ref, entry)
90
97
  return unless entry["status"] == "running"
91
98
 
92
- return if @manager_factory.build(entry.fetch("configuration")).stop(entry)
99
+ unless @manager_factory.build(entry.fetch("configuration")).stop(entry)
100
+ raise Brunch::Runtime::Errors::OperationError,
101
+ "Could not stop environment during worktree move."
102
+ end
93
103
 
94
- raise Brunch::Runtime::Errors::OperationError,
95
- "Could not stop environment during worktree move."
104
+ @state_repository.with_state_lock do |data|
105
+ Brunch::State::WorktreeRecord.new(data.fetch("worktrees").fetch(move.id)).environment(ref).mark_stopped!
106
+ end
96
107
  end
97
108
 
98
109
  def repair(path)
@@ -113,12 +124,11 @@ module Brunch
113
124
  end
114
125
 
115
126
  def reconcile_worktree(id, record, snapshot)
116
- identities, paths = snapshot.to_h.fetch_values(:identities, :paths)
117
127
  path = record.fetch("path")
118
- actual_path = identities[id]
128
+ actual_path = snapshot.identities[id]
119
129
  if actual_path && actual_path != path
120
130
  move(path, actual_path)
121
- elsif !paths.include?(path)
131
+ elsif !snapshot.paths.include?(path)
122
132
  remove(path)
123
133
  end
124
134
  end
@@ -131,7 +141,7 @@ module Brunch
131
141
  end
132
142
  end
133
143
 
134
- private :stop_current, :stop_entry!, :remove_locked, :remove_record, :remove_environment,
144
+ private :stop_current, :record_stopped, :stop_entry!, :remove_locked, :remove_record, :remove_environment,
135
145
  :move_known, :move_locked, :stop_for_move, :reconcile_worktree
136
146
  end
137
147
  end
@@ -11,7 +11,7 @@ module Brunch
11
11
  end
12
12
 
13
13
  def update_entry(entry)
14
- entry.update("snapshot" => path, "status" => "stopped")
14
+ Brunch::State::Environment.new(entry).relocate!(path)
15
15
  end
16
16
  end
17
17
  end
data/lib/brunch.rb CHANGED
@@ -26,6 +26,8 @@ require_relative "brunch/runtime/configuration"
26
26
  require_relative "brunch/ports/compose_mappings"
27
27
  require_relative "brunch/ports/allocator"
28
28
  require_relative "brunch/ports/search"
29
+ require_relative "brunch/state/environment"
30
+ require_relative "brunch/state/worktree_record"
29
31
  require_relative "brunch/state/repository"
30
32
  require_relative "brunch/git/repository"
31
33
  require_relative "brunch/git/branch_rename_search"
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: brunch
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.2.1
4
+ version: 1.3.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Maciej Ciemborowicz
@@ -133,7 +133,9 @@ files:
133
133
  - lib/brunch/runtime/errors/configuration_error.rb
134
134
  - lib/brunch/runtime/errors/operation_error.rb
135
135
  - lib/brunch/runtime/process_inspector.rb
136
+ - lib/brunch/state/environment.rb
136
137
  - lib/brunch/state/repository.rb
138
+ - lib/brunch/state/worktree_record.rb
137
139
  - lib/brunch/version.rb
138
140
  - lib/brunch/worktrees/activation/flow.rb
139
141
  - lib/brunch/worktrees/activation/record.rb