blob: e563fd9a54e849be949938374f25ecdd4030fd45 [file] [log] [blame]
Shinichiro Hamajib69bf8a2015-06-10 14:52:06 +09001// Copyright 2015 Google Inc. All rights reserved
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Fumitoshi Ukai744bb2b2015-06-25 00:10:52 +090015package kati
Shinichiro Hamaji6aa86ac2015-05-26 15:21:11 +090016
17import (
18 "bytes"
19 "fmt"
20 "os"
Shinichiro Hamaji11c45842015-05-27 19:02:07 +090021 "path/filepath"
Shinichiro Hamajibcecb502015-06-04 16:20:25 +090022 "regexp"
23 "runtime"
Fumitoshi Ukaie08e9ee2015-07-13 13:14:41 +090024 "sort"
Shinichiro Hamaji6aa86ac2015-05-26 15:21:11 +090025 "strings"
Fumitoshi Ukai49599e52015-06-26 10:10:24 +090026 "time"
Shinichiro Hamaji6aa86ac2015-05-26 15:21:11 +090027)
28
Fumitoshi Ukaib79b2902015-07-16 16:40:09 +090029// NinjaGenerator generates ninja build files from DepGraph.
30type NinjaGenerator struct {
Fumitoshi Ukaid4a016e2015-07-27 16:50:00 +090031 // Args is original arguments to generate the ninja file.
32 Args []string
33 // Suffix is suffix for generated files.
34 Suffix string
Fumitoshi Ukaib79b2902015-07-16 16:40:09 +090035 // GomaDir is goma directory. If empty, goma will not be used.
36 GomaDir string
Fumitoshi Ukaib92f0282015-07-21 14:05:51 +090037 // DetectAndroidEcho detects echo as description.
38 DetectAndroidEcho bool
Fumitoshi Ukaid4a016e2015-07-27 16:50:00 +090039 // ErrorOnEnvChange cause error when env change is detected when run ninja.
40 ErrorOnEnvChange bool
Fumitoshi Ukaib79b2902015-07-16 16:40:09 +090041
Shinichiro Hamaji30a02ad2015-05-29 14:56:43 +090042 f *os.File
43 nodes []*DepNode
Shinichiro Hamaji30a02ad2015-05-29 14:56:43 +090044 exports map[string]bool
Fumitoshi Ukaia70b4ea2015-06-30 15:31:49 +090045
46 ctx *execContext
47
Fumitoshi Ukaie08e9ee2015-07-13 13:14:41 +090048 ruleID int
49 done map[string]bool
50 shortNames map[string][]string
Shinichiro Hamaji6aa86ac2015-05-26 15:21:11 +090051}
52
Fumitoshi Ukaib79b2902015-07-16 16:40:09 +090053func (n *NinjaGenerator) init(g *DepGraph) {
54 n.nodes = g.nodes
55 n.exports = g.exports
56 n.ctx = newExecContext(g.vars, g.vpaths, true)
57 n.done = make(map[string]bool)
58 n.shortNames = make(map[string][]string)
Shinichiro Hamaji6aa86ac2015-05-26 15:21:11 +090059}
60
Shinichiro Hamaji74ab4b62015-05-28 22:56:24 +090061func getDepfileImpl(ss string) (string, error) {
Shinichiro Hamaji6dca2202015-05-27 18:00:34 +090062 tss := ss + " "
Fumitoshi Ukaib8b80502015-07-21 14:28:26 +090063 if (!strings.Contains(tss, " -MD ") && !strings.Contains(tss, " -MMD ")) || !strings.Contains(tss, " -c ") {
Shinichiro Hamaji6dca2202015-05-27 18:00:34 +090064 return "", nil
65 }
66
67 mfIndex := strings.Index(ss, " -MF ")
68 if mfIndex >= 0 {
69 mf := trimLeftSpace(ss[mfIndex+4:])
70 if strings.Index(mf, " -MF ") >= 0 {
71 return "", fmt.Errorf("Multiple output file candidates in %s", ss)
72 }
73 mfEndIndex := strings.IndexAny(mf, " \t\n")
74 if mfEndIndex >= 0 {
75 mf = mf[:mfEndIndex]
76 }
77
Shinichiro Hamaji6dca2202015-05-27 18:00:34 +090078 return mf, nil
79 }
80
81 outIndex := strings.Index(ss, " -o ")
82 if outIndex < 0 {
83 return "", fmt.Errorf("Cannot find the depfile in %s", ss)
84 }
85 out := trimLeftSpace(ss[outIndex+4:])
86 if strings.Index(out, " -o ") >= 0 {
87 return "", fmt.Errorf("Multiple output file candidates in %s", ss)
88 }
89 outEndIndex := strings.IndexAny(out, " \t\n")
90 if outEndIndex >= 0 {
91 out = out[:outEndIndex]
92 }
93 return stripExt(out) + ".d", nil
94}
95
Fumitoshi Ukai923b1282015-07-13 12:53:30 +090096// getDepfile gets depfile from cmdline, and returns cmdline and depfile.
97func getDepfile(cmdline string) (string, string, error) {
Shinichiro Hamaji74ab4b62015-05-28 22:56:24 +090098 // A hack for Android - llvm-rs-cc seems not to emit a dep file.
Fumitoshi Ukai923b1282015-07-13 12:53:30 +090099 if strings.Contains(cmdline, "bin/llvm-rs-cc ") {
100 return cmdline, "", nil
Shinichiro Hamaji74ab4b62015-05-28 22:56:24 +0900101 }
102
Fumitoshi Ukai923b1282015-07-13 12:53:30 +0900103 depfile, err := getDepfileImpl(cmdline)
104 if depfile == "" || err != nil {
105 return cmdline, depfile, err
Shinichiro Hamaji74ab4b62015-05-28 22:56:24 +0900106 }
107
Shinichiro Hamaji3438ae32015-06-05 11:33:20 +0900108 // A hack for Makefiles generated by automake.
Fumitoshi Ukai923b1282015-07-13 12:53:30 +0900109 mvCmd := "(mv -f " + depfile + " "
110 if i := strings.LastIndex(cmdline, mvCmd); i >= 0 {
111 rest := cmdline[i+len(mvCmd):]
Shinichiro Hamaji3438ae32015-06-05 11:33:20 +0900112 ei := strings.IndexByte(rest, ')')
113 if ei < 0 {
Fumitoshi Ukai923b1282015-07-13 12:53:30 +0900114 return cmdline, "", fmt.Errorf("unbalanced parenthes? %s", cmdline)
Shinichiro Hamaji3438ae32015-06-05 11:33:20 +0900115 }
Fumitoshi Ukai923b1282015-07-13 12:53:30 +0900116 cmdline = cmdline[:i] + "(cp -f " + depfile + " " + rest
117 return cmdline, depfile, nil
Shinichiro Hamaji3438ae32015-06-05 11:33:20 +0900118 }
119
Shinichiro Hamaji74ab4b62015-05-28 22:56:24 +0900120 // A hack for Android to get .P files instead of .d.
Fumitoshi Ukai923b1282015-07-13 12:53:30 +0900121 p := stripExt(depfile) + ".P"
122 if strings.Contains(cmdline, p) {
123 rmfCmd := "; rm -f " + depfile
124 ncmdline := strings.Replace(cmdline, rmfCmd, "", 1)
125 if ncmdline == cmdline {
126 return cmdline, "", fmt.Errorf("cannot find removal of .d file: %s", cmdline)
127 }
128 return ncmdline, p, nil
Shinichiro Hamaji74ab4b62015-05-28 22:56:24 +0900129 }
130
131 // A hack for Android. For .s files, GCC does not use
132 // C preprocessor, so it ignores -MF flag.
Fumitoshi Ukai923b1282015-07-13 12:53:30 +0900133 as := "/" + stripExt(filepath.Base(depfile)) + ".s"
134 if strings.Contains(cmdline, as) {
135 return cmdline, "", nil
Shinichiro Hamaji74ab4b62015-05-28 22:56:24 +0900136 }
137
Fumitoshi Ukai923b1282015-07-13 12:53:30 +0900138 cmdline += fmt.Sprintf(" && cp %s %s.tmp", depfile, depfile)
139 depfile += ".tmp"
140 return cmdline, depfile, nil
Shinichiro Hamaji74ab4b62015-05-28 22:56:24 +0900141}
142
Shinichiro Hamaji246cd232015-05-27 17:08:23 +0900143func stripShellComment(s string) string {
144 if strings.IndexByte(s, '#') < 0 {
145 // Fast path.
146 return s
147 }
Fumitoshi Ukai43b56662015-07-15 10:41:47 +0900148 // set space as an initial value so the leading comment will be
149 // stripped out.
150 lastch := rune(' ')
Shinichiro Hamaji246cd232015-05-27 17:08:23 +0900151 var escape bool
152 var quote rune
153 for i, c := range s {
Fumitoshi Ukaib92f0282015-07-21 14:05:51 +0900154 if quote != 0 {
Shinichiro Hamaji246cd232015-05-27 17:08:23 +0900155 if quote == c && (quote == '\'' || !escape) {
156 quote = 0
157 }
158 } else if !escape {
Fumitoshi Ukai43b56662015-07-15 10:41:47 +0900159 if c == '#' && isWhitespace(lastch) {
Shinichiro Hamaji246cd232015-05-27 17:08:23 +0900160 return s[:i]
161 } else if c == '\'' || c == '"' || c == '`' {
162 quote = c
163 }
164 }
165 if escape {
166 escape = false
167 } else if c == '\\' {
168 escape = true
169 } else {
170 escape = false
171 }
Fumitoshi Ukai43b56662015-07-15 10:41:47 +0900172 lastch = c
Shinichiro Hamaji246cd232015-05-27 17:08:23 +0900173 }
174 return s
175}
176
Fumitoshi Ukai1713c6f2015-07-14 13:08:24 +0900177var ccRE = regexp.MustCompile(`^prebuilts/(gcc|clang)/.*(gcc|g\+\+|clang|clang\+\+) .* ?-c `)
178
179func gomaCmdForAndroidCompileCmd(cmd string) (string, bool) {
180 i := strings.Index(cmd, " ")
181 if i < 0 {
182 return cmd, false
183 }
184 driver := cmd[:i]
185 if strings.HasSuffix(driver, "ccache") {
186 return gomaCmdForAndroidCompileCmd(cmd[i+1:])
187 }
188 return cmd, ccRE.MatchString(cmd)
189}
190
Fumitoshi Ukaib92f0282015-07-21 14:05:51 +0900191func descriptionFromCmd(cmd string) (string, bool) {
192 if !strings.HasPrefix(cmd, "echo") || !isWhitespace(rune(cmd[4])) {
193 return "", false
194 }
195 echoarg := cmd[5:]
196
197 // strip outer quotes, and fail if it is not a single echo command.
198 var buf bytes.Buffer
199 var escape bool
200 var quote rune
201 for _, c := range echoarg {
202 if escape {
203 escape = false
204 buf.WriteRune(c)
205 continue
206 }
207 if c == '\\' {
208 escape = true
209 buf.WriteRune(c)
210 continue
211 }
212 if quote != 0 {
213 if c == quote {
214 quote = 0
215 continue
216 }
217 buf.WriteRune(c)
218 continue
219 }
220 switch c {
221 case '\'', '"', '`':
222 quote = c
223 case '<', '>', '&', '|', ';':
224 return "", false
225 default:
226 buf.WriteRune(c)
227 }
228 }
229 return buf.String(), true
230}
231
232func (n *NinjaGenerator) genShellScript(runners []runner) (cmd string, desc string, useLocalPool bool) {
233 const defaultDesc = "build $out"
234 var useGomacc bool
Shinichiro Hamaji6aa86ac2015-05-26 15:21:11 +0900235 var buf bytes.Buffer
Shinichiro Hamajia5467792015-05-27 16:28:40 +0900236 for i, r := range runners {
237 if i > 0 {
238 if runners[i-1].ignoreError {
239 buf.WriteString(" ; ")
240 } else {
241 buf.WriteString(" && ")
242 }
243 }
Shinichiro Hamaji246cd232015-05-27 17:08:23 +0900244 cmd := stripShellComment(r.cmd)
245 cmd = trimLeftSpace(cmd)
Fumitoshi Ukai74663592015-07-17 17:53:11 +0900246 cmd = strings.Replace(cmd, "\\\n", "", -1)
Shinichiro Hamajia5467792015-05-27 16:28:40 +0900247 cmd = strings.TrimRight(cmd, " \t\n;")
Fumitoshi Ukai701b0e02015-07-28 14:06:06 +0900248 cmd = escapeNinja(cmd)
Shinichiro Hamaji501f68e2015-05-27 17:33:41 +0900249 if cmd == "" {
250 cmd = "true"
251 }
Fumitoshi Ukaib79b2902015-07-16 16:40:09 +0900252 if n.GomaDir != "" {
Fumitoshi Ukai1713c6f2015-07-14 13:08:24 +0900253 rcmd, ok := gomaCmdForAndroidCompileCmd(cmd)
254 if ok {
Fumitoshi Ukaib79b2902015-07-16 16:40:09 +0900255 cmd = fmt.Sprintf("%s/gomacc %s", n.GomaDir, rcmd)
Fumitoshi Ukai1713c6f2015-07-14 13:08:24 +0900256 useGomacc = true
257 }
Shinichiro Hamajibcecb502015-06-04 16:20:25 +0900258 }
Fumitoshi Ukaib92f0282015-07-21 14:05:51 +0900259 if n.DetectAndroidEcho && desc == "" {
260 d, ok := descriptionFromCmd(cmd)
261 if ok {
262 desc = d
263 cmd = "true"
264 }
265 }
Shinichiro Hamaji13653b22015-05-28 22:45:12 +0900266 needsSubShell := i > 0 || len(runners) > 1
267 if cmd[0] == '(' {
268 needsSubShell = false
269 }
270
271 if needsSubShell {
272 buf.WriteByte('(')
273 }
Shinichiro Hamajia5467792015-05-27 16:28:40 +0900274 buf.WriteString(cmd)
275 if i == len(runners)-1 && r.ignoreError {
276 buf.WriteString(" ; true")
277 }
Shinichiro Hamaji13653b22015-05-28 22:45:12 +0900278 if needsSubShell {
279 buf.WriteByte(')')
280 }
Shinichiro Hamaji6aa86ac2015-05-26 15:21:11 +0900281 }
Fumitoshi Ukaib92f0282015-07-21 14:05:51 +0900282 if desc == "" {
283 desc = defaultDesc
284 }
285 return buf.String(), desc, n.GomaDir != "" && !useGomacc
Shinichiro Hamaji6aa86ac2015-05-26 15:21:11 +0900286}
287
Fumitoshi Ukaib79b2902015-07-16 16:40:09 +0900288func (n *NinjaGenerator) genRuleName() string {
Fumitoshi Ukai936de102015-06-08 11:21:16 +0900289 ruleName := fmt.Sprintf("rule%d", n.ruleID)
290 n.ruleID++
Shinichiro Hamajifd872162015-05-26 18:06:48 +0900291 return ruleName
292}
293
Fumitoshi Ukai3dae8042015-07-22 13:49:23 +0900294func (n *NinjaGenerator) emitBuild(output, rule, inputs, orderOnlys string) {
295 fmt.Fprintf(n.f, "build %s: %s", escapeBuildTarget(output), rule)
296 if inputs != "" {
297 fmt.Fprintf(n.f, " %s", inputs)
298 }
299 if orderOnlys != "" {
300 fmt.Fprintf(n.f, " || %s", orderOnlys)
301 }
Fumitoshi Ukai26e83812015-07-21 14:38:33 +0900302}
303
304func escapeBuildTarget(s string) string {
305 i := strings.IndexAny(s, "$: ")
306 if i < 0 {
307 return s
308 }
309 var buf bytes.Buffer
310 for _, c := range s {
311 switch c {
312 case '$', ':', ' ':
313 buf.WriteByte('$')
314 }
315 buf.WriteRune(c)
316 }
317 return buf.String()
Shinichiro Hamajifd872162015-05-26 18:06:48 +0900318}
319
Fumitoshi Ukai3dae8042015-07-22 13:49:23 +0900320func getDepString(node *DepNode) (string, string) {
Shinichiro Hamajifd872162015-05-26 18:06:48 +0900321 var deps []string
Fumitoshi Ukai3dae8042015-07-22 13:49:23 +0900322 seen := make(map[string]bool)
Shinichiro Hamajifd872162015-05-26 18:06:48 +0900323 for _, d := range node.Deps {
Fumitoshi Ukai3dae8042015-07-22 13:49:23 +0900324 t := escapeBuildTarget(d.Output)
325 if seen[t] {
326 continue
327 }
328 deps = append(deps, t)
329 seen[t] = true
Fumitoshi Ukaic916ea22015-06-30 09:52:13 +0900330 }
331 var orderOnlys []string
332 for _, d := range node.OrderOnlys {
Fumitoshi Ukai3dae8042015-07-22 13:49:23 +0900333 t := escapeBuildTarget(d.Output)
334 if seen[t] {
335 continue
336 }
337 orderOnlys = append(orderOnlys, t)
338 seen[t] = true
Shinichiro Hamajifd872162015-05-26 18:06:48 +0900339 }
Fumitoshi Ukai3dae8042015-07-22 13:49:23 +0900340 return strings.Join(deps, " "), strings.Join(orderOnlys, " ")
Shinichiro Hamajifd872162015-05-26 18:06:48 +0900341}
342
Fumitoshi Ukai701b0e02015-07-28 14:06:06 +0900343func escapeNinja(s string) string {
344 return strings.Replace(s, "$", "$$", -1)
345}
346
Fumitoshi Ukaicf6c6c22015-07-21 15:24:35 +0900347func escapeShell(s string) string {
348 i := strings.IndexAny(s, "$`!\\\"")
349 if i < 0 {
350 return s
351 }
352 var buf bytes.Buffer
353 var lastDollar bool
354 for _, c := range s {
355 switch c {
356 case '$':
357 if lastDollar {
358 buf.WriteRune(c)
359 lastDollar = false
360 continue
361 }
362 buf.WriteString(`\$`)
363 lastDollar = true
364 continue
365 case '`', '"', '!', '\\':
366 buf.WriteByte('\\')
367 }
368 buf.WriteRune(c)
369 lastDollar = false
370 }
371 return buf.String()
372}
373
Fumitoshi Ukaib79b2902015-07-16 16:40:09 +0900374func (n *NinjaGenerator) emitNode(node *DepNode) error {
Shinichiro Hamaji6aa86ac2015-05-26 15:21:11 +0900375 if n.done[node.Output] {
Fumitoshi Ukai65c72332015-06-26 21:32:50 +0900376 return nil
Shinichiro Hamaji6aa86ac2015-05-26 15:21:11 +0900377 }
378 n.done[node.Output] = true
379
Fumitoshi Ukaic916ea22015-06-30 09:52:13 +0900380 if len(node.Cmds) == 0 && len(node.Deps) == 0 && len(node.OrderOnlys) == 0 && !node.IsPhony {
Fumitoshi Ukai3857a242015-07-17 17:15:12 +0900381 if _, ok := n.ctx.vpaths.exists(node.Output); ok {
382 return nil
383 }
Fumitoshi Ukai3dae8042015-07-22 13:49:23 +0900384 n.emitBuild(node.Output, "phony", "", "")
Fumitoshi Ukai3857a242015-07-17 17:15:12 +0900385 fmt.Fprintln(n.f)
Fumitoshi Ukai65c72332015-06-26 21:32:50 +0900386 return nil
Shinichiro Hamajifd4aaa02015-05-26 15:40:53 +0900387 }
388
Fumitoshi Ukaie08e9ee2015-07-13 13:14:41 +0900389 base := filepath.Base(node.Output)
390 if base != node.Output {
391 n.shortNames[base] = append(n.shortNames[base], node.Output)
392 }
393
Fumitoshi Ukaia70b4ea2015-06-30 15:31:49 +0900394 runners, _, err := createRunners(n.ctx, node)
Fumitoshi Ukai65c72332015-06-26 21:32:50 +0900395 if err != nil {
396 return err
397 }
Shinichiro Hamajibd59ebb2015-05-28 17:07:17 +0900398 ruleName := "phony"
Shinichiro Hamajibcecb502015-06-04 16:20:25 +0900399 useLocalPool := false
Fumitoshi Ukai3dae8042015-07-22 13:49:23 +0900400 inputs, orderOnlys := getDepString(node)
Shinichiro Hamajibd59ebb2015-05-28 17:07:17 +0900401 if len(runners) > 0 {
402 ruleName = n.genRuleName()
Fumitoshi Ukai701b0e02015-07-28 14:06:06 +0900403 fmt.Fprintf(n.f, "\n# rule for %q\n", node.Output)
Shinichiro Hamajibd59ebb2015-05-28 17:07:17 +0900404 fmt.Fprintf(n.f, "rule %s\n", ruleName)
Shinichiro Hamajibd59ebb2015-05-28 17:07:17 +0900405
Fumitoshi Ukaib92f0282015-07-21 14:05:51 +0900406 ss, desc, ulp := n.genShellScript(runners)
Shinichiro Hamajibcecb502015-06-04 16:20:25 +0900407 if ulp {
408 useLocalPool = true
409 }
Fumitoshi Ukaib92f0282015-07-21 14:05:51 +0900410 fmt.Fprintf(n.f, " description = %s\n", desc)
Fumitoshi Ukai923b1282015-07-13 12:53:30 +0900411 cmdline, depfile, err := getDepfile(ss)
Shinichiro Hamaji0ab9a2f2015-05-27 18:32:46 +0900412 if err != nil {
Fumitoshi Ukai65c72332015-06-26 21:32:50 +0900413 return err
Shinichiro Hamaji0ab9a2f2015-05-27 18:32:46 +0900414 }
Shinichiro Hamajibd59ebb2015-05-28 17:07:17 +0900415 if depfile != "" {
416 fmt.Fprintf(n.f, " depfile = %s\n", depfile)
Fumitoshi Ukai923b1282015-07-13 12:53:30 +0900417 fmt.Fprintf(n.f, " deps = gcc\n")
Shinichiro Hamajibd59ebb2015-05-28 17:07:17 +0900418 }
Shinichiro Hamajia5467792015-05-27 16:28:40 +0900419 // It seems Linux is OK with ~130kB.
420 // TODO: Find this number automatically.
421 ArgLenLimit := 100 * 1000
Fumitoshi Ukaicf6c6c22015-07-21 15:24:35 +0900422 if len(cmdline) > ArgLenLimit {
Shinichiro Hamajia5467792015-05-27 16:28:40 +0900423 fmt.Fprintf(n.f, " rspfile = $out.rsp\n")
Fumitoshi Ukai3dae8042015-07-22 13:49:23 +0900424 if inputs != "" {
Fumitoshi Ukai701b0e02015-07-28 14:06:06 +0900425 cmdline = strings.Replace(cmdline, inputs, "${in}", -1)
Fumitoshi Ukai3dae8042015-07-22 13:49:23 +0900426 }
Fumitoshi Ukai701b0e02015-07-28 14:06:06 +0900427 cmdline = strings.Replace(cmdline, escapeNinja(node.Output), "${out}", -1)
Fumitoshi Ukaicf6c6c22015-07-21 15:24:35 +0900428 fmt.Fprintf(n.f, " rspfile_content = %s\n", cmdline)
429 fmt.Fprintf(n.f, " command = %s $out.rsp\n", n.ctx.shell)
430 } else {
Fumitoshi Ukai3dae8042015-07-22 13:49:23 +0900431 cmdline = escapeShell(cmdline)
432 if inputs != "" {
Fumitoshi Ukai701b0e02015-07-28 14:06:06 +0900433 cmdline = strings.Replace(cmdline, escapeShell(inputs), "${in}", -1)
Fumitoshi Ukai3dae8042015-07-22 13:49:23 +0900434 }
Fumitoshi Ukai701b0e02015-07-28 14:06:06 +0900435 cmdline = strings.Replace(cmdline, escapeShell(escapeNinja(node.Output)), "${out}", -1)
Fumitoshi Ukai3dae8042015-07-22 13:49:23 +0900436 fmt.Fprintf(n.f, " command = %s -c \"%s\"\n", n.ctx.shell, cmdline)
Shinichiro Hamaji6aa86ac2015-05-26 15:21:11 +0900437 }
438 }
Fumitoshi Ukai3dae8042015-07-22 13:49:23 +0900439 n.emitBuild(node.Output, ruleName, inputs, orderOnlys)
Shinichiro Hamajibcecb502015-06-04 16:20:25 +0900440 if useLocalPool {
441 fmt.Fprintf(n.f, " pool = local_pool\n")
442 }
Fumitoshi Ukaic916ea22015-06-30 09:52:13 +0900443 fmt.Fprintf(n.f, "\n")
Shinichiro Hamaji6aa86ac2015-05-26 15:21:11 +0900444
445 for _, d := range node.Deps {
Fumitoshi Ukai65c72332015-06-26 21:32:50 +0900446 err := n.emitNode(d)
447 if err != nil {
448 return err
449 }
Shinichiro Hamaji6aa86ac2015-05-26 15:21:11 +0900450 }
Fumitoshi Ukaic916ea22015-06-30 09:52:13 +0900451 for _, d := range node.OrderOnlys {
452 err := n.emitNode(d)
453 if err != nil {
454 return err
455 }
456 }
Fumitoshi Ukai65c72332015-06-26 21:32:50 +0900457 return nil
Shinichiro Hamaji6aa86ac2015-05-26 15:21:11 +0900458}
459
Fumitoshi Ukaid4a016e2015-07-27 16:50:00 +0900460func (n *NinjaGenerator) emitRegenRules() error {
461 if len(n.Args) == 0 {
462 return nil
463 }
464 mkfiles, err := n.ctx.ev.EvaluateVar("MAKEFILE_LIST")
465 if err != nil {
466 return err
467 }
468 fmt.Fprintf(n.f, `
469rule regen_ninja
470 description = Regenerate ninja files due to dependency
471 generator=1
472 command=%s
473`, strings.Join(n.Args, " "))
474 fmt.Fprintf(n.f, "build %s: regen_ninja %s", n.ninjaName(), mkfiles)
475 // TODO: Add dependencies to directories read by $(wildcard) or
476 // $(shell find).
477 if len(usedEnvs) > 0 {
478 fmt.Fprintf(n.f, " %s", n.envlistName())
479 }
480 fmt.Fprintf(n.f, "\n\n")
481 if len(usedEnvs) == 0 {
482 return nil
483 }
484 fmt.Fprint(n.f, `
485build .always_build: phony
486rule regen_envlist
487 description = Check $out
488 generator = 1
489 restat = 1
490 command = rm -f $out.tmp`)
491 for env := range usedEnvs {
492 fmt.Fprintf(n.f, " && echo %s=$$%s >> $out.tmp", env, env)
493 }
494 if n.ErrorOnEnvChange {
495 fmt.Fprintln(n.f, " && (cmp -s $out.tmp $out || (echo Environment variable changes are detected && diff -u $out $out.tmp))")
496 } else {
497 fmt.Fprintln(n.f, " && (cmp -s $out.tmp $out || mv $out.tmp $out)")
498 }
499
500 fmt.Fprintf(n.f, "build %s: regen_envlist .always_build\n\n", n.envlistName())
501 return nil
Fumitoshi Ukai861c9f22015-07-22 10:54:01 +0900502}
503
Fumitoshi Ukaid4a016e2015-07-27 16:50:00 +0900504func (n *NinjaGenerator) shName() string {
505 return fmt.Sprintf("ninja%s.sh", n.Suffix)
Fumitoshi Ukai861c9f22015-07-22 10:54:01 +0900506}
507
Fumitoshi Ukaid4a016e2015-07-27 16:50:00 +0900508func (n *NinjaGenerator) ninjaName() string {
509 return fmt.Sprintf("build%s.ninja", n.Suffix)
510}
511
512func (n *NinjaGenerator) envlistName() string {
513 return fmt.Sprintf(".kati_env%s", n.Suffix)
514}
515
516func (n *NinjaGenerator) generateEnvlist() (err error) {
517 f, err := os.Create(n.envlistName())
518 if err != nil {
519 return err
520 }
521 defer func() {
522 cerr := f.Close()
523 if err == nil {
524 err = cerr
525 }
526 }()
527 for k := range usedEnvs {
528 v, err := n.ctx.ev.EvaluateVar(k)
529 if err != nil {
530 return err
531 }
Fumitoshi Ukaid5570262015-07-28 12:44:31 +0900532 fmt.Fprintf(f, "%q=%q\n", k, v)
Fumitoshi Ukaid4a016e2015-07-27 16:50:00 +0900533 }
534 return nil
535}
536
537func (n *NinjaGenerator) generateShell() (err error) {
538 f, err := os.Create(n.shName())
Shinichiro Hamaji30a02ad2015-05-29 14:56:43 +0900539 if err != nil {
Fumitoshi Ukai65c72332015-06-26 21:32:50 +0900540 return err
Shinichiro Hamaji30a02ad2015-05-29 14:56:43 +0900541 }
Fumitoshi Ukai65c72332015-06-26 21:32:50 +0900542 defer func() {
543 cerr := f.Close()
544 if err == nil {
545 err = cerr
546 }
547 }()
Shinichiro Hamaji30a02ad2015-05-29 14:56:43 +0900548
Fumitoshi Ukaibe9104d2015-07-28 14:20:43 +0900549 fmt.Fprintf(f, "#!/bin/bash\n")
Fumitoshi Ukai08db53a2015-07-17 14:45:57 +0900550 fmt.Fprintf(f, "# Generated by kati %s\n", gitVersion)
551 fmt.Fprintln(f)
552 fmt.Fprintln(f, `cd $(dirname "$0")`)
Fumitoshi Ukaid4a016e2015-07-27 16:50:00 +0900553 if n.Suffix != "" {
554 fmt.Fprintf(f, "if [ -f %s ]; then\n export $(cat %s)\nfi\n", n.envlistName(), n.envlistName())
555 }
Shinichiro Hamaji30a02ad2015-05-29 14:56:43 +0900556 for name, export := range n.exports {
557 if export {
Fumitoshi Ukaia70b4ea2015-06-30 15:31:49 +0900558 v, err := n.ctx.ev.EvaluateVar(name)
Fumitoshi Ukai65c72332015-06-26 21:32:50 +0900559 if err != nil {
560 return err
561 }
Fumitoshi Ukaid5570262015-07-28 12:44:31 +0900562 // TODO(ukai): if name contains space, ignore it?
563 // export "a b"=c will error on bash
564 // bash: export `a b=c': not a valid identifier
565 fmt.Fprintf(f, "export %q=%q\n", name, v)
Shinichiro Hamaji30a02ad2015-05-29 14:56:43 +0900566 } else {
Fumitoshi Ukaid5570262015-07-28 12:44:31 +0900567 fmt.Fprintf(f, "unset %q\n", name)
Shinichiro Hamaji30a02ad2015-05-29 14:56:43 +0900568 }
569 }
Fumitoshi Ukaib79b2902015-07-16 16:40:09 +0900570 if n.GomaDir == "" {
Fumitoshi Ukaid4a016e2015-07-27 16:50:00 +0900571 fmt.Fprintf(f, `exec ninja -f %s "$@"`+"\n", n.ninjaName())
Shinichiro Hamajibcecb502015-06-04 16:20:25 +0900572 } else {
Fumitoshi Ukaid4a016e2015-07-27 16:50:00 +0900573 fmt.Fprintf(f, `exec ninja -f %s -j500 "$@"`+"\n", n.ninjaName())
Shinichiro Hamajibcecb502015-06-04 16:20:25 +0900574 }
Shinichiro Hamaji30a02ad2015-05-29 14:56:43 +0900575
Fumitoshi Ukai65c72332015-06-26 21:32:50 +0900576 return f.Chmod(0755)
Shinichiro Hamaji30a02ad2015-05-29 14:56:43 +0900577}
578
Fumitoshi Ukaid4a016e2015-07-27 16:50:00 +0900579func (n *NinjaGenerator) generateNinja(defaultTarget string) (err error) {
580 f, err := os.Create(n.ninjaName())
Shinichiro Hamaji30a02ad2015-05-29 14:56:43 +0900581 if err != nil {
Fumitoshi Ukai65c72332015-06-26 21:32:50 +0900582 return err
Shinichiro Hamaji30a02ad2015-05-29 14:56:43 +0900583 }
Fumitoshi Ukai65c72332015-06-26 21:32:50 +0900584 defer func() {
585 cerr := f.Close()
586 if err == nil {
587 err = cerr
588 }
589 }()
Shinichiro Hamaji30a02ad2015-05-29 14:56:43 +0900590
591 n.f = f
Fumitoshi Ukai9dd48a92015-07-14 13:39:03 +0900592 fmt.Fprintf(n.f, "# Generated by kati %s\n", gitVersion)
Shinichiro Hamajiea2e0de2015-05-28 15:22:16 +0900593 fmt.Fprintf(n.f, "\n")
594
Fumitoshi Ukaib5612a82015-07-14 13:22:17 +0900595 if len(usedEnvs) > 0 {
596 fmt.Fprintln(n.f, "# Environment variables used:")
597 var names []string
598 for name := range usedEnvs {
599 names = append(names, name)
600 }
601 sort.Strings(names)
602 for _, name := range names {
603 v, err := n.ctx.ev.EvaluateVar(name)
604 if err != nil {
605 return err
606 }
Fumitoshi Ukaid5570262015-07-28 12:44:31 +0900607 fmt.Fprintf(n.f, "# %q=%q\n", name, v)
Fumitoshi Ukaib5612a82015-07-14 13:22:17 +0900608 }
609 fmt.Fprintf(n.f, "\n")
610 }
611
Fumitoshi Ukaib79b2902015-07-16 16:40:09 +0900612 if n.GomaDir != "" {
Shinichiro Hamajibcecb502015-06-04 16:20:25 +0900613 fmt.Fprintf(n.f, "pool local_pool\n")
Fumitoshi Ukaid4a016e2015-07-27 16:50:00 +0900614 fmt.Fprintf(n.f, " depth = %d\n\n", runtime.NumCPU())
615 }
616
617 err = n.emitRegenRules()
618 if err != nil {
619 return err
Shinichiro Hamajibcecb502015-06-04 16:20:25 +0900620 }
621
Fumitoshi Ukai3dae8042015-07-22 13:49:23 +0900622 // defining $out for $@ and $in for $^ here doesn't work well,
623 // because these texts will be processed in escapeShell...
Fumitoshi Ukai65c72332015-06-26 21:32:50 +0900624 for _, node := range n.nodes {
625 err := n.emitNode(node)
626 if err != nil {
627 return err
628 }
629 }
Fumitoshi Ukaie08e9ee2015-07-13 13:14:41 +0900630
Fumitoshi Ukaib79b2902015-07-16 16:40:09 +0900631 if defaultTarget != "" {
Fumitoshi Ukai701b0e02015-07-28 14:06:06 +0900632 fmt.Fprintf(n.f, "\ndefault %s\n", escapeNinja(defaultTarget))
Fumitoshi Ukaib79b2902015-07-16 16:40:09 +0900633 }
634
Fumitoshi Ukaie08e9ee2015-07-13 13:14:41 +0900635 fmt.Fprintf(n.f, "\n# shortcuts:\n")
636 var names []string
637 for name := range n.shortNames {
Fumitoshi Ukai2dc2c172015-07-17 17:39:26 +0900638 if n.done[name] {
639 continue
640 }
Fumitoshi Ukaie08e9ee2015-07-13 13:14:41 +0900641 names = append(names, name)
642 }
643 sort.Strings(names)
644 for _, name := range names {
645 if len(n.shortNames[name]) != 1 {
646 // we generate shortcuts only for targets whose basename are unique.
647 continue
648 }
649 fmt.Fprintf(n.f, "build %s: phony %s\n", name, n.shortNames[name][0])
650 }
Fumitoshi Ukai65c72332015-06-26 21:32:50 +0900651 return nil
Shinichiro Hamaji6aa86ac2015-05-26 15:21:11 +0900652}
653
Fumitoshi Ukaib79b2902015-07-16 16:40:09 +0900654// Save generates build.ninja from DepGraph.
Fumitoshi Ukaid4a016e2015-07-27 16:50:00 +0900655func (n *NinjaGenerator) Save(g *DepGraph, name string, targets []string) error {
Fumitoshi Ukai49599e52015-06-26 10:10:24 +0900656 startTime := time.Now()
Fumitoshi Ukaib79b2902015-07-16 16:40:09 +0900657 n.init(g)
Fumitoshi Ukaid4a016e2015-07-27 16:50:00 +0900658 err := n.generateEnvlist()
659 if err != nil {
660 return err
661 }
662 err = n.generateShell()
Fumitoshi Ukai65c72332015-06-26 21:32:50 +0900663 if err != nil {
664 return err
665 }
Fumitoshi Ukaib79b2902015-07-16 16:40:09 +0900666 var defaultTarget string
667 if len(targets) == 0 && len(g.nodes) > 0 {
668 defaultTarget = g.nodes[0].Output
669 }
Fumitoshi Ukaid4a016e2015-07-27 16:50:00 +0900670 err = n.generateNinja(defaultTarget)
Fumitoshi Ukai65c72332015-06-26 21:32:50 +0900671 if err != nil {
672 return err
673 }
Fumitoshi Ukai49599e52015-06-26 10:10:24 +0900674 logStats("generate ninja time: %q", time.Since(startTime))
Fumitoshi Ukai65c72332015-06-26 21:32:50 +0900675 return nil
Shinichiro Hamaji6aa86ac2015-05-26 15:21:11 +0900676}