/
main.go
111 lines (88 loc) · 2.24 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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
package main
import (
"fmt"
"os"
"os/exec"
"strings"
"gopkg.in/yaml.v2"
)
type Command struct {
Name string
Description string
Command string
}
type Include struct {
Commands []Command `yaml:"commands"`
Include []string `yaml:"include"`
}
func parseYaml(yamlFile string) ([]Command, error) {
data, err := os.ReadFile(yamlFile)
if err != nil {
return nil, err
}
var includes Include
err = yaml.Unmarshal(data, &includes)
if err != nil {
return nil, err
}
commands := includes.Commands
for _, includeFile := range includes.Include {
includeCommands, err := parseYaml(includeFile) // Treat included files the same as the main file
if err != nil {
return nil, err
}
commands = append(commands, includeCommands...)
}
return commands, nil
}
func listCommands(commands []Command) {
teal := "\033[1;36m"
white := "\033[0;37m"
reset := "\033[0m"
fmt.Printf("\nBKN (bacon): A better Make using Golang\n\n")
fmt.Printf("-----\nAvailable commands:\n-----\n\n")
longestName := 0
for _, cmd := range commands {
if len(cmd.Name) > longestName {
longestName = len(cmd.Name)
}
}
for _, cmd := range commands {
padding := longestName - len(cmd.Name) + 5
spaces := strings.Repeat(" ", padding)
fmt.Printf("%s%s%s%s%s%s\n", teal, cmd.Name, reset, spaces, white, cmd.Description)
}
}
func executeCommand(command Command, variable string) {
cmdStr := strings.Replace(command.Command, "<variable>", variable, -1)
cmd := exec.Command("sh", "-c", cmdStr)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Run()
if err != nil {
fmt.Printf("Failed to execute command: %s\n", err)
}
}
func main() {
commands, err := parseYaml("bkn.yaml")
if err != nil {
fmt.Printf("Failed to parse YAML file: %s\n", err)
os.Exit(1)
}
if len(os.Args) == 1 || os.Args[1] == "--help" {
listCommands(commands)
return
}
option := os.Args[1]
variable := ""
if len(os.Args) > 2 {
variable = os.Args[2]
}
for _, cmd := range commands {
if cmd.Name == option {
executeCommand(cmd, variable)
return
}
}
fmt.Printf("Invalid option: %s\n", option)
}