-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
103 lines (82 loc) · 1.92 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
package main
import (
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"os/exec"
"path/filepath"
"regexp"
"github.com/creack/pty"
)
func makefileHasTarget(target string, path string) (bool, error) {
fileContent, err := ioutil.ReadFile(path)
if err != nil {
return false, err
}
stringMatch := fmt.Sprintf(`\n?%s:`, target)
return regexp.Match(stringMatch, fileContent)
}
func exists(name string) (bool, error) {
_, err := os.Stat(name)
if errors.Is(err, os.ErrNotExist) {
return false, nil
}
return err == nil, err
}
func findMakeFileWithTarget(cwd, target string) (string, error) {
makefilePath := filepath.Join(cwd, "Makefile")
hasMakefile, err := exists(makefilePath)
if err != nil {
return "", err
}
if hasMakefile {
commandExists, err := makefileHasTarget(target, makefilePath)
if err != nil {
return "", err
}
if commandExists {
return cwd, nil
}
}
isGitRoot, err := exists(filepath.Join(cwd, ".git"))
if err != nil {
return "", err
}
if !isGitRoot && cwd != "/" {
parentDir := filepath.Dir(cwd)
return findMakeFileWithTarget(parentDir, target)
} else {
return "", fmt.Errorf("Stopped at %v and found no make target '%v'", cwd, target)
}
}
func runMake(dir string, args ...string) error {
dirCommand := []string{"-C", dir}
allArgs := append(dirCommand, args...)
cmd := exec.Command("make", allArgs...)
f, err := pty.Start(cmd)
if err != nil {
return err
}
io.Copy(os.Stdout, f)
return nil
}
func main() {
if len(os.Args[1:]) < 1 {
log.Fatalln("You must provide a make target")
}
cwd, err := os.Getwd()
if err != nil {
log.Fatalln("Could not get current working directory:", err)
}
makeFileDir, err := findMakeFileWithTarget(cwd, os.Args[1])
if err != nil {
log.Fatalln("Could not find a makefile:", err)
}
err = runMake(makeFileDir, os.Args[1:]...)
if err != nil {
log.Fatalf("Could not run makefile in %v: %v\n", makeFileDir, err)
}
}