ruby-ship 0.1.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.
data/lib/ship/setup.rb ADDED
@@ -0,0 +1,318 @@
1
+ require_relative "terminal"
2
+ require_relative "setup_options"
3
+
4
+ module Ship
5
+ class Setup
6
+ include SetupOptions
7
+
8
+ FRAMEWORK_LABELS = Application::FRAMEWORKS
9
+ attr_reader :data
10
+
11
+ def initialize(root, terminal, options)
12
+ @root, @terminal, @options = root, terminal, options
13
+ @host_ports = {}
14
+ prior = read_existing(root, options[:force])
15
+ prior = {} if options[:force] && !prior.keys.all? { |key| Config::KEYS.include?(key) }
16
+ @data = { "$schema" => Config::SCHEMA, "name" => Config.name_for(root) }.merge(prior, options[:config])
17
+ selections = prior.fetch("services", {}).dup
18
+ if selections["analytics"] == "clickhouse" && !selections.key?("database") && !options[:services].key?("analytics")
19
+ selections["database"] = selections.delete("analytics")
20
+ end
21
+ @data["services"] = selections.merge(options[:services]).reject { |_, provider| provider == "none" }
22
+ instances = prior.fetch("additionalServices", []).reject { |entry| options[:remove].include?(entry["name"]) } + options[:additional]
23
+ @data["additionalServices"] = instances.map do |entry|
24
+ entry["group"] == "analytics" && entry["service"] == "clickhouse" ? entry.merge("group" => "database") : entry
25
+ end
26
+ @data["processes"] = prior.fetch("processes", {}).reject { |key, _| options[:remove_processes].include?(key) }.merge(options[:processes])
27
+ @data["deployCommands"] = options[:deploy] if options.key?(:deploy)
28
+ @data.delete("externalNetwork") if options[:clear_networks]
29
+ detected = Application.new(Config.new(root, data))
30
+ @application = detected
31
+ data["framework"] ||= detected.framework
32
+ data["server"] ||= detected.gem?("puma") || !detected.gem?("falcon") ? "puma" : "falcon"
33
+ data["nodeAssets"] = detected.node? unless data.key?("nodeAssets") || !detected.node?
34
+ database = detected.gem?("sqlite3") && detected.framework == "rails" ? "sqlite" : nil
35
+ data["services"]["database"] ||= database unless options[:services].key?("database") || database.nil? || prior.key?("services")
36
+ @workers = detected.workers
37
+ @catalog = Services::CATALOG.merge(Extensions.new(detected.config).services)
38
+ @prior = prior
39
+ end
40
+
41
+ def run
42
+ if @terminal.interactive? && !@options[:defaults]
43
+ @terminal.screen { walk(steps) }
44
+ end
45
+ if data["services"]["database"] == "clickhouse" && data["services"]["analytics"] == "clickhouse"
46
+ data["services"].delete("analytics")
47
+ end
48
+ remove_stale_service_references
49
+ finalize_publications
50
+ data.delete("additionalServices") if data["additionalServices"].empty?
51
+ data.delete("services") if data["services"].empty?
52
+ data.delete("processes") if data["processes"].empty?
53
+ data.delete("externalNetwork") if data.key?("externalNetwork") && Array(data["externalNetwork"]).empty?
54
+ config = Config.new(@root, data)
55
+ project = Project.new(config)
56
+ environment = {}
57
+ changes = project.regenerate(write_config: true, environment_report: environment, host_ports: @host_ports)
58
+ summary(project, changes, environment)
59
+ end
60
+
61
+ private
62
+
63
+ def read_existing(root, force)
64
+ Config.read(root, required: false)
65
+ rescue Error
66
+ raise unless force
67
+ {}
68
+ end
69
+
70
+ def steps
71
+ prompts = []
72
+ unless @options[:config].key?("name")
73
+ prompts << ["Project name", nil, -> { data["name"] }, ->(value) { data["name"] = value },
74
+ ->(value) { Config::NAME.match?(value) }]
75
+ end
76
+ if !@options[:config].key?("framework")
77
+ prompts << [
78
+ "Application framework", FRAMEWORK_LABELS.to_a, -> { data["framework"] }, ->(value) { data["framework"] = value }
79
+ ]
80
+ end
81
+ if !@options[:config].key?("server")
82
+ prompts << [
83
+ "Application server",
84
+ -> { Application::SERVERS.reject { |key, _| key == "thruster" && data["framework"] != "rails" }.to_a },
85
+ -> { data["server"] }, ->(value) { data["server"] = value }
86
+ ]
87
+ end
88
+ unless @options[:config].key?("port")
89
+ prompts << ["Application container port", nil, -> { data.fetch("port", 3000) },
90
+ ->(value) { data["port"] = value.to_i }, ->(value) { valid_port_text?(value) }]
91
+ end
92
+ groups = service_groups.reject { |group, _| @options[:services].key?(group) }
93
+ unless groups.empty?
94
+ selected = groups.keys.intersection(data["services"].keys)
95
+ prompts << ["Service categories", groups.to_a, -> { selected }, ->(value) {
96
+ selected = value
97
+ (groups.keys - selected).each { |group| data["services"].delete(group) }
98
+ }, nil, nil, true]
99
+ end
100
+ groups.each do |group, label|
101
+ prompts << [label, -> { service_options(group) }, -> { data["services"][group] }, ->(selected) {
102
+ selected ? data["services"][group] = selected : data["services"].delete(group)
103
+ }, nil, -> { selected.include?(group) }]
104
+ end
105
+ prompts << ["Other named services", -> { named_service_options }, -> { :done }, method(:manage_named_services)]
106
+ prompts.concat(optional_service_steps)
107
+ prompts.concat(frontend_steps)
108
+ prompts << ["Processes to run", method(:process_options), -> { :done }, method(:manage_processes)]
109
+ unless @options.key?(:deploy)
110
+ prompts << ["Deploy commands", method(:deploy_options), -> { :done }, method(:manage_deploy_commands)]
111
+ end
112
+ prompts << ["Compose service names", method(:service_name_options), -> { :done }, method(:manage_service_names)]
113
+ if !@options[:config].key?("externalNetwork") && !@options[:clear_networks]
114
+ prompts << ["External network (optional)", nil, -> { Array(data["externalNetwork"]).join(", ") },
115
+ ->(value) { value.empty? ? data.delete("externalNetwork") : data["externalNetwork"] = value.split(",").map(&:strip).uniq },
116
+ ->(value) { value.empty? || value.split(",", -1).all? { |name| Config::NETWORK.match?(name.strip) } }]
117
+ end
118
+ %w[development production].each do |environment|
119
+ next if @options.fetch(:publish, {}).key?(environment)
120
+
121
+ prompts << [->(back:) { configure_published_ports(environment, back: back) }]
122
+ end
123
+ prompts << ["Write ship.json and generated files?", yes_no, -> { true }, ->(approved) {
124
+ raise Terminal::Cancelled, "Setup cancelled." unless approved
125
+ }]
126
+ prompts
127
+ end
128
+
129
+ def service_groups
130
+ groups = @catalog.values.map { |entry| entry["group"] }.uniq
131
+ Services::GROUPS.merge(groups.to_h { |group| [group, Services::GROUPS.fetch(group, group.capitalize)] })
132
+ end
133
+
134
+ def providers(group, named: false)
135
+ @catalog.filter_map do |key, info|
136
+ next if info["group"] != group || (key == "anycable" && !@application.anycable_available?)
137
+ next if named && !info["named"]
138
+
139
+ missing = @application.missing_database_gem(key) if group == "database" && !named
140
+ [key, missing ? "#{info["label"]} (requires #{missing})" : info["label"]]
141
+ end
142
+ end
143
+
144
+ def service_options(group) = [[nil, "None"], *providers(group)]
145
+
146
+ def named_service_options
147
+ options = [[:done, "Continue"], [:add, "Add a named service"]]
148
+ options.concat(data["additionalServices"].map do |entry|
149
+ [entry["name"], "Manage #{entry['name']} (#{@catalog.fetch(entry['service'], {}).fetch('label', entry['service'])})"]
150
+ end)
151
+ options << [:legacy_clickhouse, "Manage ClickHouse (existing standalone service)"] if data["services"]["analytics"] == "clickhouse"
152
+ options
153
+ end
154
+
155
+ def manage_named_services(choice)
156
+ return if choice == :done
157
+
158
+ if choice == :add
159
+ add_named_service
160
+ else
161
+ label = choice == :legacy_clickhouse ? "ClickHouse" : choice
162
+ remove = @terminal.question("Remove #{label}?", [[false, "Keep"], [true, "Remove"]], false, back: true)
163
+ if remove == true
164
+ if choice == :legacy_clickhouse
165
+ data["services"].delete("analytics")
166
+ else
167
+ data["additionalServices"].reject! { |entry| entry["name"] == choice }
168
+ end
169
+ end
170
+ end
171
+ :stay
172
+ end
173
+
174
+ def add_named_service
175
+ groups = service_groups.select { |group, _| providers(group, named: true).any? }
176
+ draft = { "group" => groups.keys.first }
177
+ prompts = [
178
+ ["Service category", groups.to_a, -> { draft["group"] }, ->(group) {
179
+ draft.delete("service") if draft["group"] != group
180
+ draft["group"] = group
181
+ }],
182
+ ["Service provider", -> { providers(draft["group"], named: true) }, -> { draft["service"] },
183
+ ->(service) { draft["service"] = service }],
184
+ ["Instance name (environment prefix)", nil, -> { draft["name"] }, ->(name) { draft["name"] = name },
185
+ ->(name) { Config::INSTANCE_NAME.match?(name) && data["additionalServices"].none? { |entry| entry["name"] == name } }]
186
+ ]
187
+ data["additionalServices"] << draft unless walk(prompts, back_out: true) == :back
188
+ end
189
+
190
+ def service_resources(config = data)
191
+ ["app", *config.fetch("services", {}).values, *config.fetch("processes", {}).keys,
192
+ *config.fetch("additionalServices", []).map { |entry| "#{entry['service']}-#{entry['name']}" }].uniq
193
+ end
194
+
195
+ def remove_stale_service_references
196
+ removed = service_resources(@prior) - service_resources
197
+ return if removed.empty?
198
+
199
+ names = data.fetch("serviceNames", {})
200
+ aliases = removed.filter_map { |name| names.delete(name) }
201
+ data.fetch("portPublishing", {}).each_value do |ports|
202
+ ports.reject! { |port| (removed + aliases).include?(port.split(":", 2).first) }
203
+ end
204
+ end
205
+
206
+ def walk(prompts, back_out: false)
207
+ index = 0
208
+ direction = 1
209
+ while index.between?(0, prompts.length - 1)
210
+ prompt, options, current, set, validate, enabled, multiple = prompts[index]
211
+ if enabled && !enabled.call
212
+ index += direction
213
+ next
214
+ end
215
+
216
+ back = back_out || prompts.take(index).any? { |step| !step[5] || step[5].call }
217
+ result = if prompt.respond_to?(:call)
218
+ prompt.call(back: back)
219
+ else
220
+ options = options.call if options.respond_to?(:call)
221
+ value = @terminal.question(prompt, options, current.call, back: back, validate: validate, multiple: !!multiple)
222
+ value == :back ? :back : set.call(value)
223
+ end
224
+ next if result == :stay
225
+
226
+ direction = result == :back ? -1 : 1
227
+ index += direction
228
+ end
229
+ :back if index.negative?
230
+ end
231
+
232
+ def summary(project, changes, environment)
233
+ term = @terminal
234
+ term.title("Ruby Ship")
235
+ term.status("Project configured")
236
+ term.section("Application")
237
+ term.table([["Project", project.config.name], ["Framework", FRAMEWORK_LABELS.fetch(project.app.framework)],
238
+ ["Ruby", project.app.ruby], ["Bundler", project.app.bundler], ["Server", Application::SERVERS.fetch(project.config.server)],
239
+ ["Port", project.config.port.to_s], ["Node assets", project.app.node? ? "Enabled" : "Disabled"]])
240
+ unless project.services.instances.empty?
241
+ term.section("Services")
242
+ term.table(project.services.instances.map { |entry| [entry.host, entry.label] })
243
+ end
244
+ removed = @prior.fetch("services", {}).values - data.fetch("services", {}).values
245
+ named = data.fetch("additionalServices", []).map { |entry| entry["name"] }
246
+ removed += @prior.fetch("additionalServices", []).map { |entry| entry["name"] } - named
247
+ term.table(removed.uniq.map { |name| [name, "Removed", :error] })
248
+ unless project.config.processes.empty?
249
+ term.section("Processes")
250
+ term.table(project.config.processes.keys.map { |name| [name, "Enabled", :ok] })
251
+ end
252
+ published_ports_summary(project)
253
+ term.section("Project files")
254
+ generated = changes.reject { |file, _| EnvironmentFiles::FILES.key?(file) }
255
+ if generated.empty?
256
+ term.status("All generated files are current.", :muted)
257
+ else
258
+ term.table(generated.map { |file, action| [file, action, action == "Created" ? :ok : :warning] })
259
+ end
260
+ environment_summary(environment, changes)
261
+ if environment.fetch(".env.production").any? { |_, value, purpose, _| value == "—" && purpose.end_with?(" · Required") }
262
+ term.status("Set production credentials in .env.production before deployment.", :warning)
263
+ end
264
+ term.section("Next steps")
265
+ next_steps = [["ship up", "Start the development environment"]]
266
+ next_steps << ["ship rails db:prepare", "Prepare the Rails databases"] if project.app.framework == "rails" && project.app.gem?("activerecord")
267
+ project.services.instances.select { |entry| entry.key == "clickhouse" }.each do |entry|
268
+ next_steps << ["ship db #{entry.name || 'clickhouse'}", "Open the ClickHouse console"]
269
+ end
270
+ next_steps.concat([["ship check", "Validate your configuration"], ["ship logs --follow", "Watch the service logs"]])
271
+ term.table(next_steps)
272
+ 0
273
+ end
274
+
275
+ def environment_summary(environment, changes)
276
+ @terminal.section("Environment files")
277
+ colors = { "Added" => :ok, "Updated" => :warning, "Removed" => :error, "Unchanged" => :muted }
278
+ EnvironmentFiles::FILES.each do |filename, purpose|
279
+ state = changes.fetch(filename, "Unchanged")
280
+ @terminal.output.puts
281
+ @terminal.output.puts(" #{@terminal.paint(filename, :title)} #{purpose} #{@terminal.paint(state, state == 'Created' ? :ok : colors.fetch(state))}")
282
+ rows = environment.fetch(filename)
283
+ if rows.empty?
284
+ @terminal.output.puts(" #{@terminal.paint('No settings', :muted)}")
285
+ else
286
+ @terminal.grid(%w[Setting Value Source Status], rows.map do |key, value, source, status|
287
+ [[key, :key], [value, :value], [source, :muted], [status, colors.fetch(status)]]
288
+ end)
289
+ end
290
+ end
291
+ end
292
+
293
+ def published_ports_summary(project)
294
+ env = EnvironmentFiles.new(project)
295
+ rows = [project.development, project.production].flat_map do |compose|
296
+ settings = env.current(compose.env_file)
297
+ stage = compose.production ? "Production" : "Development"
298
+ compose.published_endpoints.map do |service, port, protocol, variable, fallback|
299
+ value = settings.fetch(variable, fallback.to_s)
300
+ binding = if value == "0"
301
+ "Automatic"
302
+ elsif valid_port_text?(value)
303
+ "#{compose.production ? '*' : '127.0.0.1'}:#{value}"
304
+ else
305
+ variable
306
+ end
307
+ [[stage, :heading], [binding, :value], ["#{service}:#{port}/#{protocol}", :key], [variable, :muted]]
308
+ end
309
+ end
310
+ @terminal.section("Published ports")
311
+ if rows.empty?
312
+ @terminal.status("The stack is available on the Docker network.", :muted)
313
+ else
314
+ @terminal.grid(%w[Environment Host Container Setting], rows)
315
+ end
316
+ end
317
+ end
318
+ end
@@ -0,0 +1,317 @@
1
+ require "socket"
2
+
3
+ module Ship
4
+ module SetupOptions
5
+ private
6
+
7
+ def optional_service_steps
8
+ prompts = []
9
+ unless @options[:config].key?("mongodbMode")
10
+ prompts << ["MongoDB mode", [%w[replica-set Replica-set], %w[standalone Standalone]],
11
+ -> { data.fetch("mongodbMode", "replica-set") }, ->(value) { data["mongodbMode"] = value },
12
+ nil, -> { service_selected?("mongodb") }]
13
+ end
14
+ unless @options[:config].key?("siloImage")
15
+ choices = [["standard", "Standard (x86-64-v2 on x86)"], ["distroless", "Distroless (without a shell)"]]
16
+ prompts << ["Silo image", choices, -> { data.fetch("siloImage", "standard") },
17
+ ->(value) { data["siloImage"] = value }, nil, -> { service_selected?("silo") }]
18
+ end
19
+ prompts
20
+ end
21
+
22
+ def frontend_steps
23
+ prompts = []
24
+ unless @options[:config].key?("nodeAssets")
25
+ prompts << ["Build Node.js assets?", yes_no, -> { data.fetch("nodeAssets", false) },
26
+ ->(value) { data["nodeAssets"] = value }, nil, -> { @application.file?("package.json") }]
27
+ end
28
+ unless @options[:config].key?("node")
29
+ prompts << ["Container Node.js major version", nil, -> { data.fetch("node", "24") },
30
+ ->(value) { data["node"] = value }, ->(value) { /\A[1-9][0-9]*\z/.match?(value) }, method(:node_selected?)]
31
+ end
32
+ unless @options[:config].key?("packageManager")
33
+ prompts << ["Frontend package manager", %w[npm pnpm yarn bun].map { |name| [name, name] },
34
+ -> { data["packageManager"] || detected_package_manager }, ->(value) {
35
+ if value != (data["packageManager"] || detected_package_manager)
36
+ data.delete("packageManagerVersion") unless @options[:config].key?("packageManagerVersion")
37
+ end
38
+ data["packageManager"] = value
39
+ }, nil, method(:node_selected?)]
40
+ end
41
+ unless @options[:config].key?("packageManagerVersion")
42
+ prompts << ["Exact package-manager version (optional)", nil, -> { preview_project.package_manager_version },
43
+ ->(value) { set_optional(data, "packageManagerVersion", value) },
44
+ ->(value) { value.empty? || /\A(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\z/.match?(value) },
45
+ method(:node_selected?)]
46
+ end
47
+ if RUBY_PLATFORM.include?("linux") && !@options[:config].key?("hostUser")
48
+ prompts << ["Match the host user for development?", yes_no, -> { data.fetch("hostUser", true) },
49
+ ->(value) { data["hostUser"] = value }]
50
+ end
51
+ prompts
52
+ end
53
+
54
+ def service_selected?(service)
55
+ data.fetch("services", {}).value?(service) || data.fetch("additionalServices", []).any? { |entry| entry["service"] == service }
56
+ end
57
+
58
+ def node_selected? = data["nodeAssets"] || service_selected?("node")
59
+
60
+ def detected_package_manager = preview_project.package_manager
61
+
62
+ def yes_no = [[false, "No"], [true, "Yes"]]
63
+
64
+ def set_optional(target, key, value)
65
+ value.empty? ? target.delete(key) : target[key] = value
66
+ end
67
+
68
+ def process_options
69
+ options = [[:done, "Continue"], [:add, "Add a custom process"]]
70
+ @workers.each_key do |name|
71
+ options << [name, "Enable #{name}"] unless data["processes"].key?(name) || service_resources.include?(name)
72
+ end
73
+ options.concat(data["processes"].keys.map { |name| [name, "Manage #{name}"] })
74
+ end
75
+
76
+ def manage_processes(choice)
77
+ return if choice == :done
78
+
79
+ if choice == :add
80
+ edit_process
81
+ elsif data["processes"].key?(choice)
82
+ action = @terminal.question("Process #{choice}", [[:keep, "Keep"], [:edit, "Edit"], [:remove, "Remove"]], :keep, back: true)
83
+ case action
84
+ when :edit then edit_process(choice)
85
+ when :remove then data["processes"].delete(choice)
86
+ end
87
+ else
88
+ data["processes"][choice] = @workers.fetch(choice)
89
+ end
90
+ :stay
91
+ end
92
+
93
+ def edit_process(original_name = nil)
94
+ original = data["processes"][original_name]
95
+ definition = original.is_a?(Hash) ? original : { "command" => original }
96
+ command = display_command(definition["command"])
97
+ draft = { "name" => original_name, "command" => command, "healthcheck" => definition["healthcheck"] }
98
+ http = definition["http"]&.dup || {}
99
+ receives_http = !http.empty?
100
+ prompts = [
101
+ ["Process name", nil, -> { draft["name"] }, ->(value) { draft["name"] = value },
102
+ ->(value) { available_process_name?(value, original_name) }],
103
+ ["Process shell command", nil, -> { draft["command"] }, ->(value) { draft["command"] = value }, method(:valid_command_text?)],
104
+ ["Does the process receive HTTP or WebSocket traffic?", yes_no, -> { receives_http }, ->(value) { receives_http = value }],
105
+ ["Process container port", nil, -> { http["port"] }, ->(value) { http["port"] = value.to_i },
106
+ ->(value) { valid_port_text?(value) }, -> { receives_http }],
107
+ ["Process HTTP role", nil, -> { http.fetch("role", "websocket") }, ->(value) { http["role"] = value },
108
+ ->(value) { !value.empty? }, -> { receives_http }],
109
+ ["Process healthy path (optional)", nil, -> { http["health"] }, ->(value) { set_optional(http, "health", value) },
110
+ ->(value) { value.empty? || value.start_with?("/") }, -> { receives_http }],
111
+ ["Process public URL setting name (optional)", nil, -> { http["urlSetting"] },
112
+ ->(value) { set_optional(http, "urlSetting", value) },
113
+ ->(value) { value.empty? || Config::ENV_NAME.match?(value) }, -> { receives_http }],
114
+ ["Process healthcheck command (optional)", nil, -> { draft["healthcheck"] },
115
+ ->(value) { set_optional(draft, "healthcheck", value) }]
116
+ ]
117
+ return if walk(prompts, back_out: true) == :back
118
+
119
+ updated = { "command" => draft["command"] == command ? definition["command"] : draft["command"] }
120
+ updated["http"] = http if receives_http
121
+ updated["healthcheck"] = draft["healthcheck"] if draft["healthcheck"]
122
+ if original_name && original_name != draft["name"]
123
+ data["processes"].delete(original_name)
124
+ rename_resource(original_name, draft["name"])
125
+ end
126
+ data["processes"][draft["name"]] = updated.size == 1 && !original.is_a?(Hash) ? updated.fetch("command") : updated
127
+ end
128
+
129
+ def available_process_name?(name, original)
130
+ return false unless Config::NAME.match?(name)
131
+
132
+ taken = service_resources - [original]
133
+ aliases = data.fetch("serviceNames", {}).values_at(*taken)
134
+ !taken.include?(name) && !aliases.include?(name)
135
+ end
136
+
137
+ def rename_resource(from, to)
138
+ names = data.fetch("serviceNames", {})
139
+ names[to] = names.delete(from) if names.key?(from)
140
+ data.fetch("portPublishing", {}).each_value do |ports|
141
+ ports.map! { |port| port.start_with?("#{from}:") ? "#{to}:#{port.split(':', 2).last}" : port }
142
+ end
143
+ end
144
+
145
+ def display_command(command) = command.is_a?(Array) ? Shellwords.join(command) : command.to_s
146
+
147
+ def valid_command_text?(value) = !value.empty? && !value.include?("\0")
148
+
149
+ def deploy_options
150
+ [[:done, "Continue"], [:add, "Add a deploy command"], *data.fetch("deployCommands", []).each_with_index.map do |command, index|
151
+ [index, "#{index + 1}. #{display_command(command)}"]
152
+ end]
153
+ end
154
+
155
+ def manage_deploy_commands(choice)
156
+ return if choice == :done
157
+
158
+ commands = (data["deployCommands"] ||= [])
159
+ if choice == :add
160
+ value = @terminal.question("Deploy shell command", nil, "", back: true, validate: method(:valid_command_text?))
161
+ commands << value unless value == :back
162
+ else
163
+ action = @terminal.question("Deploy command #{choice + 1}", [[:keep, "Keep"], [:edit, "Edit"], [:remove, "Remove"]], :keep, back: true)
164
+ case action
165
+ when :edit
166
+ original = display_command(commands[choice])
167
+ value = @terminal.question("Deploy shell command", nil, original, back: true, validate: method(:valid_command_text?))
168
+ commands[choice] = value unless value == :back || value == original
169
+ when :remove then commands.delete_at(choice)
170
+ end
171
+ end
172
+ :stay
173
+ end
174
+
175
+ def service_name_options
176
+ [[:done, "Continue"], *service_resources.map do |key|
177
+ [key, "Rename #{key} (#{data.fetch('serviceNames', {}).fetch(key, key)})"]
178
+ end]
179
+ end
180
+
181
+ def manage_service_names(choice)
182
+ return if choice == :done
183
+
184
+ names = (data["serviceNames"] ||= {})
185
+ current = names.fetch(choice, choice)
186
+ in_use = (service_resources - [choice]).map { |key| names.fetch(key, key) }
187
+ value = @terminal.question("Compose service name for #{choice}", nil, current, back: true,
188
+ validate: ->(name) { Config::NAME.match?(name) && !in_use.include?(name) })
189
+ unless value == :back
190
+ value == choice ? names.delete(choice) : names[choice] = value
191
+ data.fetch("portPublishing", {}).each_value do |ports|
192
+ ports.map! { |port| port.start_with?("#{current}:") ? "#{choice}:#{port.split(':', 2).last}" : port }
193
+ end
194
+ end
195
+ :stay
196
+ end
197
+
198
+ def preview_project
199
+ preview = data.merge("serviceNames" => data.fetch("serviceNames", {}).slice(*service_resources),
200
+ "portPublishing" => { "development" => [], "production" => [] })
201
+ if preview.dig("services", "database") == "clickhouse" && preview.dig("services", "analytics") == "clickhouse"
202
+ preview["services"] = preview.fetch("services").reject { |group, _| group == "analytics" }
203
+ end
204
+ Project.new(Config.new(@root, preview))
205
+ end
206
+
207
+ def publication_defaults(environment, available)
208
+ saved = data.dig("portPublishing", environment)
209
+ return available.select { |_, endpoint| endpoint[:legacy] }.keys unless saved
210
+
211
+ old_names = @prior.fetch("serviceNames", {}).invert
212
+ new_names = data.fetch("serviceNames", {}).invert
213
+ saved.filter_map do |id|
214
+ service, target = id.split(":", 2)
215
+ canonical = "#{new_names[service] || old_names[service] || service}:#{target}"
216
+ id = canonical unless available.key?(id)
217
+ id if available.key?(id)
218
+ end.uniq
219
+ end
220
+
221
+ def configure_published_ports(environment, back:)
222
+ project = preview_project
223
+ compose = environment == "development" ? project.development : project.production
224
+ available = compose.available_ports
225
+ return if available.empty?
226
+
227
+ selected = publication_defaults(environment, available)
228
+ initial = selected.dup
229
+ saved = EnvironmentFiles.new(project).current(compose.env_file).merge(@host_ports.fetch(environment, {}))
230
+ labels = available.map { |id, endpoint| [id, endpoint.fetch(:label)] }
231
+ loop do
232
+ label = environment == "production" ? "Publish production ports (can be public)" : "Publish development ports (localhost)"
233
+ selected = @terminal.question(label, labels, selected, back: back, multiple: true)
234
+ return :back if selected == :back
235
+
236
+ ports = selected_host_ports(environment, selected, available, saved, initial)
237
+ next if ports == :back
238
+
239
+ @host_ports[environment] = ports
240
+ (data["portPublishing"] ||= {})[environment] = selected
241
+ return
242
+ end
243
+ end
244
+
245
+ def selected_host_ports(environment, selected, available, saved, previous)
246
+ result = {}
247
+ index = 0
248
+ while index < selected.length
249
+ id = selected.fetch(index)
250
+ endpoint = available.fetch(id)
251
+ variable = endpoint.fetch(:variable)
252
+ original = saved[variable]
253
+ suggestion = result.fetch(variable, original)
254
+ default = valid_port_text?(suggestion, allow_zero: true) ? suggestion.to_i : preferred_host_port(endpoint)
255
+ available_port = lambda do |value|
256
+ next false unless valid_port_text?(value, allow_zero: true)
257
+
258
+ port = value.to_i
259
+ next true if port.zero?
260
+
261
+ conflict = selected.take(index).any? do |prior_id|
262
+ previous_endpoint = available.fetch(prior_id)
263
+ previous_endpoint[:protocol] == endpoint[:protocol] && result[previous_endpoint[:variable]].to_i == port
264
+ end
265
+ !conflict && (environment == "production" || (previous.include?(id) && original.to_i == port) || local_port_available?(port, endpoint[:protocol]))
266
+ end
267
+ default += 1 while default < 65535 && !available_port.call(default.to_s)
268
+ default = 0 unless available_port.call(default.to_s)
269
+ answer = @terminal.question("#{environment.capitalize} host port for #{id} (0 for automatic)", nil, default,
270
+ back: true, validate: available_port)
271
+ if answer == :back
272
+ return :back if index.zero?
273
+
274
+ index -= 1
275
+ else
276
+ result[variable] = answer.to_i.to_s
277
+ index += 1
278
+ end
279
+ end
280
+ result
281
+ end
282
+
283
+ def preferred_host_port(endpoint) = endpoint[:fallback].positive? ? endpoint[:fallback] : endpoint.fetch(:target)
284
+
285
+ def valid_port_text?(value, allow_zero: false)
286
+ value.is_a?(String) && /\A(?:0|[1-9][0-9]{0,4})\z/.match?(value) && (allow_zero ? 0 : 1) <= value.to_i && value.to_i <= 65535
287
+ end
288
+
289
+ def local_port_available?(port, protocol)
290
+ case protocol
291
+ when "tcp"
292
+ TCPServer.open("127.0.0.1", port).close
293
+ when "udp"
294
+ UDPSocket.open { |socket| socket.bind("127.0.0.1", port) }
295
+ end
296
+ true
297
+ rescue Errno::EADDRINUSE, Errno::EACCES
298
+ false
299
+ rescue Errno::EPERM
300
+ true
301
+ end
302
+
303
+ def finalize_publications
304
+ flags = @options.fetch(:publish, {})
305
+ return if flags.empty? && !data.key?("portPublishing")
306
+ return if flags.empty? && data["portPublishing"].keys.sort == %w[development production]
307
+
308
+ project = preview_project
309
+ [project.development, project.production].each do |compose|
310
+ environment = compose.production ? "production" : "development"
311
+ (data["portPublishing"] ||= {})[environment] = flags.fetch(environment) do
312
+ publication_defaults(environment, compose.available_ports)
313
+ end
314
+ end
315
+ end
316
+ end
317
+ end