blob: a98e1f6a8895db91ee49cba584942b6da6a40724 [file] [log] [blame]
Colin Cross68f55102015-03-25 14:43:57 -07001// Copyright 2015 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
15// env implements the environment JSON file handling for the soong_env command line tool run before
16// the builder and for the env writer in the builder.
17package env
18
19import (
20 "encoding/json"
21 "fmt"
22 "io/ioutil"
23 "os"
24 "sort"
25)
26
27type envFileEntry struct{ Key, Value string }
28type envFileData []envFileEntry
29
Colin Cross988414c2020-01-11 01:11:46 +000030func EnvFileContents(envDeps map[string]string) ([]byte, error) {
Colin Cross68f55102015-03-25 14:43:57 -070031 contents := make(envFileData, 0, len(envDeps))
32 for key, value := range envDeps {
33 contents = append(contents, envFileEntry{key, value})
34 }
35
36 sort.Sort(contents)
37
38 data, err := json.MarshalIndent(contents, "", " ")
39 if err != nil {
Colin Cross988414c2020-01-11 01:11:46 +000040 return nil, err
Colin Cross68f55102015-03-25 14:43:57 -070041 }
42
43 data = append(data, '\n')
44
Colin Cross988414c2020-01-11 01:11:46 +000045 return data, nil
Colin Cross68f55102015-03-25 14:43:57 -070046}
47
48func StaleEnvFile(filename string) (bool, error) {
49 data, err := ioutil.ReadFile(filename)
50 if err != nil {
51 return true, err
52 }
53
54 var contents envFileData
55
56 err = json.Unmarshal(data, &contents)
57 if err != nil {
58 return true, err
59 }
60
61 var changed []string
62 for _, entry := range contents {
63 key := entry.Key
64 old := entry.Value
65 cur := os.Getenv(key)
66 if old != cur {
67 changed = append(changed, fmt.Sprintf("%s (%q -> %q)", key, old, cur))
68 }
69 }
70
71 if len(changed) > 0 {
72 fmt.Printf("environment variables changed value:\n")
73 for _, s := range changed {
74 fmt.Printf(" %s\n", s)
75 }
76 return true, nil
77 }
78
79 return false, nil
80}
81
82func (e envFileData) Len() int {
83 return len(e)
84}
85
86func (e envFileData) Less(i, j int) bool {
87 return e[i].Key < e[j].Key
88}
89
90func (e envFileData) Swap(i, j int) {
91 e[i], e[j] = e[j], e[i]
92}