1 /* Copyright 2016 The TensorFlow Authors. 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
16 #include "tensorflow/core/util/env_var.h"
17
18 #include <stdlib.h>
19
20 #include "tensorflow/core/lib/core/errors.h"
21 #include "tensorflow/core/lib/strings/numbers.h"
22 #include "tensorflow/core/lib/strings/str_util.h"
23 #include "tensorflow/core/lib/strings/strcat.h"
24 #include "tensorflow/core/platform/logging.h"
25
26 namespace tensorflow {
27
ReadBoolFromEnvVar(StringPiece env_var_name,bool default_val,bool * value)28 Status ReadBoolFromEnvVar(StringPiece env_var_name, bool default_val,
29 bool* value) {
30 *value = default_val;
31 const char* tf_env_var_val = getenv(string(env_var_name).c_str());
32 if (tf_env_var_val == nullptr) {
33 return Status::OK();
34 }
35 string str_value = str_util::Lowercase(tf_env_var_val);
36 if (str_value == "0" || str_value == "false") {
37 *value = false;
38 return Status::OK();
39 } else if (str_value == "1" || str_value == "true") {
40 *value = true;
41 return Status::OK();
42 }
43 return errors::InvalidArgument(strings::StrCat(
44 "Failed to parse the env-var ${", env_var_name, "} into bool: ",
45 tf_env_var_val, ". Use the default value: ", default_val));
46 }
47
ReadInt64FromEnvVar(StringPiece env_var_name,int64 default_val,int64 * value)48 Status ReadInt64FromEnvVar(StringPiece env_var_name, int64 default_val,
49 int64* value) {
50 *value = default_val;
51 const char* tf_env_var_val = getenv(string(env_var_name).c_str());
52 if (tf_env_var_val == nullptr) {
53 return Status::OK();
54 }
55 if (strings::safe_strto64(tf_env_var_val, value)) {
56 return Status::OK();
57 }
58 return errors::InvalidArgument(strings::StrCat(
59 "Failed to parse the env-var ${", env_var_name, "} into int64: ",
60 tf_env_var_val, ". Use the default value: ", default_val));
61 }
62
ReadStringFromEnvVar(StringPiece env_var_name,StringPiece default_val,string * value)63 Status ReadStringFromEnvVar(StringPiece env_var_name, StringPiece default_val,
64 string* value) {
65 const char* tf_env_var_val = getenv(string(env_var_name).c_str());
66 if (tf_env_var_val != nullptr) {
67 *value = tf_env_var_val;
68 } else {
69 *value = string(default_val);
70 }
71 return Status::OK();
72 }
73
74 } // namespace tensorflow
75