summaryrefslogtreecommitdiff
path: root/src/util/godeps.go
blob: 960faa46be8775991b930fef201140b5c4279528 (plain)
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
// Copyright (c) 2018, Google Inc.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

// godeps prints out dependencies of a package in either CMake or Make depfile
// format, for incremental rebuilds.
//
// The depfile format is preferred. It works correctly when new files are added.
// However, CMake only supports depfiles for custom commands with Ninja and
// starting CMake 3.7. For other configurations, we also support CMake's format,
// but CMake must be rerun when file lists change.
package main

import (
	"flag"
	"fmt"
	"go/build"
	"os"
	"path/filepath"
	"sort"
	"strings"
)

var (
	format  = flag.String("format", "cmake", "The format to output to, either 'cmake' or 'depfile'")
	mainPkg = flag.String("pkg", "", "The package to print dependencies for")
	target  = flag.String("target", "", "The name of the output file")
	out     = flag.String("out", "", "The path to write the output to. If unset, this is stdout")
)

func cMakeQuote(in string) string {
	// See https://cmake.org/cmake/help/v3.0/manual/cmake-language.7.html#quoted-argument
	var b strings.Builder
	b.Grow(len(in))
	// Iterate over in as bytes.
	for i := 0; i < len(in); i++ {
		switch c := in[i]; c {
		case '\\', '"':
			b.WriteByte('\\')
			b.WriteByte(c)
		case '\t':
			b.WriteString("\\t")
		case '\r':
			b.WriteString("\\r")
		case '\n':
			b.WriteString("\\n")
		default:
			b.WriteByte(in[i])
		}
	}
	return b.String()
}

func writeCMake(outFile *os.File, files []string) error {
	for i, file := range files {
		if i != 0 {
			if _, err := outFile.WriteString(";"); err != nil {
				return err
			}
		}
		if _, err := outFile.WriteString(cMakeQuote(file)); err != nil {
			return err
		}
	}
	return nil
}

func makeQuote(in string) string {
	// See https://www.gnu.org/software/make/manual/make.html#Rule-Syntax
	var b strings.Builder
	b.Grow(len(in))
	// Iterate over in as bytes.
	for i := 0; i < len(in); i++ {
		switch c := in[i]; c {
		case '$':
			b.WriteString("$$")
		case '#', '\\', ' ':
			b.WriteByte('\\')
			b.WriteByte(c)
		default:
			b.WriteByte(c)
		}
	}
	return b.String()
}

func writeDepfile(outFile *os.File, files []string) error {
	if _, err := fmt.Fprintf(outFile, "%s:", makeQuote(*target)); err != nil {
		return err
	}
	for _, file := range files {
		if _, err := fmt.Fprintf(outFile, " %s", makeQuote(file)); err != nil {
			return err
		}
	}
	_, err := outFile.WriteString("\n")
	return err
}

func appendPrefixed(list, newFiles []string, prefix string) []string {
	for _, file := range newFiles {
		list = append(list, filepath.Join(prefix, file))
	}
	return list
}

func main() {
	flag.Parse()

	if len(*mainPkg) == 0 {
		fmt.Fprintf(os.Stderr, "-pkg argument is required.\n")
		os.Exit(1)
	}

	var isDepfile bool
	switch *format {
	case "depfile":
		isDepfile = true
	case "cmake":
		isDepfile = false
	default:
		fmt.Fprintf(os.Stderr, "Unknown format: %q\n", *format)
		os.Exit(1)
	}

	if isDepfile && len(*target) == 0 {
		fmt.Fprintf(os.Stderr, "-target argument is required for depfile.\n")
		os.Exit(1)
	}

	done := make(map[string]struct{})
	var files []string
	var recurse func(pkgName string) error
	recurse = func(pkgName string) error {
		pkg, err := build.Default.Import(pkgName, ".", 0)
		if err != nil {
			return err
		}

		// Skip standard packages.
		if pkg.Goroot {
			return nil
		}

		// Skip already-visited packages.
		if _, ok := done[pkg.Dir]; ok {
			return nil
		}
		done[pkg.Dir] = struct{}{}

		files = appendPrefixed(files, pkg.GoFiles, pkg.Dir)
		files = appendPrefixed(files, pkg.CgoFiles, pkg.Dir)
		// Include ignored Go files. A subsequent change may cause them
		// to no longer be ignored.
		files = appendPrefixed(files, pkg.IgnoredGoFiles, pkg.Dir)

		// Recurse into imports.
		for _, importName := range pkg.Imports {
			if err := recurse(importName); err != nil {
				return err
			}
		}
		return nil
	}
	if err := recurse(*mainPkg); err != nil {
		fmt.Fprintf(os.Stderr, "Error getting dependencies: %s\n", err)
		os.Exit(1)
	}

	sort.Strings(files)

	outFile := os.Stdout
	if len(*out) != 0 {
		var err error
		outFile, err = os.Create(*out)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error writing output: %s\n", err)
			os.Exit(1)
		}
		defer outFile.Close()
	}

	var err error
	if isDepfile {
		err = writeDepfile(outFile, files)
	} else {
		err = writeCMake(outFile, files)
	}
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error writing output: %s\n", err)
		os.Exit(1)
	}
}