Class: Bonchi::PortPool

Inherits:
Object
  • Object
show all
Defined in:
lib/bonchi/port_pool.rb

Constant Summary collapse

DEFAULT_MIN =
4000
DEFAULT_MAX =
5000

Instance Method Summary collapse

Constructor Details

#initializePortPool

Returns a new instance of PortPool.



10
11
12
13
# File 'lib/bonchi/port_pool.rb', line 10

def initialize
  @path = GlobalConfig.config_path
  load_config
end

Instance Method Details

#allocate(worktree_path, port_names) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/bonchi/port_pool.rb', line 15

def allocate(worktree_path, port_names)
  prune_stale

  existing = @allocated[worktree_path] || {}
  if port_names.all? { |name| existing[name] }
    port_names.each_with_object({}) do |name, result|
      result[name] = existing[name]
      puts "Reusing port #{existing[name]} for #{name}"
    end
  else
    used = @allocated.reject { |k, _| k == worktree_path }
      .values.flat_map { |ports| ports.values }.to_set

    new_ports = {}
    port_names.each do |name|
      port = (@min..@max).find { |p| !used.include?(p) && port_available?(p) }
      abort "Error: no available port for #{name}" unless port
      used << port
      new_ports[name] = port
      puts "Allocated port #{port} for #{name}"
    end

    @allocated[worktree_path] = new_ports
    save_config
    new_ports
  end
end