Implement main function

This commit is contained in:
Late Night Defender 2024-06-01 18:03:55 +07:00
parent 9e68a7f6d0
commit 663d89bded
2 changed files with 121 additions and 0 deletions

3
go.mod Normal file
View file

@ -0,0 +1,3 @@
module main
go 1.22.3

118
main.go Normal file
View file

@ -0,0 +1,118 @@
package main
import (
"bufio"
"flag"
"fmt"
"os"
"os/exec"
)
var verbosePtr = flag.Bool("v", false, "boolean")
func ExecSystem(command string) {
if *verbosePtr{
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())
}
} else {
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())
}
}
}
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)
}
if len(os.Args) == 1 {
fmt.Println("Usage: compose-runner [-v] [path]")
os.Exit(2)
}
if len(os.Args) == 2 {
if *verbosePtr {
workDir, err := os.Getwd()
if err != nil {
panic(err)
}
os.Chdir(workDir)
ExecSystem("docker compose up -d")
} else {
workDir := os.Args[1]
os.Chdir(workDir)
ExecSystem("docker compose up -d")
}
}
if len(os.Args) == 3 {
if os.Args[1] == "-v" {
workDir := os.Args[2]
os.Chdir(workDir)
ExecSystem("docker compose up -d")
} else {
workDir := os.Args[1]
os.Chdir(workDir)
ExecSystem("docker compose up -d")
}
}
}