-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
98 lines (83 loc) · 2.62 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
package lang_c
import (
"fmt"
"os/exec"
"strings"
"github.com/spectrevert/doze"
)
func init() {
doze.RegisterProcedure(ObjectFile{})
doze.RegisterProcedure(Executable{})
}
type ObjectFile struct {
}
func (ObjectFile) GetProcedureInfo() doze.ProcedureInfo {
return doze.ProcedureInfo{
ID: "lang:c:object_file",
New: func() doze.Procedure { return new(ObjectFile) },
}
}
// ObjectFile.Execute creates an object file from the C source code file passed to it.
// Inputs must contain exactly one '.c' file and outputs must contain exactly one '.o' file.
// Any amount of headers are accepted in the inputs (and ignored).
func (ObjectFile) Execute(rule *doze.Rule) error {
var sourceFile, objectFile string
for _, input := range rule.Inputs {
if strings.HasSuffix(input.NormalizedTag(), ".c") {
if sourceFile != "" {
return fmt.Errorf("found more than one '.c' file in rule %v", rule)
}
sourceFile = input.NormalizedTag()
} else if !strings.HasSuffix(input.NormalizedTag(), ".h") {
return fmt.Errorf("found a non-c source code file declared in rule %v", rule)
}
}
for _, output := range rule.Outputs {
if strings.HasSuffix(output.NormalizedTag(), ".o") {
if objectFile != "" {
return fmt.Errorf("found more than one '.o' file in rule %v", rule)
}
objectFile = output.NormalizedTag()
} else {
return fmt.Errorf("found a non-c object file declared in rule %v", rule)
}
}
cmd := exec.Command("gcc", "-c", sourceFile, "-o", objectFile)
if err := cmd.Run(); err != nil {
return fmt.Errorf("error executing 'gcc': %v", err)
}
fmt.Println("doze: gcc -o", objectFile, "-c", sourceFile)
return nil
}
type Executable struct {
}
func (Executable) GetProcedureInfo() doze.ProcedureInfo {
return doze.ProcedureInfo{
ID: "lang:c:executable",
New: func() doze.Procedure { return new(Executable) },
}
}
func (Executable) Execute(rule *doze.Rule) error {
var inputs []string
for _, input := range rule.Inputs {
if !strings.HasSuffix(input.NormalizedTag(), ".o") {
return fmt.Errorf("found a non-c object fiel declared in rule %v", rule)
}
inputs = append(inputs, input.NormalizedTag())
}
if len(rule.Outputs) > 1 {
return fmt.Errorf("found more than one output in rule %v", rule)
}
var executable = rule.Outputs[0].NormalizedTag()
args := []string{"-o", executable}
args = append(args, inputs...)
cmd := exec.Command("gcc", args...)
if err := cmd.Run(); err != nil {
return fmt.Errorf("error executing 'gcc': %v", err)
}
fmt.Println("doze: gcc", "-o", executable, inputs)
return nil
}
// interface guard
var _ doze.Procedure = (*ObjectFile)(nil)
var _ doze.Procedure = (*Executable)(nil)