Jorge E. Moreira | 02f464c | 2018-07-06 11:30:34 -0700 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2017 The Android Open Source Project |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | #include "common/libs/utils/files.h" |
| 18 | |
Ryan Haining | 10e4231 | 2018-07-17 12:11:52 -0700 | [diff] [blame^] | 19 | #include <glog/logging.h> |
| 20 | |
| 21 | #include <array> |
| 22 | #include <climits> |
| 23 | #include <cstdlib> |
Jorge E. Moreira | 02f464c | 2018-07-06 11:30:34 -0700 | [diff] [blame] | 24 | #include <sys/types.h> |
| 25 | #include <sys/stat.h> |
| 26 | #include <unistd.h> |
| 27 | |
| 28 | namespace cvd { |
| 29 | |
| 30 | bool FileHasContent(const std::string& path) { |
| 31 | struct stat st; |
Ryan Haining | 10e4231 | 2018-07-17 12:11:52 -0700 | [diff] [blame^] | 32 | if (stat(path.c_str(), &st) == -1) { |
Jorge E. Moreira | 02f464c | 2018-07-06 11:30:34 -0700 | [diff] [blame] | 33 | return false; |
Ryan Haining | 10e4231 | 2018-07-17 12:11:52 -0700 | [diff] [blame^] | 34 | } |
| 35 | if (st.st_size == 0) { |
Jorge E. Moreira | 02f464c | 2018-07-06 11:30:34 -0700 | [diff] [blame] | 36 | return false; |
Ryan Haining | 10e4231 | 2018-07-17 12:11:52 -0700 | [diff] [blame^] | 37 | } |
Jorge E. Moreira | 02f464c | 2018-07-06 11:30:34 -0700 | [diff] [blame] | 38 | return true; |
| 39 | } |
| 40 | |
| 41 | bool DirectoryExists(const std::string& path) { |
| 42 | struct stat st; |
Ryan Haining | 10e4231 | 2018-07-17 12:11:52 -0700 | [diff] [blame^] | 43 | if (stat(path.c_str(), &st) == -1) { |
| 44 | return false; |
| 45 | } |
| 46 | if ((st.st_mode & S_IFMT) != S_IFDIR) { |
| 47 | return false; |
| 48 | } |
Jorge E. Moreira | 02f464c | 2018-07-06 11:30:34 -0700 | [diff] [blame] | 49 | return true; |
| 50 | } |
Ryan Haining | 10e4231 | 2018-07-17 12:11:52 -0700 | [diff] [blame^] | 51 | |
| 52 | std::string RealPath(const std::string& path) { |
| 53 | std::array<char, PATH_MAX> buffer{}; |
| 54 | if (!realpath(path.c_str(), buffer.data())) { |
| 55 | LOG(WARNING) << "Could not get real path for file " << path << ": " |
| 56 | << strerror(errno); |
| 57 | return {}; |
| 58 | } |
| 59 | return {buffer.data()}; |
| 60 | } |
| 61 | |
Jorge E. Moreira | 02f464c | 2018-07-06 11:30:34 -0700 | [diff] [blame] | 62 | } // namespace cvd |