| 1 |
#include "filesystem.h" |
| 2 |
|
| 3 |
// POSIX dependencies |
| 4 |
#include <dirent.h> |
| 5 |
#include <sys/stat.h> |
| 6 |
#include <unistd.h> |
| 7 |
#include <string.h> |
| 8 |
#include "atlas/runtime/Exception.h" |
| 9 |
|
| 10 |
namespace atlas::filesystem { |
| 11 |
|
| 12 |
static void create_directory(const char path[]) { |
| 13 |
if (::mkdir(path, 0777) != 0) { |
| 14 |
ATLAS_THROW_EXCEPTION("Could not create directory: " << path); |
| 15 |
} |
| 16 |
} |
| 17 |
|
| 18 |
void create_directory(const std::string& path) { |
| 19 |
return create_directory(path.c_str()); |
| 20 |
} |
| 21 |
|
| 22 |
static bool exists(const char path[]) { |
| 23 |
struct stat info; |
| 24 |
return stat( path, &info ) == 0; |
| 25 |
} |
| 26 |
|
| 27 |
bool exists(const std::string& path) { |
| 28 |
return exists(path.c_str()); |
| 29 |
} |
| 30 |
|
| 31 |
static void remove_all(const char path[]) { |
| 32 |
size_t path_len; |
| 33 |
char *full_path; |
| 34 |
DIR *dir; |
| 35 |
struct stat stat_path, stat_entry; |
| 36 |
struct dirent *entry; |
| 37 |
|
| 38 |
// stat for the path |
| 39 |
::stat(path, &stat_path); |
| 40 |
|
| 41 |
// if path does not exists or is not dir, throw |
| 42 |
if (S_ISDIR(stat_path.st_mode) == 0) { |
| 43 |
ATLAS_THROW_EXCEPTION("Is not a directory: " << path); |
| 44 |
} |
| 45 |
|
| 46 |
// if not possible to read the directory for this user |
| 47 |
if ((dir = opendir(path)) == nullptr) { |
| 48 |
ATLAS_THROW_EXCEPTION("Cannot open directory: " << path); |
| 49 |
} |
| 50 |
|
| 51 |
// the length of the path |
| 52 |
path_len = ::strlen(path); |
| 53 |
|
| 54 |
// iteration through entries in the directory |
| 55 |
while ((entry = readdir(dir)) != nullptr) { |
| 56 |
|
| 57 |
// skip entries "." and ".." |
| 58 |
if (!::strcmp(entry->d_name, ".") || !::strcmp(entry->d_name, "..")) { |
| 59 |
continue; |
| 60 |
} |
| 61 |
|
| 62 |
// determinate a full path of an entry |
| 63 |
full_path = (char*) ::calloc(path_len + 1 + ::strlen(entry->d_name) + 1, sizeof(char)); |
| 64 |
::strcpy(full_path, path); |
| 65 |
::strcat(full_path, "/"); |
| 66 |
::strcat(full_path, entry->d_name); |
| 67 |
|
| 68 |
// stat for the entry |
| 69 |
::stat(full_path, &stat_entry); |
| 70 |
|
| 71 |
// recursively remove a nested directory |
| 72 |
if (S_ISDIR(stat_entry.st_mode) != 0) { |
| 73 |
remove_all(full_path); |
| 74 |
::free(full_path); |
| 75 |
continue; |
| 76 |
} |
| 77 |
|
| 78 |
// remove a file object |
| 79 |
if (::unlink(full_path) != 0) { |
| 80 |
ATLAS_THROW_EXCEPTION("Can't remove a file: " << full_path); |
| 81 |
} |
| 82 |
::free(full_path); |
| 83 |
} |
| 84 |
|
| 85 |
// remove the devastated directory and close the object of it |
| 86 |
if (::rmdir(path) != 0) { |
| 87 |
ATLAS_THROW_EXCEPTION("Can't remove a directory: " << path); |
| 88 |
} |
| 89 |
::closedir(dir); |
| 90 |
} |
| 91 |
|
| 92 |
void remove_all(const std::string& path) { |
| 93 |
remove_all(path.c_str()); |
| 94 |
} |
| 95 |
|
| 96 |
} |