blob: ad084da66c5f5bab38ace2a49b5d25ec47081583 [file] [log] [blame]
Dan Willemsen1e704462016-08-21 15:17:17 -07001// Copyright 2017 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 build
16
17import (
18 "os"
19 "path/filepath"
20 "strings"
21)
22
23// indexList finds the index of a string in a []string
24func indexList(s string, list []string) int {
25 for i, l := range list {
26 if l == s {
27 return i
28 }
29 }
30
31 return -1
32}
33
34// inList determines whether a string is in a []string
35func inList(s string, list []string) bool {
36 return indexList(s, list) != -1
37}
38
39// ensureDirectoriesExist is a shortcut to os.MkdirAll, sending errors to the ctx logger.
40func ensureDirectoriesExist(ctx Context, dirs ...string) {
41 for _, dir := range dirs {
42 err := os.MkdirAll(dir, 0777)
43 if err != nil {
44 ctx.Fatalf("Error creating %s: %q\n", dir, err)
45 }
46 }
47}
48
49// ensureEmptyFileExists ensures that the containing directory exists, and the
50// specified file exists. If it doesn't exist, it will write an empty file.
51func ensureEmptyFileExists(ctx Context, file string) {
52 ensureDirectoriesExist(ctx, filepath.Dir(file))
53 if _, err := os.Stat(file); os.IsNotExist(err) {
54 f, err := os.Create(file)
55 if err != nil {
56 ctx.Fatalf("Error creating %s: %q\n", file, err)
57 }
58 f.Close()
59 } else if err != nil {
60 ctx.Fatalf("Error checking %s: %q\n", file, err)
61 }
62}
63
64// singleUnquote is similar to strconv.Unquote, but can handle multi-character strings inside single quotes.
65func singleUnquote(str string) (string, bool) {
66 if len(str) < 2 || str[0] != '\'' || str[len(str)-1] != '\'' {
67 return "", false
68 }
69 return str[1 : len(str)-1], true
70}
71
72// decodeKeyValue decodes a key=value string
73func decodeKeyValue(str string) (string, string, bool) {
74 idx := strings.IndexRune(str, '=')
75 if idx == -1 {
76 return "", "", false
77 }
78 return str[:idx], str[idx+1:], true
79}