blob: 49729e02ac26a10ac11d59c3d0436546065e4a7f [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"
Jingwen Chendaa54bc2020-12-14 02:58:54 -050019 "fmt"
Liz Kammer2dd9ca42020-11-25 16:06:39 -080020 "os"
21)
22
Jingwen Chendaa54bc2020-12-14 02:58:54 -050023// The Bazel bp2build code generator is responsible for writing .bzl files that are equivalent to
Liz Kammer2dd9ca42020-11-25 16:06:39 -080024// Android.bp files that are capable of being built with Bazel.
Jingwen Chendaa54bc2020-12-14 02:58:54 -050025func Codegen(ctx CodegenContext) {
26 outputDir := android.PathForOutput(ctx, "bp2build")
27 android.RemoveAllOutputDir(outputDir)
Liz Kammer2dd9ca42020-11-25 16:06:39 -080028
29 ruleShims := CreateRuleShims(android.ModuleTypeFactories())
30
Jingwen Chendaa54bc2020-12-14 02:58:54 -050031 buildToTargets := GenerateSoongModuleTargets(ctx.Context())
Liz Kammer2dd9ca42020-11-25 16:06:39 -080032
33 filesToWrite := CreateBazelFiles(ruleShims, buildToTargets)
34 for _, f := range filesToWrite {
Jingwen Chendaa54bc2020-12-14 02:58:54 -050035 if err := writeFile(outputDir, ctx, f); err != nil {
36 fmt.Errorf("Failed to write %q (dir %q) due to %q", f.Basename, f.Dir, err)
Liz Kammer2dd9ca42020-11-25 16:06:39 -080037 }
38 }
39}
40
Jingwen Chendaa54bc2020-12-14 02:58:54 -050041func writeFile(outputDir android.OutputPath, ctx android.PathContext, f BazelFile) error {
42 return writeReadOnlyFile(ctx, getOutputPath(outputDir, ctx, f.Dir), f.Basename, f.Contents)
Liz Kammer2dd9ca42020-11-25 16:06:39 -080043}
44
Jingwen Chendaa54bc2020-12-14 02:58:54 -050045func getOutputPath(outputDir android.OutputPath, ctx android.PathContext, dir string) android.OutputPath {
46 return outputDir.Join(ctx, dir)
Liz Kammer2dd9ca42020-11-25 16:06:39 -080047}
48
49// The auto-conversion directory should be read-only, sufficient for bazel query. The files
50// are not intended to be edited by end users.
51func writeReadOnlyFile(ctx android.PathContext, dir android.OutputPath, baseName, content string) error {
52 android.CreateOutputDirIfNonexistent(dir, os.ModePerm)
53 pathToFile := dir.Join(ctx, baseName)
54
55 // 0444 is read-only
56 err := android.WriteFileToOutputDir(pathToFile, []byte(content), 0444)
57
58 return err
59}