blob: 30f298a0c8b80776e33ce230292f90fe90f212aa [file] [log] [blame]
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001// Copyright 2020 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
15package bp2build
16
17import (
18 "android/soong/android"
19 "os"
20)
21
22// The Bazel bp2build singleton is responsible for writing .bzl files that are equivalent to
23// Android.bp files that are capable of being built with Bazel.
24func init() {
25 android.RegisterBazelConverterPreSingletonType("androidbp_to_build", AndroidBpToBuildSingleton)
26}
27
28func AndroidBpToBuildSingleton() android.Singleton {
29 return &androidBpToBuildSingleton{
30 name: "bp2build",
31 }
32}
33
34type androidBpToBuildSingleton struct {
35 name string
36 outputDir android.OutputPath
37}
38
39func (s *androidBpToBuildSingleton) GenerateBuildActions(ctx android.SingletonContext) {
40 s.outputDir = android.PathForOutput(ctx, s.name)
41 android.RemoveAllOutputDir(s.outputDir)
42
43 if !ctx.Config().IsEnvTrue("CONVERT_TO_BAZEL") {
44 return
45 }
46
47 ruleShims := CreateRuleShims(android.ModuleTypeFactories())
48
49 buildToTargets := GenerateSoongModuleTargets(ctx)
50
51 filesToWrite := CreateBazelFiles(ruleShims, buildToTargets)
52 for _, f := range filesToWrite {
53 if err := s.writeFile(ctx, f); err != nil {
54 ctx.Errorf("Failed to write %q (dir %q) due to %q", f.Basename, f.Dir, err)
55 }
56 }
57}
58
59func (s *androidBpToBuildSingleton) getOutputPath(ctx android.PathContext, dir string) android.OutputPath {
60 return s.outputDir.Join(ctx, dir)
61}
62
63func (s *androidBpToBuildSingleton) writeFile(ctx android.PathContext, f BazelFile) error {
64 return writeReadOnlyFile(ctx, s.getOutputPath(ctx, f.Dir), f.Basename, f.Contents)
65}
66
67// The auto-conversion directory should be read-only, sufficient for bazel query. The files
68// are not intended to be edited by end users.
69func writeReadOnlyFile(ctx android.PathContext, dir android.OutputPath, baseName, content string) error {
70 android.CreateOutputDirIfNonexistent(dir, os.ModePerm)
71 pathToFile := dir.Join(ctx, baseName)
72
73 // 0444 is read-only
74 err := android.WriteFileToOutputDir(pathToFile, []byte(content), 0444)
75
76 return err
77}