Debian Codegraph @

bazel/exporter/gni_exporter.go

raw
1 // Copyright 2022 Google LLC
2 //
3 // Use of this source code is governed by a BSD-style license that can be
4 // found in the LICENSE file.
5
6 package exporter
7
8 import (
9 "bytes"
10 "fmt"
11 "path/filepath"
12 "regexp"
13 "sort"
14 "strings"
15
16 "go.skia.org/infra/go/skerr"
17 "go.skia.org/skia/bazel/exporter/build_proto/build"
18 "go.skia.org/skia/bazel/exporter/interfaces"
19 "google.golang.org/protobuf/proto"
20 )
21
22 // The contents (or partial contents) of a GNI file.
23 type gniFileContents struct {
24 hasExperimental bool // Has at least one file in $_experimental/ dir?
25 hasIncludes bool // Has at least one file in $_include/ dir?
26 hasModules bool // Has at least one file in $_module/ dir?
27 hasRust bool // Has at least one file in $_rust/ dir?
28 hasSrcs bool // Has at least one file in $_src/ dir?
29 bazelFiles map[string]bool // Set of Bazel files generating GNI contents.
30 data []byte // The file contents to be written.
31 }
32
33 // GNIFileListExportDesc contains a description of the data that
34 // will comprise a GN file list variable when written to a *.gni file.
35 type GNIFileListExportDesc struct {
36 // The file list variable name to use in the exported *.gni file.
37 // In the *.gni file this will look like:
38 // var_name = [ ... ]
39 Var string
40 // The Bazel rule name(s) to export into the file list.
41 Rules []string
42 }
43
44 // GNIExportDesc defines a GNI file to be exported, the rules to be
45 // exported, and the file list variable names in which to list the
46 // rule files.
47 type GNIExportDesc struct {
48 GNI string // The export destination *.gni file path (relative to workspace).
49 Vars []GNIFileListExportDesc // List of GNI file list variable rules.
50 }
51
52 // GNIExporterParams contains the construction parameters when
53 // creating a new GNIExporter via NewGNIExporter().
54 type GNIExporterParams struct {
55 WorkspaceDir string // The Bazel workspace directory path.
56 ExportDescs []GNIExportDesc // The Bazel rules to export.
57 }
58
59 // GNIExporter is an object responsible for exporting rules defined in a
60 // Bazel workspace to file lists in GNI format (GN's *.gni files). This exporter
61 // is tightly coupled to the Skia Bazel rules and GNI configuration.
62 type GNIExporter struct {
63 workspaceDir string // The Bazel workspace path.
64 fs interfaces.FileSystem // For filesystem interactions.
65 exportGNIDescs []GNIExportDesc // The rules to export.
66 }
67
68 // The footer written to gn/codec.gni.
69 const codecGNIFooter = `
70 skia_codec_rust_bmp_ffi_crate_root = "$_experimental/rust_bmp/ffi/FFI.rs"
71 skia_codec_rust_png_ffi_crate_root = "$_rust/png/FFI.rs"
72 `
73
74 // The footer written to gn/rust.gni.
75 const rustGNIFooter = `
76 skia_rust_common_ffi_crate_root = "$_rust/common/io_traits_ffi.rs"
77 skia_rust_icc_ffi_crate_root = "$_rust/icc/FFI.rs"
78 `
79
80 // The footer written to gn/sksl_tests.gni.
81 const skslTestsFooter = `sksl_glsl_tests_sources =
82 sksl_error_tests + sksl_glsl_tests + sksl_inliner_tests +
83 sksl_folding_tests + sksl_shared_tests
84
85 sksl_glsl_settings_tests_sources = sksl_blend_tests + sksl_settings_tests
86
87 sksl_metal_tests_sources =
88 sksl_blend_tests + sksl_compute_tests + sksl_metal_tests + sksl_shared_tests
89
90 sksl_hlsl_tests_sources = sksl_blend_tests + sksl_shared_tests
91
92 sksl_wgsl_tests_sources =
93 sksl_blend_tests + sksl_compute_tests + sksl_folding_tests +
94 sksl_shared_tests + sksl_wgsl_tests
95
96 sksl_spirv_tests_sources =
97 sksl_blend_tests + sksl_compute_tests + sksl_shared_tests + sksl_spirv_tests
98
99 sksl_skrp_tests_sources = sksl_folding_tests + sksl_rte_tests + sksl_shared_tests
100
101 sksl_stage_tests_sources =
102 sksl_rte_tests + sksl_mesh_tests + sksl_mesh_error_tests
103
104 sksl_minify_tests_sources = sksl_folding_tests + sksl_mesh_tests + sksl_rte_tests`
105
106 // The footer written to modules/skshaper/skshaper.gni.
107 const skshaperFooter = `
108 declare_args() {
109 skia_enable_skshaper = true
110 }
111 declare_args() {
112 skia_enable_skshaper_tests = skia_enable_skshaper
113 }`
114
115 const portsFooter = `
116 skia_fontations_path_bridge_sources = [
117 "$_src/ports/fontations/src/skpath_bridge.h"
118 ]
119
120 skia_fontations_bridge_root = "$_src/ports/fontations/src/ffi.rs"
121 `
122
123 // Map of GNI file names to footer text to be appended to the end of the file.
124 var footerMap = map[string]string{
125 "gn/codec.gni": codecGNIFooter,
126 "gn/ports.gni": portsFooter,
127 "gn/rust.gni": rustGNIFooter,
128 "gn/sksl_tests.gni": skslTestsFooter,
129 "modules/skshaper/skshaper.gni": skshaperFooter,
130 }
131
132 // Match variable definition of a list in a *.gni file. For example:
133 //
134 // foo = []
135 //
136 // will match "foo"
137 var gniVariableDefReg = regexp.MustCompile(`^(\w+)\s?=\s?\[`)
138
139 // NewGNIExporter creates an exporter that will export to GN's (*.gni) files.
140 func NewGNIExporter(params GNIExporterParams, filesystem interfaces.FileSystem) *GNIExporter {
141 e := &GNIExporter{
142 workspaceDir: params.WorkspaceDir,
143 fs: filesystem,
144 exportGNIDescs: params.ExportDescs,
145 }
146 return e
147 }
148
149 func makeGniFileContents() gniFileContents {
150 return gniFileContents{
151 bazelFiles: make(map[string]bool),
152 }
153 }
154
155 // Given a Bazel rule name find that rule from within the
156 // query results. Returns nil if the given rule is not present.
157 func findQueryResultRule(qr *build.QueryResult, name string) *build.Rule {
158 for _, target := range qr.GetTarget() {
159 r := target.GetRule()
160 if r.GetName() == name {
161 return r
162 }
163 }
164 return nil
165 }
166
167 // Given a relative path to a file return the relative path to the
168 // top directory (in our case the workspace). For example:
169 //
170 // getPathToTopDir("path/to/file.h") -> "../.."
171 //
172 // The paths are to be delimited by forward slashes ('/') - even on
173 // Windows.
174 func getPathToTopDir(path string) string {
175 if filepath.IsAbs(path) {
176 return ""
177 }
178 d, _ := filepath.Split(path)
179 if d == "" {
180 return "."
181 }
182 d = strings.TrimSuffix(d, "/")
183 items := strings.Split(d, "/")
184 var sb = strings.Builder{}
185 for i := 0; i < len(items); i++ {
186 if i > 0 {
187 sb.WriteString("/")
188 }
189 sb.WriteString("..")
190 }
191 return sb.String()
192 }
193
194 // Retrieve all rule attributes which are internal file targets.
195 func getRuleFiles(r *build.Rule, attrName string) ([]string, error) {
196 items, err := getRuleStringArrayAttribute(r, attrName)
197 if err != nil {
198 return nil, skerr.Wrap(err)
199 }
200
201 var files []string
202 for _, item := range items {
203 if !isExternalRule(item) && isFileTarget(item) {
204 files = append(files, item)
205 }
206 }
207 return files, nil
208 }
209
210 // Convert a file path into a workspace relative path using variables to
211 // specify the base folder. The variables are one of $_src, $_include, or $_modules.
212 func makeRelativeFilePathForGNI(path string) (string, error) {
213 if strings.HasPrefix(path, "src/") {
214 return "$_src/" + strings.TrimPrefix(path, "src/"), nil
215 }
216 if strings.HasPrefix(path, "include/") {
217 return "$_include/" + strings.TrimPrefix(path, "include/"), nil
218 }
219 if strings.HasPrefix(path, "modules/") {
220 return "$_modules/" + strings.TrimPrefix(path, "modules/"), nil
221 }
222 if strings.HasPrefix(path, "rust/") {
223 return "$_rust/" + strings.TrimPrefix(path, "rust/"), nil
224 }
225 if strings.HasPrefix(path, "experimental/") {
226 return "$_experimental/" + strings.TrimPrefix(path, "experimental/"), nil
227 }
228 // These sksl tests are purposely listed as a relative path underneath resources/sksl because
229 // that relative path is re-used by the GN logic to put stuff under //tests/sksl as well.
230 if strings.HasPrefix(path, "resources/sksl/") {
231 return strings.TrimPrefix(path, "resources/sksl/"), nil
232 }
233
234 return "", skerr.Fmt("can't find path for %q\n", path)
235 }
236
237 // Convert a slice of workspace relative paths into a new slice containing
238 // GNI variables ($_src, $_include, etc.). *All* paths in the supplied
239 // slice must be a supported top-level directory.
240 func addGNIVariablesToWorkspacePaths(paths []string) ([]string, error) {
241 vars := make([]string, 0, len(paths))
242 for _, path := range paths {
243 withVar, err := makeRelativeFilePathForGNI(path)
244 if err != nil {
245 return nil, skerr.Wrap(err)
246 }
247 vars = append(vars, withVar)
248 }
249 return vars, nil
250 }
251
252 // Is the file path a C++ header?
253 func isHeaderFile(path string) bool {
254 ext := strings.ToLower(filepath.Ext(path))
255 return ext == ".h" || ext == ".hpp"
256 }
257
258 // Does the list of file paths contain only header files?
259 func fileListContainsOnlyCppHeaderFiles(files []string) bool {
260 for _, f := range files {
261 if !isHeaderFile(f) {
262 return false
263 }
264 }
265 return len(files) > 0 // Empty list is false, else all are headers.
266 }
267
268 // Write the *.gni file header.
269 func writeGNFileHeader(writer interfaces.Writer, gniFile *gniFileContents, pathToWorkspace string) {
270 _, _ = fmt.Fprintln(writer, "# DO NOT EDIT: This is a generated file.")
271 _, _ = fmt.Fprintln(writer, "# See //bazel/exporter_tool/README.md for more information.")
272
273 _, _ = fmt.Fprintln(writer, "#")
274 if len(gniFile.bazelFiles) > 1 {
275 keys := make([]string, 0, len(gniFile.bazelFiles))
276 _, _ = fmt.Fprintln(writer, "# The sources of truth are:")
277 for bazelPath := range gniFile.bazelFiles {
278 keys = append(keys, bazelPath)
279 }
280 sort.Strings(keys)
281 for _, wsPath := range keys {
282 _, _ = fmt.Fprintf(writer, "# //%s\n", wsPath)
283 }
284 } else {
285 for bazelPath := range gniFile.bazelFiles {
286 _, _ = fmt.Fprintf(writer, "# The source of truth is //%s\n", bazelPath)
287 }
288 }
289
290 _, _ = writer.WriteString("\n")
291 _, _ = fmt.Fprintln(writer, "# To update this file, run make -C bazel generate_gni")
292
293 _, _ = writer.WriteString("\n")
294 if gniFile.hasExperimental {
295 _, _ = fmt.Fprintf(writer, "_experimental = get_path_info(\"%s/experimental\", \"abspath\")\n", pathToWorkspace)
296 }
297 if gniFile.hasSrcs {
298 _, _ = fmt.Fprintf(writer, "_src = get_path_info(\"%s/src\", \"abspath\")\n", pathToWorkspace)
299 }
300 if gniFile.hasIncludes {
301 _, _ = fmt.Fprintf(writer, "_include = get_path_info(\"%s/include\", \"abspath\")\n", pathToWorkspace)
302 }
303 if gniFile.hasModules {
304 _, _ = fmt.Fprintf(writer, "_modules = get_path_info(\"%s/modules\", \"abspath\")\n", pathToWorkspace)
305 }
306 if gniFile.hasRust {
307 _, _ = fmt.Fprintf(writer, "_rust = get_path_info(\"%s/rust\", \"abspath\")\n", pathToWorkspace)
308 }
309 }
310
311 // removeDuplicates returns the list of files after it has been sorted and
312 // all duplicate values have been removed.
313 func removeDuplicates(files []string) []string {
314 if len(files) <= 1 {
315 return files
316 }
317 sort.Strings(files)
318 rv := make([]string, 0, len(files))
319 rv = append(rv, files[0])
320 for _, f := range files {
321 if rv[len(rv)-1] != f {
322 rv = append(rv, f)
323 }
324 }
325 return rv
326 }
327
328 // Retrieve all sources ("srcs" attribute) and headers ("hdrs" attribute)
329 // and return as a single slice of target names. Slice entries will be
330 // something like:
331 //
332 // "//src/core/file.cpp".
333 func getSrcsAndHdrs(r *build.Rule) ([]string, error) {
334 srcs, err := getRuleFiles(r, "srcs")
335 if err != nil {
336 return nil, skerr.Wrap(err)
337 }
338
339 hdrs, err := getRuleFiles(r, "hdrs")
340 if err != nil {
341 return nil, skerr.Wrap(err)
342 }
343 return append(srcs, hdrs...), nil
344 }
345
346 // Convert a slice of file path targets to workspace relative file paths.
347 // i.e. convert each element like:
348 //
349 // "//src/core/file.cpp"
350 //
351 // into:
352 //
353 // "src/core/file.cpp"
354 func convertTargetsToFilePaths(targets []string) ([]string, error) {
355 paths := make([]string, 0, len(targets))
356 for _, target := range targets {
357 path, err := getFilePathFromFileTarget(target)
358 if err != nil {
359 return nil, skerr.Wrap(err)
360 }
361 paths = append(paths, path)
362 }
363 return paths, nil
364 }
365
366 // Return the top-level component (directory or file) of a relative file path.
367 // The paths are assumed to be delimited by forward slash (/) characters (even on Windows).
368 // An empty string is returned if no top level folder can be found.
369 //
370 // Example:
371 //
372 // "foo/bar/baz.txt" returns "foo"
373 func extractTopLevelFolder(path string) string {
374 parts := strings.Split(path, "/")
375 if len(parts) > 0 {
376 return parts[0]
377 }
378 return ""
379 }
380
381 // Extract the name of a variable assignment from a line of text from a GNI file.
382 // So, a line like:
383 //
384 // "foo = [...]"
385 //
386 // will return:
387 //
388 // "foo"
389 func getGNILineVariable(line string) string {
390 if matches := gniVariableDefReg.FindStringSubmatch(line); matches != nil {
391 return matches[1]
392 }
393 return ""
394 }
395
396 // Given a workspace relative path return an absolute path.
397 func (e *GNIExporter) workspaceToAbsPath(wsPath string) string {
398 if filepath.IsAbs(wsPath) {
399 panic("filepath already absolute")
400 }
401 return filepath.Join(e.workspaceDir, wsPath)
402 }
403
404 // Given an absolute path return a workspace relative path.
405 func (e *GNIExporter) absToWorkspacePath(absPath string) (string, error) {
406 if !filepath.IsAbs(absPath) {
407 return "", skerr.Fmt(`"%s" is not an absolute path`, absPath)
408 }
409 if absPath == e.workspaceDir {
410 return "", nil
411 }
412 wsDir := e.workspaceDir + "/"
413 if !strings.HasPrefix(absPath, wsDir) {
414 return "", skerr.Fmt(`"%s" is not in the workspace "%s"`, absPath, wsDir)
415 }
416 return strings.TrimPrefix(absPath, wsDir), nil
417 }
418
419 // Merge the another file contents object into this one.
420 func (c *gniFileContents) merge(other gniFileContents) {
421 if other.hasExperimental {
422 c.hasExperimental = true
423 }
424 if other.hasIncludes {
425 c.hasIncludes = true
426 }
427 if other.hasModules {
428 c.hasModules = true
429 }
430 if other.hasRust {
431 c.hasRust = true
432 }
433 if other.hasSrcs {
434 c.hasSrcs = true
435 }
436 for path := range other.bazelFiles {
437 c.bazelFiles[path] = true
438 }
439 c.data = append(c.data, other.data...)
440 }
441
442 // Convert all rules that go into a GNI file list.
443 func (e *GNIExporter) convertGNIFileList(desc GNIFileListExportDesc, qr *build.QueryResult) (gniFileContents, error) {
444 var rules []string
445 fileContents := makeGniFileContents()
446 var targets []string
447 for _, ruleName := range desc.Rules {
448 r := findQueryResultRule(qr, ruleName)
449 if r == nil {
450 return gniFileContents{}, skerr.Fmt("Cannot find rule %s", ruleName)
451 }
452 absBazelPath, _, _, err := parseLocation(*r.Location)
453 if err != nil {
454 return gniFileContents{}, skerr.Wrap(err)
455 }
456 wsBazelpath, err := e.absToWorkspacePath(absBazelPath)
457 if err != nil {
458 return gniFileContents{}, skerr.Wrap(err)
459 }
460 fileContents.bazelFiles[wsBazelpath] = true
461 t, err := getSrcsAndHdrs(r)
462 if err != nil {
463 return gniFileContents{}, skerr.Wrap(err)
464 }
465 if len(t) == 0 {
466 return gniFileContents{}, skerr.Fmt("No files to export in rule %s", ruleName)
467 }
468 targets = append(targets, t...)
469 rules = append(rules, ruleName)
470 }
471
472 files, err := convertTargetsToFilePaths(targets)
473 if err != nil {
474 return gniFileContents{}, skerr.Wrap(err)
475 }
476
477 files, err = addGNIVariablesToWorkspacePaths(files)
478 if err != nil {
479 return gniFileContents{}, skerr.Wrap(err)
480 }
481
482 files = removeDuplicates(files)
483
484 for i := range files {
485 if strings.HasPrefix(files[i], "$_experimental/") {
486 fileContents.hasExperimental = true
487 } else if strings.HasPrefix(files[i], "$_src/") {
488 fileContents.hasSrcs = true
489 } else if strings.HasPrefix(files[i], "$_include/") {
490 fileContents.hasIncludes = true
491 } else if strings.HasPrefix(files[i], "$_modules/") {
492 fileContents.hasModules = true
493 } else if strings.HasPrefix(files[i], "$_rust/") {
494 fileContents.hasRust = true
495 }
496 }
497
498 var contents bytes.Buffer
499
500 if len(rules) > 1 {
501 _, _ = fmt.Fprintln(&contents, "# List generated by Bazel rules:")
502 for _, bazelFile := range rules {
503 _, _ = fmt.Fprintf(&contents, "# %s\n", bazelFile)
504 }
505 } else if len(rules) > 0 {
506 _, _ = fmt.Fprintf(&contents, "# Generated by Bazel rule %s\n", rules[0])
507 }
508 _, _ = fmt.Fprintf(&contents, "%s = [\n", desc.Var)
509
510 for _, target := range files {
511 _, _ = fmt.Fprintf(&contents, " %q,\n", target)
512 }
513 _, _ = fmt.Fprintln(&contents, "]")
514 _, _ = fmt.Fprintln(&contents)
515 fileContents.data = contents.Bytes()
516
517 return fileContents, nil
518 }
519
520 // Export all Bazel rules to a single *.gni file.
521 func (e *GNIExporter) exportGNIFile(gniExportDesc GNIExportDesc, qr *build.QueryResult) error {
522 // Keep the contents of each file list in memory before writing to disk.
523 // This is done so that we know what variables to define for each of the
524 // file lists. i.e. $_src, $_include, etc.
525 gniFileContents := makeGniFileContents()
526 for _, varDesc := range gniExportDesc.Vars {
527 fileListContents, err := e.convertGNIFileList(varDesc, qr)
528 if err != nil {
529 return skerr.Wrap(err)
530 }
531 gniFileContents.merge(fileListContents)
532 }
533
534 writer, err := e.fs.OpenFile(e.workspaceToAbsPath(gniExportDesc.GNI))
535 if err != nil {
536 return skerr.Wrap(err)
537 }
538
539 pathToWorkspace := getPathToTopDir(gniExportDesc.GNI)
540 writeGNFileHeader(writer, &gniFileContents, pathToWorkspace)
541 _, _ = writer.WriteString("\n")
542
543 _, err = writer.Write(gniFileContents.data)
544 if err != nil {
545 return skerr.Wrap(err)
546 }
547
548 for gniPath, footer := range footerMap {
549 if gniExportDesc.GNI == gniPath {
550 _, _ = fmt.Fprintln(writer, footer)
551 break
552 }
553 }
554
555 return nil
556 }
557
558 // Export the contents of a Bazel query response to one or more GNI
559 // files.
560 //
561 // The Bazel data to export, and the destination GNI files are defined
562 // by the configuration data supplied to NewGNIExporter().
563 func (e *GNIExporter) Export(qcmd interfaces.QueryCommand) error {
564 in, err := qcmd.Read()
565 if err != nil {
566 return skerr.Wrapf(err, "error reading bazel cquery data")
567 }
568 qr := &build.QueryResult{}
569 if err := proto.Unmarshal(in, qr); err != nil {
570 return skerr.Wrapf(err, "failed to unmarshal cquery result")
571 }
572 for _, desc := range e.exportGNIDescs {
573 err = e.exportGNIFile(desc, qr)
574 if err != nil {
575 return skerr.Wrap(err)
576 }
577 }
578 return nil
579 }
580
581 // Make sure GNIExporter fulfills the Exporter interface.
582 var _ interfaces.Exporter = (*GNIExporter)(nil)