-
-
Save idabmat/59e08ae6ddb1e169ff07494990d62f90 to your computer and use it in GitHub Desktop.
dockerized PG
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/env ruby | |
require "thor" | |
require "json" | |
class PG < Thor | |
package_name "Dockerized PG" | |
include Thor::Actions | |
def self.exit_on_failure? | |
true | |
end | |
desc "up [VERSION] [PORT]", "Start latest or VERSION of a postgresql server on port 5432 or PORT." | |
def up(version = "latest", port = "5432") | |
say "Starting postgres version " | |
say version + " ", :magenta | |
say "on port " | |
say port, :yellow | |
run "docker run -d -p #{port}:5432 -l dockerized-postgresql -e POSTGRES_HOST_AUTH_METHOD=trust postgres:#{version}", capture: true, verbose: false | |
say "Started", :green | |
rescue SystemExit => e | |
say "Not started", :red | |
say "Is there a server already running on port #{port}?" | |
raise e | |
end | |
desc "down", "Stop postgresql server" | |
def down | |
instances = list_instances | |
return say "No instances running", :red if instances.length == 0 | |
instances.each { |instance| stop_instance(instance) } | |
end | |
desc "status", "Shows the status of the postgresql server" | |
def status | |
instances = list_instances | |
return say "No instances running", :red if instances.length == 0 | |
instances.each { |instance| print_instance(instance) } | |
end | |
private | |
def list_instances | |
`docker ps -f label=dockerized-postgresql --format json` | |
.split("\n") | |
.map { |line| JSON.parse(line) } | |
end | |
def print_instance(instance) | |
info = JSON.parse(`docker inspect #{instance["ID"]}`) | |
port = info.dig(0, "HostConfig", "PortBindings", "5432/tcp", 0, "HostPort") | |
status = info.dig(0, "State", "Status") | |
version = info.dig(0, "Config", "Image").split(":").last | |
say "Found version " | |
say version + " ", :magenta | |
say status + " on port " | |
say port, :yellow | |
end | |
def stop_instance(instance) | |
print_instance(instance) | |
return say "Skipping...", :yellow unless yes?("Stop it? [yN]") | |
`docker stop #{instance["ID"]}` | |
say "Stopped", :green | |
end | |
end | |
PG.start(ARGV) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment