blob: f94cf2fd465ba7c9382e88cbb14c78f28ba54c28 [file] [log] [blame]
Dan Willemsen43398532018-02-21 02:10:29 -08001// Copyright 2018 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
15// This tool reads "make"-like dependency files, and outputs a canonical version
16// that can be used by ninja. Ninja doesn't support multiple output files (even
17// though it doesn't care what the output file is, or whether it matches what is
18// expected).
19package main
20
21import (
22 "bytes"
23 "flag"
24 "fmt"
25 "io/ioutil"
26 "log"
27 "os"
28)
29
30func main() {
31 flag.Usage = func() {
Colin Cross1d2cf042019-03-29 15:33:06 -070032 fmt.Fprintf(os.Stderr, "Usage: %s [-o <output>] <depfile.d> [<depfile.d>...]", os.Args[0])
Dan Willemsen43398532018-02-21 02:10:29 -080033 flag.PrintDefaults()
34 }
35 output := flag.String("o", "", "Optional output file (defaults to rewriting source if necessary)")
36 flag.Parse()
37
Colin Cross1d2cf042019-03-29 15:33:06 -070038 if flag.NArg() < 1 {
39 log.Fatal("Expected at least one input file as an argument")
Dan Willemsen43398532018-02-21 02:10:29 -080040 }
41
Colin Cross1d2cf042019-03-29 15:33:06 -070042 var mergedDeps *Deps
43 var firstInput []byte
44
45 for i, arg := range flag.Args() {
46 input, err := ioutil.ReadFile(arg)
47 if err != nil {
48 log.Fatalf("Error opening %q: %v", arg, err)
49 }
50
51 deps, err := Parse(arg, bytes.NewBuffer(append([]byte(nil), input...)))
52 if err != nil {
53 log.Fatalf("Failed to parse: %v", err)
54 }
55
56 if i == 0 {
57 mergedDeps = deps
58 firstInput = input
59 } else {
60 mergedDeps.Inputs = append(mergedDeps.Inputs, deps.Inputs...)
61 }
Dan Willemsen43398532018-02-21 02:10:29 -080062 }
63
Colin Cross1d2cf042019-03-29 15:33:06 -070064 new := mergedDeps.Print()
Dan Willemsen43398532018-02-21 02:10:29 -080065
66 if *output == "" || *output == flag.Arg(0) {
Colin Cross1d2cf042019-03-29 15:33:06 -070067 if !bytes.Equal(firstInput, new) {
Dan Willemsen43398532018-02-21 02:10:29 -080068 err := ioutil.WriteFile(flag.Arg(0), new, 0666)
69 if err != nil {
70 log.Fatalf("Failed to write: %v", err)
71 }
72 }
73 } else {
74 err := ioutil.WriteFile(*output, new, 0666)
75 if err != nil {
76 log.Fatalf("Failed to write to %q: %v", *output, err)
77 }
78 }
79}