simple-compose-runner/main.go

130 lines
2.8 KiB
Go
Raw Normal View History

2024-06-01 11:03:55 +00:00
package main
import (
"bufio"
"flag"
"fmt"
"os"
"os/exec"
)
var verbosePtr = flag.Bool("v", false, "boolean")
func ExecSystemFull(command string) {
2024-06-01 11:03:55 +00:00
cmd := exec.Command("/usr/bin/bash", "-c", command)
stdout, err := cmd.StdoutPipe()
if err != nil {
fmt.Println("Error obtaining stdout pipe:", err)
return
}
stderr, err := cmd.StderrPipe()
if err != nil {
fmt.Println("Error obtaining stderr pipe:", err)
return
}
// Start the command
if err := cmd.Start(); err != nil {
fmt.Println("Error starting command:", err)
return
}
// Read the output line by line
stdoutScanner := bufio.NewScanner(stdout)
stderrScanner := bufio.NewScanner(stderr)
for stdoutScanner.Scan() {
fmt.Println(stdoutScanner.Text())
}
for stderrScanner.Scan() {
fmt.Println(stderrScanner.Text())
}
}
func ExecSystemErr(command string) {
2024-06-01 11:03:55 +00:00
cmd := exec.Command("/usr/bin/bash", "-c", command)
stderr, err := cmd.StderrPipe()
if err != nil {
fmt.Println("Error obtaining stderr pipe:", err)
return
}
// Start the command
if err := cmd.Start(); err != nil {
fmt.Println("Error starting command:", err)
return
}
// Read the output line by line
stderrScanner := bufio.NewScanner(stderr)
for stderrScanner.Scan() {
fmt.Println(stderrScanner.Text())
}
}
2024-06-01 11:03:55 +00:00
func main() {
flag.Parse()
maxArgs := 3
if len(os.Args) > maxArgs {
fmt.Printf("Error: Too many arguments. Expected at most %d, got %d\n", maxArgs, len(os.Args))
os.Exit(1)
}
// ./compose-runner should run docker compose up -d in current working directory
2024-06-01 11:03:55 +00:00
if len(os.Args) == 1 {
workDir, err := os.Getwd()
if err != nil {
panic(err)
}
os.Chdir(workDir)
fmt.Println("[1] Running docker compose up -d in", workDir)
ExecSystemErr("docker compose up -d")
ExecSystemFull("docker compose ps")
2024-06-01 11:03:55 +00:00
}
if len(os.Args) == 2 {
// ./compose-runner -v should run docker compose up -d in current working directory, verbose output
2024-06-01 11:03:55 +00:00
if *verbosePtr {
workDir, err := os.Getwd()
if err != nil {
panic(err)
}
os.Chdir(workDir)
fmt.Println("[2v] Running docker compose up -d in", workDir)
ExecSystemFull("docker compose up -d")
ExecSystemFull("docker compose ps")
2024-06-01 11:03:55 +00:00
} else {
// ./compose-runner /path should run docker compose up -d in /path
2024-06-01 11:03:55 +00:00
workDir := os.Args[1]
os.Chdir(workDir)
fmt.Println("[2] Running docker compose up -d in", workDir)
ExecSystemErr("docker compose up -d")
ExecSystemFull("docker compose ps")
2024-06-01 11:03:55 +00:00
}
}
// ./compose-runner -v /path should run docker compose up -d in /path, verbose output
2024-06-01 11:03:55 +00:00
if len(os.Args) == 3 {
workDir := os.Args[2]
os.Chdir(workDir)
fmt.Println("[3] Running docker compose up -d in", workDir)
ExecSystemFull("docker compose up -d")
ExecSystemFull("docker compose ps")
2024-06-01 11:03:55 +00:00
}
}