-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransform.go
75 lines (63 loc) · 1.88 KB
/
transform.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
package main
import (
"os"
"path/filepath"
"strings"
)
// CompileCommandEntry is a single entry of the compile_commands.json database.
type CompileCommandEntry struct {
Directory string `json:"directory"`
Arguments []string `json:"arguments,omitempty"`
File string `json:"file"`
Command string `json:"command,omitempty"`
Output string `json:"output,omitempty"`
}
// Transformer converts the Please structure into a flat list of entries
// of CompileCommands.
type Transformer struct {
RootDirectory string
}
// Transform transforms the call graph with the config to
func (t Transformer) Transform(graph *PleaseGraph, config *PleaseConfig) []CompileCommandEntry {
output := []CompileCommandEntry{}
for pkgName, pkg := range graph.Packages {
// skip the builtin _please package
if pkgName == "_please" {
continue
}
for targetName, target := range pkg.Targets {
// filter out anything that doesn't have a #cc label
if !strings.HasSuffix(targetName, "cc") {
continue
}
// generate outputs for each file
for _, input := range target.Inputs {
output = append(output, CompileCommandEntry{
File: filepath.Join(t.RootDirectory, input),
Directory: filepath.Join(t.RootDirectory, filepath.Dir(input)),
Command: t.expandCommand(target),
})
}
}
}
return output
}
func (t Transformer) expandCommand(target *PleaseTarget) string {
expandFunction := func(varName string) string {
if strings.HasPrefix(varName, "TOOLS") {
_, after, _ := strings.Cut(varName, "TOOLS_")
toolName := strings.ToLower(after)
return target.ToolForName(toolName)
}
if strings.HasPrefix(varName, "SRCS") {
return target.AllSources()
}
if varName == "OUTS" {
return strings.Join(target.Outs, " ")
}
return ""
}
before, _, _ := strings.Cut(target.Command, "&&")
command := os.Expand(before, expandFunction)
return command
}