32#include "google/protobuf/util/json_util.h"
33#include "nlohmann/json.hpp"
39using std::istreambuf_iterator;
44 int file_descriptor) {
45 using google::protobuf::TextFormat;
46 using google::protobuf::io::FileOutputStream;
47 using google::protobuf::io::ZeroCopyOutputStream;
48 if (file_descriptor < 0) {
49 AERROR <<
"Invalid file descriptor.";
52 ZeroCopyOutputStream *output =
new FileOutputStream(file_descriptor);
53 bool success = TextFormat::Print(message, output);
55 close(file_descriptor);
60 const std::string &file_name) {
61 int fd = open(file_name.c_str(), O_WRONLY | O_CREAT | O_TRUNC, S_IRWXU);
63 AERROR <<
"Unable to open file " << file_name <<
" to write.";
70 const std::string &file_name) {
71 int fd = open(file_name.c_str(), O_WRONLY | O_CREAT | O_TRUNC, S_IRWXU);
73 AERROR <<
"Unable to open file " << file_name <<
" to write.";
77 ssize_t bytes_written = write(fd, content.c_str(), content.size());
78 if (bytes_written < 0) {
79 AERROR <<
"Failed to write to file.";
90 google::protobuf::Message *message) {
91 using google::protobuf::TextFormat;
92 using google::protobuf::io::FileInputStream;
93 using google::protobuf::io::ZeroCopyInputStream;
94 int file_descriptor = open(file_name.c_str(), O_RDONLY);
95 if (file_descriptor < 0) {
96 AERROR <<
"Failed to open file " << file_name <<
" in text mode.";
101 ZeroCopyInputStream *input =
new FileInputStream(file_descriptor);
102 bool success = TextFormat::Parse(input, message);
104 AERROR <<
"Failed to parse file " << file_name <<
" as text proto.";
107 close(file_descriptor);
112 const std::string &file_name) {
113 std::fstream output(file_name,
114 std::ios::out | std::ios::trunc | std::ios::binary);
115 return message.SerializeToOstream(&output);
119 google::protobuf::Message *message) {
120 std::fstream input(file_name, std::ios::in | std::ios::binary);
122 AERROR <<
"Failed to open file " << file_name <<
" in binary mode.";
125 if (!message->ParseFromIstream(&input)) {
126 AERROR <<
"Failed to parse file " << file_name <<
" as binary proto.";
133 google::protobuf::Message *message) {
135 AERROR <<
"File [" << file_name <<
"] does not exist! ";
139 static const std::string kBinExt =
".bin";
140 if (std::equal(kBinExt.rbegin(), kBinExt.rend(), file_name.rbegin())) {
150 google::protobuf::Message *message) {
151 using google::protobuf::util::JsonParseOptions;
152 using google::protobuf::util::JsonStringToMessage;
153 std::ifstream ifs(file_name);
154 if (!ifs.is_open()) {
155 AERROR <<
"Failed to open file " << file_name;
161 JsonParseOptions options;
162 options.ignore_unknown_fields =
true;
163 google::protobuf::util::Status dump_status;
164 return (JsonStringToMessage(
Json.dump(), message, options).ok());
167bool GetContent(
const std::string &file_name, std::string *content) {
168 std::ifstream fin(file_name);
173 std::stringstream str_stream;
174 str_stream << fin.rdbuf();
175 *content = str_stream.str();
180 const std::string &relative_path) {
181 if (relative_path.empty()) {
185 if (prefix.empty() || relative_path.front() ==
'/') {
186 return relative_path;
189 if (prefix.back() ==
'/') {
190 return prefix + relative_path;
192 return prefix +
"/" + relative_path;
197 return stat(path.c_str(), &info) == 0;
204 return path.front() ==
'/';
209 return stat(directory_path.c_str(), &info) == 0 && (info.st_mode & S_IFDIR);
212std::vector<std::string>
Glob(
const std::string &pattern) {
214 std::vector<std::string> results;
215 if (glob(pattern.c_str(), GLOB_TILDE,
nullptr, &globs) == 0) {
216 for (
size_t i = 0; i < globs.gl_pathc; ++i) {
217 results.emplace_back(globs.gl_pathv[i]);
224bool CopyFile(
const std::string &from,
const std::string &to) {
225 std::ifstream src(from, std::ios::binary);
227 AWARN <<
"Source path could not be normally opened: " << from;
228 std::string command =
"cp -r " + from +
" " + to;
230 const int ret = std::system(command.c_str());
232 ADEBUG <<
"Copy success, command returns " << ret;
235 ADEBUG <<
"Copy error, command returns " << ret;
240 std::ofstream dst(to, std::ios::binary);
242 AERROR <<
"Target path is not writable: " << to;
251 const std::string illegal_chars =
"\0<>:\"|?*;";
252 for (
char ch : path) {
253 if (illegal_chars.find(ch) != std::string::npos) {
260bool CopyDir(
const std::string &from,
const std::string &to) {
261 DIR *directory = opendir(from.c_str());
262 if (directory ==
nullptr) {
263 AERROR <<
"Cannot open directory " << from;
267 AERROR <<
"invalid path format: " << from <<
" to " << to;
273 struct dirent *entry;
274 while ((entry = readdir(directory)) !=
nullptr) {
276 if (!strcmp(entry->d_name,
".") || !strcmp(entry->d_name,
"..")) {
279 const std::string sub_path_from = from +
"/" + entry->d_name;
280 const std::string sub_path_to = to +
"/" + entry->d_name;
281 if (entry->d_type == DT_DIR) {
282 ret &=
CopyDir(sub_path_from, sub_path_to);
284 ret &=
CopyFile(sub_path_from, sub_path_to);
288 AERROR <<
"Cannot create target directory " << to;
295bool Copy(
const std::string &from,
const std::string &to) {
300 std::string path = directory_path;
301 for (
size_t i = 1; i < directory_path.size(); ++i) {
302 if (directory_path[i] ==
'/') {
307 if (mkdir(path.c_str(), S_IRWXU) != 0) {
308 if (errno != EEXIST) {
319 if (mkdir(path.c_str(), S_IRWXU) != 0) {
320 if (errno != EEXIST) {
329 DIR *directory = opendir(directory_path.c_str());
330 if (directory ==
nullptr) {
331 AERROR <<
"Cannot open directory " << directory_path;
336 while ((file = readdir(directory)) !=
nullptr) {
338 if (!strcmp(file->d_name,
".") || !strcmp(file->d_name,
"..")) {
342 std::string file_path = directory_path +
"/" + file->d_name;
343 if (unlink(file_path.c_str()) < 0) {
344 AERROR <<
"Fail to remove file " << file_path <<
": " << strerror(errno);
353std::vector<std::string>
ListSubPaths(
const std::string &directory_path,
354 const unsigned char d_type) {
355 std::vector<std::string> result;
356 DIR *directory = opendir(directory_path.c_str());
357 if (directory ==
nullptr) {
358 AERROR <<
"Cannot open directory " << directory_path;
362 struct dirent *entry;
363 while ((entry = readdir(directory)) !=
nullptr) {
365 if (entry->d_type == d_type && strcmp(entry->d_name,
".") != 0 &&
366 strcmp(entry->d_name,
"..") != 0) {
367 result.emplace_back(entry->d_name);
375 const unsigned char d_type,
const bool recursive,
376 std::vector<std::string> *result_list) {
377 DIR *directory = opendir(base_path.c_str());
378 size_t result_cnt = 0;
379 if (directory ==
nullptr) {
380 AWARN <<
"cannot open directory " << base_path;
383 struct dirent *entry;
384 for (entry = readdir(directory); entry !=
nullptr;
385 entry = readdir(directory)) {
386 std::string entry_path = base_path +
"/" + std::string(entry->d_name);
388 if (strcmp(entry->d_name,
".") != 0 && strcmp(entry->d_name,
"..") != 0) {
390 if ((patt ==
"" || strcmp(entry->d_name, patt.c_str()) == 0) &&
391 entry->d_type == d_type) {
393 result_list->emplace_back(entry_path);
396 if (recursive && (entry->d_type == DT_DIR)) {
407 std::string::size_type end = path.rfind(
'/');
408 if (end == std::string::npos) {
412 return path.substr(0, end);
415std::string
GetFileName(
const std::string &path,
const bool remove_extension) {
416 std::string::size_type start = path.rfind(
'/');
417 if (start == std::string::npos) {
424 std::string::size_type end = std::string::npos;
425 if (remove_extension) {
426 end = path.rfind(
'.');
428 if (end != std::string::npos && end < start) {
429 end = std::string::npos;
432 const auto len = (end != std::string::npos) ? end - start : end;
433 return path.substr(start, len);
437 std::string *file_path) {
447 bool relative_path_exists =
false;
451 relative_path_exists =
true;
453 if (path.front() ==
'.') {
455 return relative_path_exists;
458 const char *var = std::getenv(env_var.c_str());
459 if (var ==
nullptr) {
460 AWARN <<
"GetFilePathWithEnv: env " << env_var <<
" not found.";
461 return relative_path_exists;
463 std::string env_path = std::string(var);
469 index = env_path.find(
':', begin);
470 auto p = env_path.substr(begin, index - begin);
474 if (p.back() !=
'/') {
484 }
while (index != std::string::npos);
485 return relative_path_exists;
490 return getcwd(tmp,
sizeof(tmp)) ? std::string(tmp) : std::string(
"");
494 struct stat stat_buf;
495 if (lstat(filename.c_str(), &stat_buf) != 0) {
498 if (S_ISDIR(stat_buf.st_mode) != 0) {
500 }
else if (S_ISREG(stat_buf.st_mode) != 0) {
503 AWARN <<
"failed to get type: " << filename;
514 if (!
GetType(filename, &type)) {
518 if (remove(filename.c_str()) != 0) {
519 AERROR <<
"failed to remove file: " << filename;
524 DIR *dir = opendir(filename.c_str());
525 if (dir ==
nullptr) {
526 AWARN <<
"failed to opendir: " << filename;
529 dirent *dir_info =
nullptr;
530 while ((dir_info = readdir(dir)) !=
nullptr) {
531 if (strcmp(dir_info->d_name,
".") == 0 ||
532 strcmp(dir_info->d_name,
"..") == 0) {
535 string temp_file = filename +
"/" + string(dir_info->d_name);
537 if (!
GetType(temp_file, &temp_type)) {
538 AWARN <<
"failed to get file type: " << temp_file;
545 remove(temp_file.c_str());
548 remove(filename.c_str());
553 int ret = mkdir(dir.c_str(), S_IRWXU | S_IRWXG | S_IRWXO);
555 AWARN <<
"failed to create dir. [dir: " << dir
556 <<
"] [err: " << strerror(errno) <<
"]";
bool DeleteFile(const string &filename)
std::vector< std::string > Glob(const std::string &pattern)
Expand path pattern to matched paths.
size_t FindPathByPattern(const std::string &base_path, const std::string &patt, const unsigned char d_type, const bool recursive, std::vector< std::string > *result_list)
Find path with pattern
bool GetProtoFromASCIIFile(const std::string &file_name, google::protobuf::Message *message)
Parses the content of the file specified by the file_name as ascii representation of protobufs,...
bool CopyFile(const std::string &from, const std::string &to)
Copy a file.
bool CreateDir(const string &dir)
bool GetType(const string &filename, FileType *type)
bool PathExists(const std::string &path)
Check if the path exists.
bool GetProtoFromFile(const std::string &file_name, google::protobuf::Message *message)
Parses the content of the file specified by the file_name as a representation of protobufs,...
std::string GetDirName(const std::string &path)
get directory name of path
bool CopyDir(const std::string &from, const std::string &to)
Copy a directory.
std::string GetCurrentPath()
bool SetStringToASCIIFile(const std::string &content, const std::string &file_name)
Sets the content of the file specified by the file_name to be the ascii representation of the input s...
bool GetFilePathWithEnv(const std::string &path, const std::string &env_var, std::string *file_path)
get file path, judgement priority:
bool Copy(const std::string &from, const std::string &to)
Copy a file or directory.
bool SetProtoToBinaryFile(const google::protobuf::Message &message, const std::string &file_name)
Sets the content of the file specified by the file_name to be the binary representation of the input ...
std::string GetFileName(const std::string &path, const bool remove_extension)
bool GetProtoFromJsonFile(const std::string &file_name, google::protobuf::Message *message)
Parses the content of the json file specified by the file_name as ascii representation of protobufs,...
bool SetProtoToASCIIFile(const google::protobuf::Message &message, int file_descriptor)
std::string GetAbsolutePath(const std::string &prefix, const std::string &relative_path)
Get absolute path by concatenating prefix and relative_path.
bool RemoveAllFiles(const std::string &directory_path)
Remove all the files under a specified directory.
bool PathIsAbsolute(const std::string &path)
bool DirectoryExists(const std::string &directory_path)
Check if the directory specified by directory_path exists and is indeed a directory.
bool GetProtoFromBinaryFile(const std::string &file_name, google::protobuf::Message *message)
Parses the content of the file specified by the file_name as binary representation of protobufs,...
bool GetContent(const std::string &file_name, std::string *content)
Get file content as string.
std::vector< std::string > ListSubPaths(const std::string &directory_path, const unsigned char d_type)
List sub-paths.
bool EnsureDirectory(const std::string &directory_path)
Check if a specified directory specified by directory_path exists.
bool IsValidPath(const std::string &path)