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.
- checksums.yaml +7 -0
- data/LICENSE.md +21 -0
- data/README.md +175 -0
- data/docs/extensions.md +38 -0
- data/exe/ship +4 -0
- data/lib/ship/application.rb +123 -0
- data/lib/ship/cli.rb +429 -0
- data/lib/ship/compose.rb +288 -0
- data/lib/ship/config.rb +160 -0
- data/lib/ship/docker.rb +123 -0
- data/lib/ship/environment_files.rb +227 -0
- data/lib/ship/extensions.rb +70 -0
- data/lib/ship/project.rb +255 -0
- data/lib/ship/release.rb +332 -0
- data/lib/ship/services.rb +103 -0
- data/lib/ship/setup.rb +318 -0
- data/lib/ship/setup_options.rb +317 -0
- data/lib/ship/terminal.rb +205 -0
- data/lib/ship/version.rb +3 -0
- data/lib/ship.rb +6 -0
- data/schema/service-environment.json +23 -0
- data/schema/ship-release.schema.json +145 -0
- data/schema/ship.schema.json +507 -0
- data/templates/entrypoint.rb +19 -0
- data/templates/garage/Dockerfile +7 -0
- data/templates/garage/garage.toml +15 -0
- data/templates/mongodb/Dockerfile +7 -0
- data/templates/mongodb/app-user.js +4 -0
- data/templates/mongodb/bootstrap.js +28 -0
- data/templates/mongodb/bootstrap.sh +10 -0
- data/templates/mongodb/entrypoint.sh +20 -0
- data/templates/mongodb/health.js +18 -0
- data/templates/services.json +1783 -0
- metadata +70 -0
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
module Ship
|
|
2
|
+
class EnvironmentFiles
|
|
3
|
+
FILES = {
|
|
4
|
+
".env" => "Development settings",
|
|
5
|
+
".env.example" => "Development template",
|
|
6
|
+
".env.production" => "Production settings",
|
|
7
|
+
".env.production.example" => "Production template"
|
|
8
|
+
}.freeze
|
|
9
|
+
ASSIGNMENT = /^(?<prefix>[\uFEFF \t]*(?:export[ \t]+)?(?<key>[A-Za-z_][A-Za-z0-9_]*)[ \t]*=)(?<space>[ \t]*?)(?<value>"(?:\\.|[^"\\])*"|'(?:\\'|[^'])*'|[^\r\n]*?)(?<tail>[ \t]+#[^\r\n]*|[ \t]*)(?=\r?$)/
|
|
10
|
+
SENSITIVE = /(?:^|_)(?:key|password|passwd|pwd|secret|token|credentials?|auth|dsn|pin)(?:_|$)/i
|
|
11
|
+
URL_CREDENTIALS = %r{://[^/?#\s]+@|[?&](?:token|secret|password|api[_-]?key)=}i
|
|
12
|
+
DEV_TOOL = /(?:^|_)(?:SELENIUM_REMOTE_URL|PLAYWRIGHT_WS_URL|PW_TEST_CONNECT_WS_ENDPOINT|PLAYWRIGHT_BASE_URL|CYPRESS_BASE_URL|CYPRESS_INSTALL_BINARY|VITE_PORT|MAILPIT_WEB_PORT)\z/
|
|
13
|
+
GROUPS = {
|
|
14
|
+
"Application" => %w[APP_ PORT RAILS_ RACK_ HANAMI_ SHIP_],
|
|
15
|
+
"Database" => %w[DB_ DATABASE_ MONGODB_ CLICKHOUSE_],
|
|
16
|
+
"Cache" => %w[REDIS_ VALKEY_ MEMCACHED_],
|
|
17
|
+
"Storage" => %w[AWS_ GARAGE_ RUSTFS_ SEAWEEDFS_ SILO_],
|
|
18
|
+
"Search" => %w[MEILISEARCH_ ELASTICSEARCH_ TYPESENSE_],
|
|
19
|
+
"Mail" => %w[MAIL_ MAILPIT_],
|
|
20
|
+
"Messaging" => %w[RABBITMQ_ AMQP_ CENTRIFUGO_ MERCURE_ ANYCABLE_],
|
|
21
|
+
"Development tools" => %w[VITE_ SELENIUM_ PLAYWRIGHT_ PW_TEST_ CYPRESS_]
|
|
22
|
+
}.freeze
|
|
23
|
+
|
|
24
|
+
def initialize(project)
|
|
25
|
+
@project = project
|
|
26
|
+
@named_services = project.services.instances.select(&:name).sort_by { |entry| -entry.name.length }
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
def write(changes, host_ports: {})
|
|
30
|
+
development = definitions(@project.development).merge(port_definitions(host_ports["development"]))
|
|
31
|
+
production = definitions(@project.production).merge(port_definitions(host_ports["production"]))
|
|
32
|
+
old_development = previous_definitions(@project.development)
|
|
33
|
+
old_production = previous_definitions(@project.production)
|
|
34
|
+
update_local_app_url(development, old_development, host_ports.dig("development", "APP_PORT"))
|
|
35
|
+
|
|
36
|
+
reports = {}
|
|
37
|
+
reports[".env"] = reconcile(".env", development, old_development, changes, seed: read(".env.example"))
|
|
38
|
+
custom = placeholders(values(read(".env")).keys - development.keys)
|
|
39
|
+
reports[".env.example"] = reconcile(".env.example", custom.merge(safe_defaults(development)),
|
|
40
|
+
old_development, changes)
|
|
41
|
+
prod_defaults = custom.reject { |key, _| DEV_TOOL.match?(key) }.merge(safe_defaults(production))
|
|
42
|
+
reports[".env.production"] = reconcile(".env.production", prod_defaults, old_production, changes, production: true)
|
|
43
|
+
custom_production = values(read(".env.production")).keys - (old_production.keys | production.keys)
|
|
44
|
+
reports[".env.production.example"] = reconcile(".env.production.example",
|
|
45
|
+
placeholders(custom_production).merge(prod_defaults), old_production, changes, production: true)
|
|
46
|
+
reports
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
def current(name) = values(read(name))
|
|
50
|
+
|
|
51
|
+
private
|
|
52
|
+
|
|
53
|
+
def port_definitions(ports)
|
|
54
|
+
(ports || {}).transform_values { |port| { value: port, fixed: true } }
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
def update_local_app_url(development, previous, host_port)
|
|
58
|
+
default = development.dig("APP_URL", :value)
|
|
59
|
+
return unless host_port && host_port != "0" && default&.start_with?("http://localhost:")
|
|
60
|
+
|
|
61
|
+
saved = current(File.file?(@project.path(".env")) ? ".env" : ".env.example")
|
|
62
|
+
local_urls = [default, previous.dig("APP_URL", :value), "http://localhost:#{saved['APP_PORT']}"]
|
|
63
|
+
return unless saved["APP_URL"].to_s.empty? || local_urls.include?(saved["APP_URL"])
|
|
64
|
+
|
|
65
|
+
development["APP_URL"] = { value: "http://localhost:#{host_port}", fixed: true }
|
|
66
|
+
end
|
|
67
|
+
|
|
68
|
+
def read(name)
|
|
69
|
+
path = @project.path(name)
|
|
70
|
+
File.file?(path) ? File.read(path) : ""
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
def definitions(compose, model = compose.model)
|
|
74
|
+
settings = compose.settings(model).transform_values do |entry|
|
|
75
|
+
value = entry.fetch("value")
|
|
76
|
+
value = "" if value.include?('$') || value.match?(/[[:cntrl:]]/)
|
|
77
|
+
{ value: value, required: entry.fetch("required") }
|
|
78
|
+
end
|
|
79
|
+
if model.equal?(compose.model)
|
|
80
|
+
compose.http.filter_map { |endpoint| endpoint["urlSetting"] }.each do |key|
|
|
81
|
+
settings[key] ||= { value: "", required: false }
|
|
82
|
+
end
|
|
83
|
+
end
|
|
84
|
+
app = model.fetch("services", {})[@project.config.app]
|
|
85
|
+
app&.fetch("environment", {})&.each do |key, value|
|
|
86
|
+
next unless Config::ENV_NAME.match?(key) && value.is_a?(String) && !value.empty? && !value.match?(/[\$[:cntrl:]]/)
|
|
87
|
+
next if sensitive?(key, value) || !key.match?(/(?:\A(?:RAILS_ENV|RACK_ENV|HANAMI_ENV|PORT|SHIP_DATABASE|SHIP_SQLITE_PATH)\z|_(?:HOST|PORT|URL|ENDPOINT|PROTOCOL)\z)/)
|
|
88
|
+
|
|
89
|
+
settings[key] = { value: value, fixed: key != "APP_URL" }
|
|
90
|
+
end
|
|
91
|
+
settings
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
def previous_definitions(compose)
|
|
95
|
+
model = YAML.safe_load(read(compose.filename), aliases: true)
|
|
96
|
+
return {} unless model.is_a?(Hash) && model["services"].is_a?(Hash)
|
|
97
|
+
|
|
98
|
+
definitions(compose, model)
|
|
99
|
+
rescue Psych::Exception
|
|
100
|
+
{}
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
def placeholders(keys) = keys.to_h { |key| [key, { value: "" }] }
|
|
104
|
+
|
|
105
|
+
def safe_defaults(settings)
|
|
106
|
+
settings.to_h do |key, entry|
|
|
107
|
+
[key, entry.merge(value: entry[:required] || sensitive?(key, entry.fetch(:value)) ? "" : entry.fetch(:value))]
|
|
108
|
+
end
|
|
109
|
+
end
|
|
110
|
+
|
|
111
|
+
def assignments(text)
|
|
112
|
+
matches = []
|
|
113
|
+
text.scan(ASSIGNMENT) { matches << Regexp.last_match }
|
|
114
|
+
matches.group_by { |entry| entry["key"] }
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
def decode(raw)
|
|
118
|
+
if raw.start_with?("'") && raw.end_with?("'")
|
|
119
|
+
raw[1...-1].gsub("\\'") { "'" }
|
|
120
|
+
elsif raw.start_with?('"') && raw.end_with?('"')
|
|
121
|
+
escapes = { 'n' => "\n", 'r' => "\r", 't' => "\t" }
|
|
122
|
+
raw[1...-1].gsub(/\\([nrt"\\$])/) { escapes.fetch(Regexp.last_match(1), Regexp.last_match(1)) }
|
|
123
|
+
else
|
|
124
|
+
raw.strip
|
|
125
|
+
end
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
def values(text) = assignments(text).transform_values { |entries| decode(entries.last["value"]) }
|
|
129
|
+
|
|
130
|
+
def quote(value)
|
|
131
|
+
value.empty? ? "" : JSON.generate(value)
|
|
132
|
+
end
|
|
133
|
+
|
|
134
|
+
def reconcile(name, desired, previous, changes, seed: "", production: false)
|
|
135
|
+
path = @project.path(name)
|
|
136
|
+
exists = File.file?(path)
|
|
137
|
+
original = exists ? File.read(path) : ""
|
|
138
|
+
current = exists ? original : seed
|
|
139
|
+
example = name.end_with?(".example")
|
|
140
|
+
entries = assignments(current)
|
|
141
|
+
outdated = entries.keys.select do |key|
|
|
142
|
+
next false if desired.key?(key)
|
|
143
|
+
next true if production && DEV_TOOL.match?(key)
|
|
144
|
+
|
|
145
|
+
old = previous[key]
|
|
146
|
+
value = decode(entries[key].last["value"])
|
|
147
|
+
old && entries[key].length == 1 && (value == old[:value] || (example && value.empty?)) &&
|
|
148
|
+
(example || value.empty? || !sensitive?(key, value))
|
|
149
|
+
end
|
|
150
|
+
replacements = desired.keys & entries.keys
|
|
151
|
+
replacements.select! do |key|
|
|
152
|
+
value = decode(entries[key].last["value"])
|
|
153
|
+
definition = desired.fetch(key)
|
|
154
|
+
old = previous[key]
|
|
155
|
+
managed_default = old && value == old[:value] && (!sensitive?(key, value) || example)
|
|
156
|
+
definition.fetch(:value) != value && (definition[:fixed] || managed_default)
|
|
157
|
+
end
|
|
158
|
+
content = current.gsub(ASSIGNMENT) do |line|
|
|
159
|
+
assignment = Regexp.last_match
|
|
160
|
+
key = assignment["key"]
|
|
161
|
+
if outdated.include?(key)
|
|
162
|
+
assignment["tail"].strip
|
|
163
|
+
elsif replacements.include?(key) && entries[key].last.begin(0) == assignment.begin(0)
|
|
164
|
+
assignment["prefix"] + assignment["space"] + quote(desired[key][:value]) + assignment["tail"]
|
|
165
|
+
else
|
|
166
|
+
line
|
|
167
|
+
end
|
|
168
|
+
end
|
|
169
|
+
missing = desired.keys - entries.keys
|
|
170
|
+
unless missing.empty?
|
|
171
|
+
eol = current.include?("\r\n") ? "\r\n" : "\n"
|
|
172
|
+
content += eol if !content.empty? && !content.end_with?("\n")
|
|
173
|
+
content += eol unless content.empty?
|
|
174
|
+
content += ["# Ruby Ship settings", *missing.sort.map { |key| "#{key}=#{quote(desired.fetch(key).fetch(:value))}" }, ""].join(eol)
|
|
175
|
+
end
|
|
176
|
+
if !exists || content != original
|
|
177
|
+
destination = exists ? File.realpath(path) : path
|
|
178
|
+
mode = exists ? File.stat(destination).mode & 0o777 : (example ? 0o644 : 0o600)
|
|
179
|
+
Project.atomic_write(destination, content, mode)
|
|
180
|
+
changes[name] = exists ? "Updated" : "Created"
|
|
181
|
+
end
|
|
182
|
+
rows(values(original), values(content), desired)
|
|
183
|
+
end
|
|
184
|
+
|
|
185
|
+
def rows(before, after, desired)
|
|
186
|
+
(after.keys | before.keys).sort.map do |key|
|
|
187
|
+
value = after[key]
|
|
188
|
+
status = if !after.key?(key) then "Removed"
|
|
189
|
+
elsif !before.key?(key) then "Added"
|
|
190
|
+
elsif before[key] != value then "Updated"
|
|
191
|
+
else "Unchanged"
|
|
192
|
+
end
|
|
193
|
+
definition = desired[key]
|
|
194
|
+
shown = if value.to_s.empty?
|
|
195
|
+
"—"
|
|
196
|
+
elsif definition && !sensitive?(key, value) && public_value?(key, value, definition)
|
|
197
|
+
value
|
|
198
|
+
else
|
|
199
|
+
"******"
|
|
200
|
+
end
|
|
201
|
+
purpose = definition&.fetch(:required, false) ? "#{source(key)} · Required" : source(key)
|
|
202
|
+
[key, shown, purpose, status]
|
|
203
|
+
end
|
|
204
|
+
end
|
|
205
|
+
|
|
206
|
+
def sensitive?(key, value) = SENSITIVE.match?(key) || URL_CREDENTIALS.match?(value)
|
|
207
|
+
|
|
208
|
+
def public_value?(key, value, definition)
|
|
209
|
+
return true if (definition.key?(:required) || definition.key?(:fixed)) &&
|
|
210
|
+
(key.end_with?("_PORT") || key.include?("_HOST_PORT_")) && /\A\d{1,5}\z/.match?(value)
|
|
211
|
+
return true if key == "APP_URL" && definition[:value] == value &&
|
|
212
|
+
%r{\Ahttps?://(?:localhost|127\.0\.0\.1|ship-app\.test)(?::\d{1,5})?\z}.match?(value)
|
|
213
|
+
|
|
214
|
+
definition[:value] == value && definition[:fixed] && source(key) != "Project setting"
|
|
215
|
+
end
|
|
216
|
+
|
|
217
|
+
def source(key)
|
|
218
|
+
instance = @named_services.find { |entry| key.start_with?(entry.prefix) }
|
|
219
|
+
return "#{instance.label} (#{instance.name})" if instance
|
|
220
|
+
return "Published host port" if key == "APP_PORT"
|
|
221
|
+
return "Published host port" if key.include?("_HOST_PORT_")
|
|
222
|
+
return "Browser testing" if DEV_TOOL.match?(key)
|
|
223
|
+
|
|
224
|
+
GROUPS.find { |_, prefixes| prefixes.any? { |prefix| key.start_with?(prefix) } }&.first || "Project setting"
|
|
225
|
+
end
|
|
226
|
+
end
|
|
227
|
+
end
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
require "digest"
|
|
2
|
+
|
|
3
|
+
module Ship
|
|
4
|
+
class Extensions
|
|
5
|
+
attr_reader :services, :definitions
|
|
6
|
+
|
|
7
|
+
def initialize(config)
|
|
8
|
+
@services = {}
|
|
9
|
+
@definitions = []
|
|
10
|
+
config.data.fetch("extensions", []).each do |relative|
|
|
11
|
+
source = read_extension(config.root, relative)
|
|
12
|
+
extension = Module.new.module_eval(source, File.join(config.root, relative), 1)
|
|
13
|
+
unless extension.is_a?(Hash) && extension.keys == ["services"] && extension["services"].is_a?(Hash)
|
|
14
|
+
raise Error, "Extension #{relative} must return a hash with a services entry."
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
extension["services"].each do |key, definition|
|
|
18
|
+
unless key.is_a?(String) && Config::NAME.match?(key) && valid_service?(definition)
|
|
19
|
+
raise Error, "Extension #{relative} has an invalid service definition for #{key.inspect}."
|
|
20
|
+
end
|
|
21
|
+
if Services::CATALOG.key?(key) || services.key?(key)
|
|
22
|
+
raise Error, "Extension #{relative} redefines the service #{key}."
|
|
23
|
+
end
|
|
24
|
+
services[key] = definition
|
|
25
|
+
end
|
|
26
|
+
definitions << [relative, Digest::SHA256.hexdigest(source)]
|
|
27
|
+
rescue SyntaxError, StandardError => error
|
|
28
|
+
raise if error.is_a?(Error)
|
|
29
|
+
|
|
30
|
+
raise Error, "Could not load extension #{relative}. #{error.class}: #{error.message}"
|
|
31
|
+
end
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
def metadata
|
|
35
|
+
return unless definitions.any?
|
|
36
|
+
|
|
37
|
+
{ "definitions" => definitions.map(&:first).sort, "fingerprint" => Digest::SHA256.hexdigest(JSON.generate(definitions.sort)) }
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
private
|
|
41
|
+
|
|
42
|
+
def read_extension(root, relative)
|
|
43
|
+
path = File.realpath(File.expand_path(relative, root))
|
|
44
|
+
unless path.start_with?(File.realpath(root) + File::SEPARATOR) && File.file?(path)
|
|
45
|
+
raise Error, "Extension #{relative} must resolve to a Ruby file in the project."
|
|
46
|
+
end
|
|
47
|
+
File.read(path)
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
def valid_service?(value)
|
|
51
|
+
return false unless value.is_a?(Hash) && value["group"].is_a?(String) && Config::NAME.match?(value["group"]) &&
|
|
52
|
+
value["label"].is_a?(String) && !value["label"].empty? && [true, false].include?(value["named"])
|
|
53
|
+
|
|
54
|
+
%w[development production].any? { |mode| value.key?(mode) } &&
|
|
55
|
+
%w[development production].all? { |mode| !value.key?(mode) || valid_mode?(value[mode]) }
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
def valid_mode?(value)
|
|
59
|
+
value.is_a?(Hash) && value["compose"].is_a?(Hash) &&
|
|
60
|
+
(value["compose"]["image"].is_a?(String) || value["compose"]["build"].is_a?(Hash)) &&
|
|
61
|
+
value.fetch("environment", {}).is_a?(Hash) && value.fetch("environment", {}).values.all? { |item| item.is_a?(String) } &&
|
|
62
|
+
value.fetch("http", []).is_a?(Array) && value.fetch("http", []).all? do |endpoint|
|
|
63
|
+
endpoint.is_a?(Hash) && endpoint["port"].is_a?(Integer) && (1..65535).cover?(endpoint["port"]) &&
|
|
64
|
+
endpoint["role"].is_a?(String) && !endpoint["role"].empty? &&
|
|
65
|
+
(endpoint["health"].nil? || (endpoint["health"].is_a?(String) && endpoint["health"].start_with?("/"))) &&
|
|
66
|
+
(endpoint["urlSetting"].nil? || (endpoint["urlSetting"].is_a?(String) && Config::ENV_NAME.match?(endpoint["urlSetting"])))
|
|
67
|
+
end
|
|
68
|
+
end
|
|
69
|
+
end
|
|
70
|
+
end
|
data/lib/ship/project.rb
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
require "fileutils"
|
|
2
|
+
require "tempfile"
|
|
3
|
+
require_relative "compose"
|
|
4
|
+
require_relative "environment_files"
|
|
5
|
+
|
|
6
|
+
module Ship
|
|
7
|
+
class Project
|
|
8
|
+
GENERATED = %w[ship.json docker-compose.generated.yml docker-compose.production.generated.yml].freeze
|
|
9
|
+
SOURCE = File.join(Config::ROOT, "templates")
|
|
10
|
+
IGNORE = %w[/.env /.env.* !/.env.example !/.env.production.example /.ship-secrets/ /.ruby-ship.lock /dist/ship/].freeze
|
|
11
|
+
DOCKER_IGNORE = %w[.git .env .env.* **/.env **/.env.* .ship-secrets **/.ship-secrets
|
|
12
|
+
.npmrc **/.npmrc .bundle vendor/bundle node_modules tmp log storage/*.sqlite3*
|
|
13
|
+
config/master.key config/credentials/*.key dist/ship .ruby-ship.lock].freeze
|
|
14
|
+
OVERRIDES = %w[docker-compose.override.yml docker-compose.override.yaml compose.override.yml compose.override.yaml].freeze
|
|
15
|
+
PRODUCTION_OVERRIDES = %w[docker-compose.production.override.yml docker-compose.production.override.yaml
|
|
16
|
+
compose.production.override.yml compose.production.override.yaml].freeze
|
|
17
|
+
|
|
18
|
+
attr_reader :config, :app, :services, :development, :production
|
|
19
|
+
|
|
20
|
+
def initialize(config)
|
|
21
|
+
@config = config
|
|
22
|
+
@app = Application.new(config)
|
|
23
|
+
@services = Services.new(config)
|
|
24
|
+
@development = Compose.new(app, services)
|
|
25
|
+
@production = Compose.new(app, services, production: true)
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
def root = config.root
|
|
29
|
+
|
|
30
|
+
def package_manager
|
|
31
|
+
config.data["packageManager"] || declared_manager&.[](1) || %w[pnpm yarn bun].find do |name|
|
|
32
|
+
{ "pnpm" => %w[pnpm-lock.yaml], "yarn" => %w[yarn.lock], "bun" => %w[bun.lock bun.lockb] }.fetch(name).any? { |file| app.file?(file) }
|
|
33
|
+
end || "npm"
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
def package_manager_version
|
|
37
|
+
configured = config.data["packageManagerVersion"]
|
|
38
|
+
configured || (declared_manager[2] if declared_manager&.[](1) == package_manager)
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
def check
|
|
42
|
+
problems = app.problems
|
|
43
|
+
if app.node?
|
|
44
|
+
lockfile = { "npm" => "package-lock.json", "pnpm" => "pnpm-lock.yaml", "yarn" => "yarn.lock", "bun" => "bun.lock" }[package_manager]
|
|
45
|
+
problems << "Add #{lockfile} for the selected #{package_manager} asset build." if lockfile && !app.file?(lockfile) &&
|
|
46
|
+
!(package_manager == "bun" && app.file?("bun.lockb"))
|
|
47
|
+
end
|
|
48
|
+
problems << "Node asset builds require package.json." if app.node? && !app.file?("package.json")
|
|
49
|
+
problems << "SQLite was selected. Add sqlite3 to Gemfile and update Gemfile.lock." if app.sqlite? && !app.gem?("sqlite3")
|
|
50
|
+
if (adapter = app.missing_database_gem(config.services["database"]))
|
|
51
|
+
problems << "Rails needs #{adapter} for #{services.database.label}. Run bundle add #{adapter} and retry."
|
|
52
|
+
end
|
|
53
|
+
if config.services["broadcasting"] == "anycable" && !app.anycable_available?
|
|
54
|
+
problems << "AnyCable requires a Rails application with anycable-rails or anycable-rails-core in Gemfile.lock."
|
|
55
|
+
end
|
|
56
|
+
problems
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
def regenerate(write_config: false, environment_report: nil, host_ports: {})
|
|
60
|
+
issues = check
|
|
61
|
+
raise Error, issues.join("\n") unless issues.empty?
|
|
62
|
+
|
|
63
|
+
changes = {}
|
|
64
|
+
File.open(path(".ruby-ship.lock"), File::RDWR | File::CREAT, 0o600) do |lock|
|
|
65
|
+
lock.flock(File::LOCK_EX)
|
|
66
|
+
append_missing(".gitignore", IGNORE, changes)
|
|
67
|
+
append_missing(".dockerignore", DOCKER_IGNORE, changes)
|
|
68
|
+
update("ship.json", JSON.pretty_generate(config.data) + "\n", changes) if write_config
|
|
69
|
+
update("docker/ship/Dockerfile", dockerfile, changes)
|
|
70
|
+
build_ignore = [File.read(path(".dockerignore")).chomp, "", "# Protected build context exclusions", *DOCKER_IGNORE, ""].join("\n")
|
|
71
|
+
update("docker/ship/Dockerfile.dockerignore", build_ignore, changes)
|
|
72
|
+
update("docker/ship/entrypoint.rb", File.read(File.join(SOURCE, "entrypoint.rb")), changes)
|
|
73
|
+
if config.services["frontend"] == "node"
|
|
74
|
+
update("docker/ship/node/Dockerfile", node_dockerfile, changes)
|
|
75
|
+
update("docker/ship/node/Dockerfile.dockerignore", build_ignore, changes)
|
|
76
|
+
end
|
|
77
|
+
services.instances.map(&:key).uniq.intersection(%w[garage mongodb]).each do |key|
|
|
78
|
+
Dir.children(File.join(SOURCE, key)).sort.each do |file|
|
|
79
|
+
update("docker/ship/#{key}/#{file}", File.binread(File.join(SOURCE, key, file)), changes)
|
|
80
|
+
end
|
|
81
|
+
end
|
|
82
|
+
report = EnvironmentFiles.new(self).write(changes, host_ports: host_ports)
|
|
83
|
+
environment_report&.merge!(report)
|
|
84
|
+
[development, production].each { |compose| update(compose.filename, compose.yaml, changes) }
|
|
85
|
+
end
|
|
86
|
+
changes
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
def compose_files(production_mode)
|
|
90
|
+
compose = production_mode ? production : development
|
|
91
|
+
overrides = production_mode ? PRODUCTION_OVERRIDES : OVERRIDES
|
|
92
|
+
[compose.filename, overrides.find { |file| app.file?(file) }].compact
|
|
93
|
+
end
|
|
94
|
+
|
|
95
|
+
def path(relative) = File.join(root, relative)
|
|
96
|
+
|
|
97
|
+
def self.atomic_write(path, content, permissions = 0o644)
|
|
98
|
+
FileUtils.mkdir_p(File.dirname(path))
|
|
99
|
+
Tempfile.create([".ship-", ".tmp"], File.dirname(path), binmode: true) do |file|
|
|
100
|
+
file.chmod(permissions)
|
|
101
|
+
file.write(content)
|
|
102
|
+
file.flush
|
|
103
|
+
file.close
|
|
104
|
+
File.rename(file.path, path)
|
|
105
|
+
end
|
|
106
|
+
end
|
|
107
|
+
|
|
108
|
+
private
|
|
109
|
+
|
|
110
|
+
def node_dockerfile
|
|
111
|
+
<<~DOCKER
|
|
112
|
+
FROM node:#{config.data.fetch('node', '24')}-bookworm-slim
|
|
113
|
+
ARG SHIP_UID=1000
|
|
114
|
+
ARG SHIP_GID=1000
|
|
115
|
+
RUN usermod --uid 2001 node && groupmod --gid 2001 node \\
|
|
116
|
+
&& (getent group "$SHIP_GID" >/dev/null || groupadd --gid "$SHIP_GID" ship) \\
|
|
117
|
+
&& useradd --no-log-init --non-unique --uid "$SHIP_UID" --gid "$SHIP_GID" --create-home ship \\
|
|
118
|
+
&& mkdir -p /app/node_modules && chown -R "$SHIP_UID:$SHIP_GID" /app
|
|
119
|
+
#{install_package_manager}WORKDIR /app
|
|
120
|
+
USER ship
|
|
121
|
+
DOCKER
|
|
122
|
+
end
|
|
123
|
+
|
|
124
|
+
def update(relative, contents, changes, permissions = 0o644)
|
|
125
|
+
file = path(relative)
|
|
126
|
+
existed = File.exist?(file)
|
|
127
|
+
return if existed && File.binread(file) == contents
|
|
128
|
+
|
|
129
|
+
self.class.atomic_write(file, contents, existed ? File.stat(file).mode & 0o777 : permissions)
|
|
130
|
+
changes[relative] = existed ? "Updated" : "Created"
|
|
131
|
+
end
|
|
132
|
+
|
|
133
|
+
def append_missing(relative, entries, changes)
|
|
134
|
+
old = File.file?(path(relative)) ? File.read(path(relative)) : ""
|
|
135
|
+
missing = entries - old.lines.map(&:strip)
|
|
136
|
+
return if missing.empty?
|
|
137
|
+
|
|
138
|
+
update(relative, [old.rstrip, "# Ruby Ship", *missing, ""].reject.with_index { |line, index| index.zero? && line.empty? }.join("\n"), changes)
|
|
139
|
+
end
|
|
140
|
+
|
|
141
|
+
def declared_manager
|
|
142
|
+
return @declared_manager if defined?(@declared_manager)
|
|
143
|
+
return unless app.file?("package.json") && (app.node? || config.services["frontend"] == "node")
|
|
144
|
+
|
|
145
|
+
@declared_manager = /\A(npm|pnpm|yarn|bun)@(\d+\.\d+\.\d+)(?:\+[^\s]+)?\z/.match(asset_manifest["packageManager"].to_s)
|
|
146
|
+
end
|
|
147
|
+
|
|
148
|
+
def asset_manifest
|
|
149
|
+
@asset_manifest ||= JSON.parse(File.read(path("package.json"))).tap do |data|
|
|
150
|
+
raise Error, "package.json must contain an object." unless data.is_a?(Hash)
|
|
151
|
+
end
|
|
152
|
+
rescue JSON::ParserError
|
|
153
|
+
raise Error, "package.json contains invalid JSON."
|
|
154
|
+
end
|
|
155
|
+
|
|
156
|
+
def install_package_manager
|
|
157
|
+
version = package_manager_version
|
|
158
|
+
tool = package_manager
|
|
159
|
+
if tool == "yarn" && version && !version.start_with?("1.")
|
|
160
|
+
return "RUN npm install --global corepack && rm -f /usr/local/bin/yarn /usr/local/bin/yarnpkg && corepack enable && corepack install --global yarn@#{version}\n"
|
|
161
|
+
end
|
|
162
|
+
version ||= { "yarn" => "1.22.22", "pnpm" => "10" }[tool]
|
|
163
|
+
return "" if tool == "npm" && version.nil?
|
|
164
|
+
|
|
165
|
+
flags = tool == "yarn" ? " --force" : ""
|
|
166
|
+
"RUN npm install --global#{flags} #{tool}#{version ? "@#{version}" : ''}\n"
|
|
167
|
+
end
|
|
168
|
+
|
|
169
|
+
def dockerfile
|
|
170
|
+
node = app.node?
|
|
171
|
+
manager = package_manager
|
|
172
|
+
version = package_manager_version
|
|
173
|
+
install = {
|
|
174
|
+
"npm" => "npm ci", "pnpm" => "pnpm install --frozen-lockfile",
|
|
175
|
+
"yarn" => version&.start_with?("1.") ? "yarn install --frozen-lockfile" : "yarn install --immutable",
|
|
176
|
+
"bun" => "bun install --frozen-lockfile"
|
|
177
|
+
}.fetch(manager)
|
|
178
|
+
install = "yarn install --frozen-lockfile" if manager == "yarn" && !version
|
|
179
|
+
public_names = config.data.fetch("build", {}).fetch("publicEnv", {}).keys
|
|
180
|
+
secret_names = config.data.fetch("build", {}).fetch("secrets", [])
|
|
181
|
+
mounts = secret_names.map { |name| "--mount=type=secret,id=#{name},env=#{name},required=true" }
|
|
182
|
+
bundle_run = "RUN #{mounts.join(' ')}".rstrip
|
|
183
|
+
npm_install = install
|
|
184
|
+
if config.data.dig("build", "npmrc")
|
|
185
|
+
npm_install = "NPM_CONFIG_USERCONFIG=/run/secrets/ship_npmrc #{install}"
|
|
186
|
+
mounts << "--mount=type=secret,id=ship_npmrc,required=true"
|
|
187
|
+
end
|
|
188
|
+
run = "RUN #{mounts.join(' ')}".rstrip
|
|
189
|
+
asset_steps = []
|
|
190
|
+
if node
|
|
191
|
+
asset_steps << "#{run} #{npm_install}"
|
|
192
|
+
if !app.assets? && !app.gem?("vite_rails")
|
|
193
|
+
scripts = asset_manifest["scripts"]
|
|
194
|
+
asset_steps << "#{run} #{manager} run build" if scripts.is_a?(Hash) && scripts.key?("build")
|
|
195
|
+
end
|
|
196
|
+
end
|
|
197
|
+
asset_steps << "#{run} SECRET_KEY_BASE_DUMMY=1 bundle exec rails assets:precompile" if app.assets?
|
|
198
|
+
asset_steps << "#{run} bundle exec vite build" if app.gem?("vite_rails") && !app.assets? && node
|
|
199
|
+
architecture = "ruby:#{app.ruby}-slim-bookworm"
|
|
200
|
+
prefix = node ? "FROM node:#{config.data.fetch('node', '24')}-bookworm-slim AS ship-node\n" : ""
|
|
201
|
+
node_copy = node ? "COPY --from=ship-node /usr/local/ /usr/local/\n#{install_package_manager}" : ""
|
|
202
|
+
node_cleanup = node ? "RUN rm -rf /app/node_modules\n" : ""
|
|
203
|
+
sqlite = app.sqlite? ? " sqlite3" : ""
|
|
204
|
+
<<~DOCKER
|
|
205
|
+
# syntax=docker/dockerfile:1.14
|
|
206
|
+
#{prefix}FROM #{architecture} AS base
|
|
207
|
+
RUN apt-get update && apt-get upgrade -y \\
|
|
208
|
+
&& apt-get install --no-install-recommends -y build-essential pkg-config git curl \\
|
|
209
|
+
libpq-dev default-libmysqlclient-dev libsqlite3-dev libyaml-dev freetds-dev#{sqlite} \\
|
|
210
|
+
&& rm -rf /var/lib/apt/lists/*
|
|
211
|
+
WORKDIR /app
|
|
212
|
+
ENV BUNDLE_FROZEN=true
|
|
213
|
+
RUN gem install --no-document bundler -v #{app.bundler}
|
|
214
|
+
COPY docker/ship/entrypoint.rb /usr/local/bin/ship-entrypoint
|
|
215
|
+
ENTRYPOINT #{JSON.generate(Application::ENTRYPOINT)}
|
|
216
|
+
|
|
217
|
+
FROM base AS development
|
|
218
|
+
ARG SHIP_UID=1000
|
|
219
|
+
ARG SHIP_GID=1000
|
|
220
|
+
RUN if ! getent group "$SHIP_GID" >/dev/null; then groupadd --gid "$SHIP_GID" ship; fi \\
|
|
221
|
+
&& useradd --no-log-init --non-unique --uid "$SHIP_UID" --gid "$SHIP_GID" --create-home ship \\
|
|
222
|
+
&& mkdir -p /app/storage /app/node_modules \\
|
|
223
|
+
&& chown -R "$SHIP_UID:$SHIP_GID" /app /usr/local/bundle
|
|
224
|
+
#{node_copy}COPY --chown=ship Gemfile Gemfile.lock ./
|
|
225
|
+
COPY --chown=ship . .
|
|
226
|
+
USER ship
|
|
227
|
+
#{bundle_run} bundle install
|
|
228
|
+
ENV BUNDLE_FROZEN=false
|
|
229
|
+
|
|
230
|
+
FROM base AS production-build
|
|
231
|
+
#{node_copy}ENV BUNDLE_WITHOUT=development:test #{app.env_name}=production
|
|
232
|
+
COPY Gemfile Gemfile.lock ./
|
|
233
|
+
COPY . .
|
|
234
|
+
#{bundle_run} bundle install && rm -rf /usr/local/bundle/cache
|
|
235
|
+
#{public_names.map { |name| "ARG #{name}" }.join("\n")}
|
|
236
|
+
#{asset_steps.join("\n")}
|
|
237
|
+
#{node_cleanup}
|
|
238
|
+
|
|
239
|
+
FROM #{architecture} AS production
|
|
240
|
+
RUN apt-get update && apt-get upgrade -y \\
|
|
241
|
+
&& apt-get install --no-install-recommends -y curl libpq5 libmariadb3 libsqlite3-0 libyaml-0-2 libsybdb5#{sqlite} \\
|
|
242
|
+
&& rm -rf /var/lib/apt/lists/* \\
|
|
243
|
+
&& groupadd --gid 10001 ship && useradd --uid 10001 --gid ship --create-home ship
|
|
244
|
+
WORKDIR /app
|
|
245
|
+
ENV BUNDLE_FROZEN=true BUNDLE_WITHOUT=development:test #{app.env_name}=production
|
|
246
|
+
COPY --from=production-build /usr/local/bundle /usr/local/bundle
|
|
247
|
+
COPY --from=production-build /usr/local/bin/ship-entrypoint /usr/local/bin/ship-entrypoint
|
|
248
|
+
COPY --chown=ship:ship --from=production-build /app /app
|
|
249
|
+
RUN mkdir -p /app/tmp /app/log /app/storage && chown ship:ship /app/tmp /app/log /app/storage
|
|
250
|
+
USER ship
|
|
251
|
+
ENTRYPOINT #{JSON.generate(Application::ENTRYPOINT)}
|
|
252
|
+
DOCKER
|
|
253
|
+
end
|
|
254
|
+
end
|
|
255
|
+
end
|