xref: /aosp_15_r20/external/sandboxed-api/oss-internship-2020/gdal/raster_to_gtiff/utils.cc (revision ec63e07ab9515d95e79c211197c445ef84cefa6a)
1 // Copyright 2020 Google LLC
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 //     https://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 #include "utils.h"  // NOLINT(build/include)
16 
17 #include <unistd.h>
18 
19 #include "sandboxed_api/util/fileops.h"
20 #include "sandboxed_api/util/path.h"
21 #include "sandboxed_api/util/temp_file.h"
22 
23 namespace gdal::sandbox::utils {
24 
25 namespace {
26 
27 constexpr char kProjDbEnvVariableName[] = "PROJ_DB_PATH";
28 inline constexpr absl::string_view kDefaultProjDbPath =
29     "/usr/local/share/proj/proj.db";
30 
31 }  // namespace
32 
TempFile(absl::string_view prefix)33 TempFile::TempFile(absl::string_view prefix) {
34   auto file_data = sandbox2::CreateNamedTempFile(prefix);
35 
36   if (file_data.ok()) {
37     file_data_ = std::move(file_data.value());
38   }
39 }
40 
~TempFile()41 TempFile::~TempFile() {
42   if (HasValue()) {
43     unlink(file_data_.value().first.c_str());
44   }
45 }
46 
HasValue() const47 bool TempFile::HasValue() const { return file_data_.has_value(); }
48 
GetFd() const49 int TempFile::GetFd() const { return file_data_.value().second; }
50 
GetPath() const51 std::string TempFile::GetPath() const { return file_data_.value().first; }
52 
FindProjDbPath()53 std::optional<std::string> FindProjDbPath() {
54   std::string proj_db_path(kDefaultProjDbPath);
55 
56   if (const char* proj_db_env_var = std::getenv(kProjDbEnvVariableName);
57       proj_db_env_var != nullptr) {
58     proj_db_path = proj_db_env_var;
59   }
60 
61   if (!sandbox2::file_util::fileops::Exists(proj_db_path, false)) {
62     return std::nullopt;
63   }
64 
65   return proj_db_path;
66 }
67 
GetTestDataPath(absl::string_view testdata_path)68 std::string GetTestDataPath(absl::string_view testdata_path) {
69   const char* test_srcdir = std::getenv("TEST_SRCDIR");
70 
71   return sandbox2::file::JoinPath(test_srcdir == nullptr
72                                       ? sandbox2::file_util::fileops::GetCWD()
73                                       : test_srcdir,
74                                   testdata_path);
75 }
76 
77 }  // namespace gdal::sandbox::utils
78