Class: Stable::CLI

Inherits:
Thor
  • Object
show all
Defined in:
lib/stable/cli.rb

Constant Summary collapse

HOSTS_FILE =
'/etc/hosts'

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeCLI

Returns a new instance of CLI.



15
16
17
18
19
20
# File 'lib/stable/cli.rb', line 15

def initialize(*)
  super
  Stable::Bootstrap.run!
  ensure_dependencies!
  dedupe_registry!
end

Class Method Details

.exit_on_failure?Boolean

Returns:

  • (Boolean)


22
23
24
# File 'lib/stable/cli.rb', line 22

def self.exit_on_failure?
  true
end

Instance Method Details

#add(folder) ⇒ Object



206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
# File 'lib/stable/cli.rb', line 206

def add(folder)
  folder = File.expand_path(folder)
  unless File.exist?(File.join(folder, 'config', 'application.rb'))
    puts "Not a Rails app: #{folder}"
    return
  end

  puts "Detected gemset: #{File.read('.ruby-gemset').strip}" if File.exist?('.ruby-gemset')

  apps = Registry.apps
  name = File.basename(folder)
  domain = "#{name}.test"

  if apps.any? { |a| a[:path] == folder }
    puts "App already exists: #{name}"
    return
  end

  port = next_free_port
  ruby = detect_ruby_version(folder)

  apps << { name: name, path: folder, domain: domain, port: port, ruby: ruby }
  Registry.save(apps)
  puts "Added #{name} -> https://#{domain} (port #{port})"

  add_host_entry(domain)
  generate_cert(domain)
  update_caddyfile(domain, port)
  caddy_reload
end

#caddy_reloadObject



333
334
335
336
337
338
339
340
# File 'lib/stable/cli.rb', line 333

def caddy_reload
  if system('which caddy > /dev/null')
    system("caddy reload --config #{Stable::Paths.caddyfile}")
    puts 'Caddy reloaded'
  else
    puts 'Caddy not found. Install Caddy first.'
  end
end

#doctorObject



355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
# File 'lib/stable/cli.rb', line 355

def doctor
  puts "Stable doctor\n\n"

  puts "Ruby version: #{RUBY_VERSION}"
  puts "RVM: #{rvm_available? ? 'yes' : 'no'}"
  puts "rbenv: #{rbenv_available? ? 'yes' : 'no'}"
  puts "Caddy: #{system('which caddy > /dev/null') ? 'yes' : 'no'}"
  puts "mkcert: #{system('which mkcert > /dev/null') ? 'yes' : 'no'}"

  Registry.apps.each do |app|
    state = boot_state(app)
    ruby  = app[:ruby] || 'default'
    port  = app[:port]

    puts "#{app[:name]} → Ruby #{ruby} | port #{port} | #{state}"
  end
end

#listObject



194
195
196
197
198
199
200
201
202
203
# File 'lib/stable/cli.rb', line 194

def list
  apps = Registry.apps
  if apps.empty?
    puts 'No apps found.'
  else
    apps.each do |app|
      puts "#{app[:name]} -> https://#{app[:domain]}"
    end
  end
end

#new(name, ruby: RUBY_VERSION, rails: nil, port: nil) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
# File 'lib/stable/cli.rb', line 34

def new(name, ruby: RUBY_VERSION, rails: nil, port: nil)
  port ||= next_free_port
  app_path = File.expand_path(name)

  # --- Add app to registry ---
  domain = "#{name}.test"
  apps = Registry.apps

  app = {
    name: name,
    path: app_path,
    domain: domain,
    port: port,
    ruby: ruby,
    started_at: nil
  }

  apps.reject! { |a| a[:name] == name }
  apps << app

  abort "Folder already exists: #{app_path}" if File.exist?(app_path)

  # --- Ensure RVM and Ruby ---
  ensure_rvm!
  puts "Using Ruby #{ruby} with RVM gemset #{name}..."
  system("bash -lc 'rvm #{ruby}@#{name} --create do true'") or abort("Failed to create RVM gemset #{name}")
  ruby_cmd = rvm_exec(app, ruby)
  # --- Install Rails in gemset if needed ---
  rails_version = rails || 'latest'
  rails_check = system("bash -lc '#{ruby_cmd} gem list -i rails#{rails ? " -v #{rails}" : ''}'")
  unless rails_check
    puts "Installing Rails #{rails_version} in gemset..."
    system("bash -lc '#{ruby_cmd} gem install rails #{rails ? "-v #{rails}" : ''}'") or abort('Failed to install Rails')
  end

  # --- Create Rails app ---
  puts "Creating Rails app #{name} (Ruby #{ruby})..."
  system("bash -lc '#{ruby_cmd} rails new #{app_path}'") or abort('Rails app creation failed')

  # --- Add .ruby-version and .ruby-gemset ---
  Dir.chdir(app_path) do
    File.write('.ruby-version', "#{ruby}\n")
    File.write('.ruby-gemset', "#{name}\n")

    # --- Install gems inside gemset ---
    puts 'Running bundle install...'
    system("bash -lc '#{ruby_cmd} bundle install --jobs=4 --retry=3'") or abort('bundle install failed')
  end

  # --- Database integration ---
  if options[:db]
    adapter = if options[:postgres]
                :postgresql
              elsif options[:mysql]
                :mysql
              else
                :postgresql
              end

    adapter == :postgresql ? 'postgresql' : 'mysql2'
    gem_name = adapter == :postgresql ? 'pg' : 'mysql2'

    gemfile_path = File.join(app_path, 'Gemfile')
    unless File.read(gemfile_path).include?(gem_name)
      File.open(gemfile_path, 'a') do |f|
        f.puts "\n# Added by Stable CLI"
        f.puts "gem '#{gem_name}'"
      end
      puts "✅ Added '#{gem_name}' gem to Gemfile"
    end

    # Ensure the gem is installed inside the gemset
    system("bash -lc 'cd #{app_path} && rvm #{ruby}@#{name} do bundle install --jobs=4 --retry=3'") or abort('bundle install failed')

    # --- Database setup ---
    db = Stable::DBManager.new(options[:db], adapter: adapter)
    creds = []

    case adapter
    when :postgresql
      db.create
    when :mysql
      creds = create_mysql_db(options[:db]) # creates DB and returns creds
      # Make sure mysql2 gem is loaded for Rails
      system("bash -lc 'cd #{app_path} && rvm #{ruby}@#{name} do bundle exec gem list | grep mysql2'") || abort('mysql2 gem not found in gemset')
    end

    # --- Generate database.yml ---
    db_config_path = File.join(app_path, 'config', 'database.yml')
    base_config = {
      'adapter' => adapter == :postgresql ? 'postgresql' : 'mysql2',
      'encoding' => adapter == :postgresql ? 'unicode' : 'utf8mb4',
      'pool' => 5,
      'database' => options[:db],
      'username' => adapter == :mysql ? creds[:user] : nil,
      'password' => adapter == :mysql ? creds[:password] : nil,
      'host' => 'localhost',
      'auth_plugin' => adapter == :mysql ? 'caching_sha2_password' : ''
    }

    db_configs = {
      'default' => base_config,
      'development' => base_config,
      'test' => base_config.merge('database' => "#{options[:db]}_test"),
      'production' => base_config.merge('database' => "#{options[:db]}_prod")
    }

    File.write(db_config_path, db_configs.to_yaml)
    puts "✅ Database '#{db.name}' configured in Rails app"

    # --- Prepare the database ---
    puts 'Preparing database...'
    system("bash -lc 'cd #{app_path} && rvm #{ruby}@#{name} do bundle exec rails db:prepare'") or abort('Database preparation failed')
  end

  # --- Generate Caddyfile ---

  puts 'Refreshing bundle environment...'
  system(
    "bash -lc 'cd #{app_path} && #{ruby_cmd} bundle check || #{ruby_cmd} bundle install'"
  ) or abort('Bundler setup failed')

  puts 'Preparing database...'
  system(
    "bash -lc 'cd #{app_path} && #{ruby_cmd} bundle exec rails db:prepare'"
  ) or abort('Database preparation failed')

  # --- Host entry & certificate ---
  add_host_entry(domain)
  generate_cert(domain) unless options[:skip_ssl]
  update_caddyfile(domain, port)
  ensure_caddy_running!
  caddy_reload

  # --- Start Rails server ---
  puts "Starting Rails server for #{name} on port #{port}..."
  log_file = File.join(app_path, 'log', 'stable.log')
  FileUtils.mkdir_p(File.dirname(log_file))

  abort "Port #{port} is already in use. Choose another port." if app_running?({ port: port })

  pid = spawn(
    'bash',
    '-lc',
    "cd #{app_path} && #{ruby_cmd} bundle exec rails s -p #{port} -b 127.0.0.1",
    out: log_file,
    err: log_file
  )
  Process.detach(pid)

  app[:started_at] = Time.now.to_i
  Registry.save(apps)

  sleep 1.5

  wait_for_port(port)
  puts "#{name} running at https://#{domain}"
end

#remove(name) ⇒ Object



238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
# File 'lib/stable/cli.rb', line 238

def remove(name)
  apps = Registry.apps
  app = apps.find { |a| a[:name] == name }
  if app.nil?
    puts "No app found with name #{name}"
    return
  end

  new_apps = apps.reject { |a| a[:name] == name }
  Registry.save(new_apps)
  puts "Removed #{name}"

  remove_host_entry(app[:domain])
  remove_caddy_entry(app[:domain])
  caddy_reload
end

#secure(domain) ⇒ Object



343
344
345
346
347
348
349
350
351
352
# File 'lib/stable/cli.rb', line 343

def secure(domain)
  app = Registry.apps.find { |a| a[:domain] == domain }
  unless app
    puts "No app found with domain #{domain}"
    return
  end
  secure_app(domain, app[:path], app[:port])
  caddy_reload
  puts "Secured https://#{domain}"
end

#setupObject



325
326
327
328
329
330
# File 'lib/stable/cli.rb', line 325

def setup
  FileUtils.mkdir_p(Stable::Paths.root)
  File.write(Stable::Paths.caddyfile, '') unless File.exist?(Stable::Paths.caddyfile)
  ensure_caddy_running!
  puts "Caddy home initialized at #{Stable::Paths.root}"
end

#start(name) ⇒ Object



256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
# File 'lib/stable/cli.rb', line 256

def start(name)
  app = Registry.apps.find { |a| a[:name] == name }
  return puts("No app found with name #{name}") unless app

  port = app[:port] || next_free_port
  ruby = app[:ruby]
  path = app[:path]

  if app_running?(app)
    puts "#{name} is already running on https://#{app[:domain]} (port #{port})"
    return
  end

  gemset = gemset_for(app)

  rvm_cmd =
    if ruby && gemset
      system("bash -lc 'rvm #{ruby}@#{gemset} --create do true'")
      "rvm #{ruby}@#{gemset} do"
    elsif ruby
      "rvm #{ruby} do"
    end

  puts "Starting #{name} on port #{port}..."

  log_file = File.join(path, 'log', 'stable.log')
  FileUtils.mkdir_p(File.dirname(log_file))

  pid = spawn(
    'bash',
    '-lc',
    <<~CMD,
      cd "#{path}"
      #{rvm_cmd} bundle exec rails s \
        -p #{port} \
        -b 127.0.0.1
    CMD
    out: log_file,
    err: log_file
  )

  Process.detach(pid)

  wait_for_port(port, timeout: 30)

  app[:started_at] = Time.now.to_i
  Registry.save(Registry.apps)

  generate_cert(app[:domain])
  update_caddyfile(app[:domain], port)
  caddy_reload

  puts "#{name} started on https://#{app[:domain]}"
end

#stop(name) ⇒ Object



312
313
314
315
316
317
318
319
320
321
322
# File 'lib/stable/cli.rb', line 312

def stop(name)
  app = Registry.apps.find { |a| a[:name] == name }

  output = `lsof -i tcp:#{app[:port]} -t`.strip
  if output.empty?
    puts "No app running on port #{app[:port]}"
  else
    output.split("\n").each { |pid| Process.kill('TERM', pid.to_i) }
    puts "Stopped #{name}"
  end
end

#upgrade_ruby(name, version) ⇒ Object



374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
# File 'lib/stable/cli.rb', line 374

def upgrade_ruby(name, version)
  app = Registry.apps.find { |a| a[:name] == name }
  unless app
    puts "No app named #{name}"
    return
  end

  if rvm_available?
    system("bash -lc 'rvm install #{version}'")
  elsif rbenv_available?
    system("rbenv install #{version}")
  else
    puts 'No Ruby version manager found'
    return
  end

  File.write(File.join(app[:path], '.ruby-version'), version)
  app[:ruby] = version
  Registry.save(Registry.apps)

  puts "#{name} now uses Ruby #{version}"
end