blob: 654d971fe998e40630eb70ba8d255a7c6a7b0301 [file] [log] [blame]
Jorge E. Moreira02f464c2018-07-06 11:30:34 -07001/*
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 Haining10e42312018-07-17 12:11:52 -070019#include <glog/logging.h>
20
21#include <array>
22#include <climits>
23#include <cstdlib>
Jorge E. Moreira02f464c2018-07-06 11:30:34 -070024#include <sys/types.h>
25#include <sys/stat.h>
26#include <unistd.h>
27
28namespace cvd {
29
30bool FileHasContent(const std::string& path) {
Cody Schuffelen2402ee52018-12-05 17:51:36 -080031 return FileSize(path) > 0;
Jorge E. Moreira02f464c2018-07-06 11:30:34 -070032}
33
34bool DirectoryExists(const std::string& path) {
35 struct stat st;
Ryan Haining10e42312018-07-17 12:11:52 -070036 if (stat(path.c_str(), &st) == -1) {
37 return false;
38 }
39 if ((st.st_mode & S_IFMT) != S_IFDIR) {
40 return false;
41 }
Jorge E. Moreira02f464c2018-07-06 11:30:34 -070042 return true;
43}
Ryan Haining10e42312018-07-17 12:11:52 -070044
Ryan Hainingd3f185d2018-07-19 12:11:47 -070045std::string AbsolutePath(const std::string& path) {
46 if (path.empty()) {
Ryan Haining10e42312018-07-17 12:11:52 -070047 return {};
48 }
Ryan Hainingd3f185d2018-07-19 12:11:47 -070049 if (path[0] == '/') {
50 return path;
51 }
52
53 std::array<char, PATH_MAX> buffer{};
54 if (!realpath(".", buffer.data())) {
55 LOG(WARNING) << "Could not get real path for current directory \".\""
56 << ": " << strerror(errno);
57 return {};
58 }
59 return std::string{buffer.data()} + "/" + path;
Ryan Haining10e42312018-07-17 12:11:52 -070060}
61
Cody Schuffelen2402ee52018-12-05 17:51:36 -080062off_t FileSize(const std::string& path) {
63 struct stat st;
64 if (stat(path.c_str(), &st) == -1) {
65 return 0;
66 }
67 return st.st_size;
68}
69
Jorge E. Moreira02f464c2018-07-06 11:30:34 -070070} // namespace cvd