1// Copyright 2017 Google Inc. 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// Package bazel provides utilities for interacting with the surrounding Bazel environment. 16package bazel 17 18import ( 19 "fmt" 20 "io/ioutil" 21 "os" 22) 23 24const TEST_SRCDIR = "TEST_SRCDIR" 25const TEST_TMPDIR = "TEST_TMPDIR" 26const TEST_WORKSPACE = "TEST_WORKSPACE" 27 28// NewTmpDir creates a new temporary directory in TestTmpDir(). 29func NewTmpDir(prefix string) (string, error) { 30 return ioutil.TempDir(TestTmpDir(), prefix) 31} 32 33// TestTmpDir returns the path the Bazel test temp directory. 34// If TEST_TMPDIR is not defined, it returns the OS default temp dir. 35func TestTmpDir() string { 36 if tmp, ok := os.LookupEnv(TEST_TMPDIR); ok { 37 return tmp 38 } 39 return os.TempDir() 40} 41 42// SpliceDelimitedOSArgs is a utility function that scans the os.Args list for 43// entries delimited by the begin and end delimiters (typically the values 44// "-begin_files" and "-end_files" are used). Entries between these delimiters 45// are spliced out of from os.Args and returned to the caller. If the ordering 46// of -begin_files or -end_files is malformed, error is returned. 47func SpliceDelimitedOSArgs(begin, end string) ([]string, error) { 48 var files []string 49 beginFiles, endFiles := -1, -1 50 for i, arg := range os.Args { 51 if arg == begin { 52 beginFiles = i 53 } else if arg == end { 54 endFiles = i 55 break 56 } else if arg == "--" { 57 break 58 } 59 } 60 61 if beginFiles >= 0 && endFiles < 0 || 62 beginFiles < 0 && endFiles >= 0 || 63 beginFiles >= 0 && beginFiles >= endFiles { 64 return nil, fmt.Errorf("error: %s, %s not set together or in order", begin, end) 65 } 66 67 if beginFiles >= 0 { 68 files = os.Args[beginFiles+1 : endFiles] 69 os.Args = append(os.Args[:beginFiles:beginFiles], os.Args[endFiles+1:]...) 70 } 71 72 return files, nil 73} 74