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.
@@ -0,0 +1,205 @@
1
+ require "io/console"
2
+
3
+ module Ship
4
+ class Terminal
5
+ class Cancelled < Error; end
6
+ COLORS = { title: 96, key: 36, value: 97, muted: 90, ok: 32, warning: 33, error: 31, heading: 35 }.freeze
7
+
8
+ attr_reader :input, :output, :error
9
+
10
+ def initialize(input: $stdin, output: $stdout, error: $stderr)
11
+ @input, @output, @error = input, output, error
12
+ end
13
+
14
+ def interactive? = input.tty? && output.tty? && ENV["TERM"] != "dumb"
15
+ def color? = !ENV.key?("NO_COLOR") && ENV["TERM"] != "dumb" && (output.tty? || ENV["FORCE_COLOR"] == "1")
16
+
17
+ def paint(value, style)
18
+ color? ? "\e[#{COLORS.fetch(style)}m#{value}\e[0m" : value.to_s
19
+ end
20
+
21
+ def title(text)
22
+ output.puts(paint(text, :title))
23
+ end
24
+
25
+ def status(text, kind = :ok)
26
+ indicator = { ok: "✓", warning: "!", error: "×", muted: "·" }.fetch(kind)
27
+ output.puts("#{paint(indicator, kind)} #{text}")
28
+ end
29
+
30
+ def table(rows)
31
+ return if rows.empty?
32
+
33
+ key_width = [rows.map { |label, *_| label.length }.max, 42].min
34
+ rows.each do |label, value, style|
35
+ output.puts(" #{paint(label.ljust(key_width), :key)} #{paint(value, style || :value)}")
36
+ end
37
+ end
38
+
39
+ def grid(headings, rows)
40
+ widths = headings.each_index.map { |index| ([headings[index].length] + rows.map { |row| row[index].first.length }).max }
41
+ if output.tty?
42
+ _, columns = output.winsize
43
+ available = columns - 2 * headings.length
44
+ while columns.positive? && widths.sum > available
45
+ index = widths.each_index.max_by { |i| widths[i] - headings[i].length }
46
+ break if widths[index] <= headings[index].length
47
+
48
+ widths[index] -= 1
49
+ end
50
+ end
51
+ [headings.map { |heading| [heading, :heading] }, *rows].each do |row|
52
+ columns = row.each_with_index.map do |(value, _), index|
53
+ value.chars.each_slice(widths[index]).map(&:join)
54
+ end
55
+ columns.map(&:length).max.times do |line|
56
+ cells = row.each_index.map do |index|
57
+ value = columns[index].fetch(line, "")
58
+ paint(index == widths.length - 1 ? value : value.ljust(widths[index]), row[index].last)
59
+ end
60
+ output.puts(" #{cells.join(' ').rstrip}")
61
+ end
62
+ end
63
+ end
64
+
65
+ def section(text)
66
+ output.puts
67
+ output.puts(paint(text, :heading))
68
+ end
69
+
70
+ def build_progress(message, log)
71
+ unless interactive? && color? && !ENV.key?("CI")
72
+ output.puts(message)
73
+ output.flush
74
+ return yield nil
75
+ end
76
+
77
+ frames = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏".chars.cycle
78
+ clear = "\r\e[2K"
79
+ update = lambda do
80
+ _, columns = output.winsize
81
+ width = columns.positive? ? [columns - 1, 1].max : 79
82
+ title = "#{frames.next} #{message}".byteslice(0, width).scrub
83
+ detail = " #{recent_build_activity(log)}".byteslice(0, width).scrub
84
+ output.print(clear, paint(title, :title), "\n", clear, paint(detail, :muted), "\e[1A")
85
+ output.flush
86
+ end
87
+ update.call
88
+ yield update
89
+ ensure
90
+ if update
91
+ output.print("\n", clear, "\e[1A", clear)
92
+ output.puts(message)
93
+ output.flush
94
+ end
95
+ end
96
+
97
+ def screen
98
+ output.print("\e[?1049h\e[?25l")
99
+ output.flush
100
+ input.raw { yield }
101
+ ensure
102
+ output.print("\e[?25h\e[?1049l")
103
+ output.flush
104
+ end
105
+
106
+ def question(prompt, options, default, back:, validate: nil, multiple: false)
107
+ options ? select(prompt, options, default, back, multiple) : edit(prompt, default.to_s, back, validate)
108
+ end
109
+
110
+ private
111
+
112
+ def recent_build_activity(log)
113
+ size = log.size
114
+ length = [8192, size].min
115
+ return "" if length.zero?
116
+
117
+ tail = log.pread(length, size - length).force_encoding(Encoding::UTF_8).scrub
118
+ tail.gsub(/\e(?:\][^\a\e]*(?:\a|\e\\)|\[[0-?]*[ -\/]*[@-~])/, "")
119
+ .split(/[\r\n]/).reverse_each do |line|
120
+ activity = line.gsub(/[[:cntrl:]]/, " ").strip
121
+ return activity unless activity.empty?
122
+ end
123
+ ""
124
+ end
125
+
126
+ def select(prompt, options, default, back, multiple)
127
+ selected = Array(default).dup if multiple
128
+ index = options.index { |value, _| value == (multiple ? selected.first : default) } || 0
129
+ hint = multiple ? "↑/↓ Move · Space Toggle · Enter Confirm" : "↑/↓ Select · Enter Confirm"
130
+ loop do
131
+ height, = input.winsize
132
+ size = [[height - 8, 2].max, options.length].min
133
+ offset = (index / size) * size
134
+ rows = options.slice(offset, size).each_with_index.map do |(value, label), position|
135
+ label = "#{selected.include?(value) ? '☑' : '☐'} #{label}" if multiple
136
+ if position + offset == index
137
+ "#{paint('›', :ok)} #{paint(label, :title)}"
138
+ else
139
+ " #{label}"
140
+ end
141
+ end
142
+ render(prompt, rows, hint, back)
143
+ case key
144
+ when :up then index = (index - 1) % options.length
145
+ when :down then index = (index + 1) % options.length
146
+ when " "
147
+ if multiple
148
+ value = options[index].first
149
+ selected.include?(value) ? selected.delete(value) : selected.push(value)
150
+ end
151
+ when :enter
152
+ return multiple ? options.map(&:first).intersection(selected) : options[index].first
153
+ when :back then return :back if back
154
+ when :cancel then raise Cancelled, "Setup cancelled."
155
+ end
156
+ end
157
+ end
158
+
159
+ def edit(prompt, value, back, validate)
160
+ message = nil
161
+ loop do
162
+ render(prompt, ["#{paint('›', :ok)} #{value}#{paint('▏', :title)}", message].compact, "Enter Confirm", back)
163
+ case (choice = key)
164
+ when :enter
165
+ return value.strip if !validate || validate.call(value.strip)
166
+
167
+ message = paint("Enter a valid value.", :warning)
168
+ when :back then return :back if back
169
+ when :cancel then raise Cancelled, "Setup cancelled."
170
+ when :erase then value = value[0...-1]
171
+ when String then value += choice if choice.match?(/\A[[:print:]]\z/)
172
+ end
173
+ end
174
+ end
175
+
176
+ def render(prompt, rows, hint, back)
177
+ height, width = input.winsize
178
+ width = 80 if width < 1
179
+ height = 24 if height < 1
180
+ guide = [hint, ("Ctrl+U Back" if back), "Ctrl+C Cancel"].compact.join(" · ")
181
+ margin = [(width - guide.length) / 2, 0].max
182
+ output.print("\e[H\e[2J", " ", paint("Ruby Ship", :title), "\r\n\r\n ", prompt, "\r\n\r\n",
183
+ rows.map { |line| " #{line}" }.join("\r\n"), "\e[#{height};1H", " " * margin, paint(guide, :muted))
184
+ output.flush
185
+ end
186
+
187
+ def key
188
+ character = input.getch
189
+ case character
190
+ when "\r", "\n" then :enter
191
+ when "\x15" then :back
192
+ when "\x03", "\x04", nil then :cancel
193
+ when "\x7f", "\x08" then :erase
194
+ when "\e"
195
+ return unless IO.select([input], nil, nil, 0.1)
196
+
197
+ prefix = input.getch
198
+ return unless ["[", "O"].include?(prefix) && IO.select([input], nil, nil, 0.1)
199
+
200
+ { "A" => :up, "B" => :down }[input.getch]
201
+ else character
202
+ end
203
+ end
204
+ end
205
+ end
@@ -0,0 +1,3 @@
1
+ module Ship
2
+ VERSION = "0.1.0"
3
+ end
data/lib/ship.rb ADDED
@@ -0,0 +1,6 @@
1
+ require_relative "ship/version"
2
+ require_relative "ship/application"
3
+ require_relative "ship/extensions"
4
+ require_relative "ship/services"
5
+ require_relative "ship/project"
6
+ require_relative "ship/cli"
@@ -0,0 +1,23 @@
1
+ {
2
+ "centrifugo": ["CENTRIFUGO_API_KEY", "CENTRIFUGO_TOKEN_SECRET", "CENTRIFUGO_URL"],
3
+ "elasticsearch": ["ELASTICSEARCH_HOST", "ELASTICSEARCH_PASSWORD", "ELASTICSEARCH_USERNAME"],
4
+ "garage": ["AWS_ACCESS_KEY_ID", "AWS_BUCKET", "AWS_DEFAULT_REGION", "AWS_ENDPOINT", "AWS_SECRET_ACCESS_KEY", "AWS_USE_PATH_STYLE_ENDPOINT"],
5
+ "mailpit": ["MAIL_HOST", "MAIL_PORT"],
6
+ "mariadb": ["DB_DATABASE", "DB_HOST", "DB_PASSWORD", "DB_PORT", "DB_USERNAME"],
7
+ "meilisearch": ["MEILISEARCH_HOST", "MEILISEARCH_KEY"],
8
+ "memcached": ["MEMCACHED_HOST", "MEMCACHED_PORT"],
9
+ "mercure": ["MERCURE_JWT_ISSUER", "MERCURE_JWT_SECRET", "MERCURE_PUBLIC_URL", "MERCURE_URL"],
10
+ "mongodb": ["MONGODB_DATABASE", "MONGODB_HOST", "MONGODB_PASSWORD", "MONGODB_PORT", "MONGODB_USERNAME"],
11
+ "mysql": ["DB_DATABASE", "DB_HOST", "DB_PASSWORD", "DB_PORT", "DB_USERNAME"],
12
+ "playwright": ["PLAYWRIGHT_BASE_URL", "PW_TEST_CONNECT_WS_ENDPOINT"],
13
+ "postgres": ["DB_DATABASE", "DB_HOST", "DB_PASSWORD", "DB_PORT", "DB_USERNAME"],
14
+ "rabbitmq": ["RABBITMQ_HOST", "RABBITMQ_PASSWORD", "RABBITMQ_PORT", "RABBITMQ_USER", "RABBITMQ_VHOST"],
15
+ "redis": ["REDIS_HOST", "REDIS_PORT", "REDIS_URL"],
16
+ "rustfs": ["AWS_ACCESS_KEY_ID", "AWS_BUCKET", "AWS_DEFAULT_REGION", "AWS_ENDPOINT", "AWS_SECRET_ACCESS_KEY", "AWS_USE_PATH_STYLE_ENDPOINT"],
17
+ "seaweedfs": ["AWS_ACCESS_KEY_ID", "AWS_BUCKET", "AWS_DEFAULT_REGION", "AWS_ENDPOINT", "AWS_SECRET_ACCESS_KEY", "AWS_USE_PATH_STYLE_ENDPOINT"],
18
+ "selenium": ["SELENIUM_REMOTE_URL"],
19
+ "silo": ["AWS_ACCESS_KEY_ID", "AWS_BUCKET", "AWS_DEFAULT_REGION", "AWS_ENDPOINT", "AWS_SECRET_ACCESS_KEY", "AWS_USE_PATH_STYLE_ENDPOINT"],
20
+ "sqlserver": ["DB_DATABASE", "DB_HOST", "DB_PASSWORD", "DB_PORT", "DB_USERNAME"],
21
+ "typesense": ["TYPESENSE_API_KEY", "TYPESENSE_HOST", "TYPESENSE_PORT", "TYPESENSE_PROTOCOL"],
22
+ "valkey": ["REDIS_HOST", "REDIS_PORT", "REDIS_URL"]
23
+ }
@@ -0,0 +1,145 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://raw.githubusercontent.com/ship-ecosystem/spec/main/schemas/ship-release.schema.json",
4
+ "$comment": "The ship-release contract (docs/release-contract.md in https://github.com/ship-ecosystem/spec). Status: draft. Every field below is required because it is part of the first contract. A field added later must NOT be added to any `required` list: readers of older releases won't find it, and the contract says what its absence means. additionalProperties stays open everywhere, because readers ignore fields they don't know.",
5
+ "title": "release.json",
6
+ "description": "Describes one release folder written by a Ship producer (`ship release --tag <tag>`).",
7
+ "type": "object",
8
+ "required": ["format", "app", "tag", "createdAt", "builder", "source", "platform", "compose", "images", "pulledImages", "http", "services", "framework", "runtime", "env", "deploy", "requires", "console"],
9
+ "properties": {
10
+ "format": {"const": "ship-release", "description": "Always \"ship-release\"."},
11
+ "app": {"$ref": "#/$defs/name", "description": "The Compose project name: the release Compose file's top-level `name:`. The same for every release of the project."},
12
+ "tag": {"type": "string", "pattern": "^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$", "description": "The release tag."},
13
+ "createdAt": {"type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$", "description": "RFC 3339 timestamp in UTC."},
14
+ "builder": {
15
+ "type": "object",
16
+ "required": ["package", "version"],
17
+ "properties": {
18
+ "package": {"type": "string", "minLength": 1, "description": "The producer, e.g. \"php-ship/ship\"."},
19
+ "version": {"type": "string", "minLength": 1, "description": "The producer's version."}
20
+ }
21
+ },
22
+ "source": {
23
+ "type": "object",
24
+ "required": ["gitCommit", "dirty"],
25
+ "properties": {
26
+ "gitCommit": {"type": ["string", "null"], "pattern": "^[0-9a-f]{40,64}$", "description": "The commit released; null outside a git repository."},
27
+ "dirty": {"type": ["boolean", "null"], "description": "Whether the work tree had uncommitted changes; null outside a git repository."}
28
+ }
29
+ },
30
+ "platform": {"type": "string", "pattern": "^[a-z0-9]+/[a-z0-9_]+(/[a-z0-9]+)?$", "description": "os/arch[/variant] of every project-owned image."},
31
+ "compose": {"type": "string", "minLength": 1, "description": "Relative path of the Compose file."},
32
+ "images": {
33
+ "type": "array",
34
+ "description": "Project-owned images, one archive each.",
35
+ "items": {
36
+ "type": "object",
37
+ "required": ["ref", "id", "file", "sha256", "services"],
38
+ "properties": {
39
+ "ref": {"type": "string", "minLength": 1},
40
+ "id": {"type": "string", "pattern": "^sha256:[0-9a-f]{64}$"},
41
+ "file": {"$ref": "#/$defs/relativePath"},
42
+ "sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"},
43
+ "services": {"$ref": "#/$defs/names"}
44
+ }
45
+ }
46
+ },
47
+ "pulledImages": {
48
+ "type": "array",
49
+ "description": "Images not built by the producer, pinned by digest.",
50
+ "items": {
51
+ "type": "object",
52
+ "required": ["ref", "services"],
53
+ "properties": {
54
+ "ref": {"type": "string", "pattern": "^[^@\\s]+@sha256:[0-9a-f]{64}$"},
55
+ "services": {"$ref": "#/$defs/names"}
56
+ }
57
+ }
58
+ },
59
+ "http": {
60
+ "type": "array",
61
+ "description": "Services that receive HTTP traffic. Empty when none.",
62
+ "items": {
63
+ "type": "object",
64
+ "required": ["service", "port", "role", "health", "urlSetting"],
65
+ "properties": {
66
+ "service": {"$ref": "#/$defs/name"},
67
+ "port": {"type": "integer", "minimum": 1, "maximum": 65535, "description": "Container port."},
68
+ "role": {"type": "string", "minLength": 1, "description": "Open list: site, websocket. Unknown: plain HTTP."},
69
+ "health": {"type": ["string", "null"], "pattern": "^/", "description": "Path answering 2xx while the service works; null when unknown."},
70
+ "urlSetting": {"type": ["string", "null"], "pattern": "^[A-Za-z_][A-Za-z0-9_]*$", "description": "Name of the setting holding the public address browsers use for this entry; null when unknown. A name, never a value."}
71
+ }
72
+ }
73
+ },
74
+ "services": {
75
+ "type": "object",
76
+ "description": "Every Compose service, by name.",
77
+ "propertyNames": {"$ref": "#/$defs/name"},
78
+ "additionalProperties": {
79
+ "type": "object",
80
+ "required": ["role", "image", "healthcheck", "volumes"],
81
+ "properties": {
82
+ "role": {"type": "string", "minLength": 1, "description": "Open list: app, web, process, infrastructure. Unknown: process."},
83
+ "image": {"type": "string", "minLength": 1, "description": "Equals an images[].ref or a pulledImages[].ref."},
84
+ "healthcheck": {"type": "boolean", "description": "Whether the service has a Compose healthcheck."},
85
+ "volumes": {"$ref": "#/$defs/names", "description": "Named volumes, as declared in Compose (no project prefix)."}
86
+ }
87
+ }
88
+ },
89
+ "framework": {"type": ["string", "null"], "minLength": 1, "description": "Open list, e.g. laravel, symfony, tempest; null when unknown."},
90
+ "runtime": {"type": "string", "minLength": 1, "description": "Open list, e.g. php-fpm, octane-swoole, octane-roadrunner, octane-frankenphp."},
91
+ "env": {
92
+ "type": "object",
93
+ "required": ["file", "keys", "referenced", "required"],
94
+ "properties": {
95
+ "file": {"type": ["string", "null"], "description": "The settings file in the release, or null when it has none."},
96
+ "keys": {"$ref": "#/$defs/variables", "description": "Every key in the producer's production settings. Names only."},
97
+ "referenced": {"$ref": "#/$defs/variables", "description": "Every variable the Compose file interpolates."},
98
+ "required": {"$ref": "#/$defs/variables", "description": "Settings the release can't start without. A subset of keys."}
99
+ }
100
+ },
101
+ "deploy": {
102
+ "type": ["object", "null"],
103
+ "description": "One-off commands to run once per deploy; null when there are none.",
104
+ "required": ["service", "needs", "commands"],
105
+ "properties": {
106
+ "service": {"$ref": "#/$defs/name"},
107
+ "needs": {"$ref": "#/$defs/names"},
108
+ "commands": {
109
+ "type": "array",
110
+ "minItems": 1,
111
+ "items": {"type": "array", "minItems": 1, "items": {"type": "string"}, "description": "An argv."}
112
+ }
113
+ }
114
+ },
115
+ "console": {
116
+ "type": "object",
117
+ "description": "How to run commands in the running app: the service, the user to run them as, its shell, and the framework's console commands.",
118
+ "required": ["service", "user", "shell", "commands"],
119
+ "properties": {
120
+ "service": {"$ref": "#/$defs/name", "description": "The service to run commands in."},
121
+ "user": {"type": "string", "minLength": 1, "description": "The user to run every command and shell as, so files they create stay writable by the app."},
122
+ "shell": {"type": "array", "minItems": 1, "items": {"type": "string", "minLength": 1}, "description": "An interactive shell's argv."},
123
+ "commands": {
124
+ "type": "object",
125
+ "description": "The framework's console commands, by name: argv prefixes the arguments are appended to. Empty when unknown.",
126
+ "propertyNames": {"pattern": "^[a-z][a-z0-9:_-]*$"},
127
+ "additionalProperties": {"type": "array", "minItems": 1, "items": {"type": "string", "minLength": 1}}
128
+ }
129
+ }
130
+ },
131
+ "requires": {
132
+ "type": "object",
133
+ "required": ["networks"],
134
+ "properties": {
135
+ "networks": {"type": "array", "items": {"type": "string", "minLength": 1}, "description": "External Docker networks that must exist."}
136
+ }
137
+ }
138
+ },
139
+ "$defs": {
140
+ "name": {"type": "string", "pattern": "^[a-z0-9][a-z0-9_-]*$"},
141
+ "names": {"type": "array", "items": {"$ref": "#/$defs/name"}},
142
+ "variables": {"type": "array", "items": {"type": "string", "pattern": "^[A-Za-z_][A-Za-z0-9_]*$"}},
143
+ "relativePath": {"type": "string", "pattern": "^(?!/)(?!.*(^|/)\\.\\.(/|$)).+$"}
144
+ }
145
+ }