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 6package exporter 7 8import ( 9 "io" 10 11 "go.skia.org/infra/go/skerr" 12 "go.skia.org/infra/go/util" 13 "go.skia.org/skia/bazel/exporter/build_proto/build" 14) 15 16// cmakeRule represents the CMake equivalent to a Bazel rule. 17type cmakeRule struct { 18 contents []byte // Data to be written to CMake file. 19 deps []string // Names of Bazel targets (not files) on which this rule directly depends. 20 rule *build.Rule // Holding pointer because struct contains a Mutex. 21} 22 23// newCMakeRule will create a new CMake rule object. 24func newCMakeRule(r *build.Rule) *cmakeRule { 25 return &cmakeRule{rule: r} 26} 27 28// Return the rule name. 29func (r *cmakeRule) getName() string { 30 return r.rule.GetName() 31} 32 33// Does this rule contain source dependencies? 34func (r *cmakeRule) hasSrcs() bool { 35 srcs, _ := getRuleStringArrayAttribute(r.rule, "srcs") 36 return len(srcs) > 0 37} 38 39// Does this rule depend directly on a rule. 40func (r *cmakeRule) hasDependency(ruleName string) bool { 41 return util.In(ruleName, r.deps) 42} 43 44// Add a rule dependency. 45func (r *cmakeRule) addDependency(ruleName string) error { 46 if ruleName == "" { 47 return skerr.Fmt("empty rule name") 48 } 49 if ruleName == r.getName() { 50 return skerr.Fmt("rule cannot depend on self: %s", ruleName) 51 } 52 if r.hasDependency(ruleName) { 53 return nil 54 } 55 // Trusting that circular dependencies are already fixed by Bazel. 56 r.deps = append(r.deps, ruleName) 57 return nil 58} 59 60// setContents will set the supplied chunk of a CMake project file to this 61// rules contents. 62func (r *cmakeRule) setContents(contents []byte) { 63 r.contents = contents 64} 65 66// Write the contents for this rule using the supplied writer. 67// Returns the number of bytes written and error. 68func (r *cmakeRule) write(writer io.Writer) (int, error) { 69 if len(r.contents) == 0 { 70 return 0, skerr.Fmt("rule %s has no contents", r.getName()) 71 } 72 return writer.Write(r.contents) 73} 74