Merge "Load RBE related env vars from config files" am: b3a5d18470

Original change: https://android-review.googlesource.com/c/platform/build/soong/+/1773209

Bug: b/194679562
Change-Id: Id84167a3ae6ab15c8b74b72b4cc2c179e0da5d0c
Merged-In: I416e8da75f84aa2b53995f525cf50501488dc972
(cherry picked from commit a7ab7c9394ccfc80e163b5e405792a3975eaf2f3)
diff --git a/cmd/soong_ui/main.go b/cmd/soong_ui/main.go
index 345a821..d416d54 100644
--- a/cmd/soong_ui/main.go
+++ b/cmd/soong_ui/main.go
@@ -16,8 +16,10 @@
 
 import (
 	"context"
+	"encoding/json"
 	"flag"
 	"fmt"
+	"io/ioutil"
 	"os"
 	"path/filepath"
 	"strconv"
@@ -32,6 +34,11 @@
 	"android/soong/ui/tracer"
 )
 
+const (
+	configDir  = "vendor/google/tools/soong_config"
+	jsonSuffix = "json"
+)
+
 func indexList(s string, list []string) int {
 	for i, l := range list {
 		if l == s {
@@ -46,6 +53,34 @@
 	return indexList(s, list) != -1
 }
 
+func loadEnvConfig() error {
+	bc := os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG")
+	if bc == "" {
+		return nil
+	}
+	cfgFile := filepath.Join(os.Getenv("TOP"), configDir, fmt.Sprintf("%s.%s", bc, jsonSuffix))
+
+	envVarsJSON, err := ioutil.ReadFile(cfgFile)
+	if err != nil {
+		fmt.Fprintf(os.Stderr, "\033[33mWARNING:\033[0m failed to open config file %s: %s\n", cfgFile, err.Error())
+		return nil
+	}
+
+	var envVars map[string]map[string]string
+	if err := json.Unmarshal(envVarsJSON, &envVars); err != nil {
+		return fmt.Errorf("env vars config file: %s did not parse correctly: %s", cfgFile, err.Error())
+	}
+	for k, v := range envVars["env"] {
+		if os.Getenv(k) != "" {
+			continue
+		}
+		if err := os.Setenv(k, v); err != nil {
+			return err
+		}
+	}
+	return nil
+}
+
 func main() {
 	buildStarted := time.Now()
 	var stdio terminal.StdioInterface
@@ -113,6 +148,12 @@
 		config = build.NewConfig(buildCtx, os.Args[1:]...)
 	}
 
+	if err := loadEnvConfig(); err != nil {
+		fmt.Fprintf(os.Stderr, "failed to parse env config files: %v", err)
+		os.Exit(1)
+	}
+
+
 	build.SetupOutDir(buildCtx, config)
 
 	logsDir := config.OutDir()