• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// 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 main
16
17import (
18	"io/ioutil"
19	"os"
20	"path/filepath"
21
22	"android/soong/android"
23	"android/soong/bp2build"
24)
25
26func createBazelQueryView(ctx *bp2build.CodegenContext, bazelQueryViewDir string) error {
27	os.RemoveAll(bazelQueryViewDir)
28	ruleShims := bp2build.CreateRuleShims(android.ModuleTypeFactories())
29
30	res, err := bp2build.GenerateBazelTargets(ctx, true)
31	if err != nil {
32		panic(err)
33	}
34
35	filesToWrite := bp2build.CreateBazelFiles(ruleShims, res.BuildDirToTargets(), bp2build.QueryView)
36	for _, f := range filesToWrite {
37		if err := writeReadOnlyFile(bazelQueryViewDir, f); err != nil {
38			return err
39		}
40	}
41
42	return nil
43}
44
45// The auto-conversion directory should be read-only, sufficient for bazel query. The files
46// are not intended to be edited by end users.
47func writeReadOnlyFile(dir string, f bp2build.BazelFile) error {
48	dir = filepath.Join(dir, f.Dir)
49	if err := createDirectoryIfNonexistent(dir); err != nil {
50		return err
51	}
52	pathToFile := filepath.Join(dir, f.Basename)
53
54	// 0444 is read-only
55	err := ioutil.WriteFile(pathToFile, []byte(f.Contents), 0444)
56
57	return err
58}
59
60func createDirectoryIfNonexistent(dir string) error {
61	if _, err := os.Stat(dir); os.IsNotExist(err) {
62		return os.MkdirAll(dir, os.ModePerm)
63	} else {
64		return err
65	}
66}
67