LogIt++
Loading...
Searching...
No Matches
path_utils.hpp
Go to the documentation of this file.
1#ifndef _LOGIT_PATH_UTILS_HPP_INCLUDED
2#define _LOGIT_PATH_UTILS_HPP_INCLUDED
5
6#include <string>
7#if __cplusplus >= 201703L
8#include <filesystem>
9#else
10#include <vector>
11#include <cctype>
12#include <stdexcept>
13#endif
14
15#ifdef _WIN32
16// For Windows systems
17#include <direct.h>
18#include <windows.h>
19#include <locale>
20#include <codecvt>
21#else
22// For POSIX systems
23#include <unistd.h>
24#include <limits.h>
25#include <dirent.h>
26#include <sys/stat.h>
27#include <errno.h>
28#endif
29
30namespace logit {
31# if __cplusplus >= 201703L
32 namespace fs = std::filesystem;
33# endif
34
37 std::string get_exec_dir() {
38# ifdef _WIN32
39 std::vector<wchar_t> buffer(MAX_PATH);
40 HMODULE hModule = GetModuleHandle(NULL);
41
42 // Пробуем получить путь
43 DWORD size = GetModuleFileNameW(hModule, buffer.data(), buffer.size());
44
45 // Если путь слишком длинный, увеличиваем буфер
46 while (size == buffer.size() && GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
47 buffer.resize(buffer.size() * 2); // Увеличиваем буфер в два раза
48 size = GetModuleFileNameW(hModule, buffer.data(), buffer.size());
49 }
50
51 if (size == 0) {
52 throw std::runtime_error("Failed to get executable path.");
53 }
54
55 std::wstring exe_path(buffer.begin(), buffer.begin() + size);
56
57 // Обрезаем путь до директории (удаляем имя файла, оставляем только путь к папке)
58 size_t pos = exe_path.find_last_of(L"\\/");
59 if (pos != std::wstring::npos) {
60 exe_path = exe_path.substr(0, pos);
61 }
62
63 // Преобразуем из std::wstring (UTF-16) в std::string (UTF-8)
64 std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
65 return converter.to_bytes(exe_path);
66# else
67 char result[PATH_MAX];
68 ssize_t count = readlink("/proc/self/exe", result, PATH_MAX);
69
70 if (count == -1) {
71 throw std::runtime_error("Failed to get executable path.");
72 }
73
74 std::string exe_path(result, count);
75
76 // Обрезаем путь до директории (удаляем имя файла, оставляем только путь к папке)
77 size_t pos = exe_path.find_last_of("\\/");
78 if (pos != std::string::npos) {
79 exe_path = exe_path.substr(0, pos);
80 }
81
82 return exe_path;
83# endif
84 }
85
89 std::vector<std::string> get_list_files(const std::string& path) {
90 std::vector<std::string> list_files;
91# ifdef _WIN32
92 // Используем wide-версии функций для корректной работы с русскими символами.
93 std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
94 std::wstring wsearch_path;
95
96 // Если путь пустой, используем текущую директорию.
97 if (path.empty()) {
98 wchar_t buffer[MAX_PATH];
99 GetCurrentDirectoryW(MAX_PATH, buffer);
100 wsearch_path = buffer;
101 } else {
102 wsearch_path = converter.from_bytes(path);
103 }
104
105 // Обеспечиваем наличие завершающего разделителя.
106 if (!wsearch_path.empty()) {
107 wchar_t last_char = wsearch_path.back();
108 if (last_char != L'\\' && last_char != L'/') {
109 wsearch_path.push_back(L'\\');
110 }
111 }
112
113 // Формируем шаблон поиска.
114 std::wstring pattern = wsearch_path + L"*";
115 WIN32_FIND_DATAW fd;
116 HANDLE hFind = FindFirstFileW(pattern.c_str(), &fd);
117 if (hFind != INVALID_HANDLE_VALUE) {
118 do {
119 if (wcscmp(fd.cFileName, L".") == 0 || wcscmp(fd.cFileName, L"..") == 0)
120 continue;
121
122 std::wstring wfull_path = wsearch_path + fd.cFileName;
123
124 if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
125 // Рекурсивно обрабатываем поддиректории.
126 std::vector<std::string> sub_files = get_list_files(converter.to_bytes(wfull_path));
127 list_files.insert(list_files.end(), sub_files.begin(), sub_files.end());
128 } else {
129 // Добавляем найденный файл.
130 list_files.push_back(converter.to_bytes(wfull_path));
131 }
132 } while (FindNextFileW(hFind, &fd));
133 FindClose(hFind);
134 }
135# else
136 // Реализация для POSIX-систем.
137 std::string search_path = path;
138 if (search_path.empty()) {
139 char buffer[PATH_MAX];
140 if (getcwd(buffer, PATH_MAX)) {
141 search_path = buffer;
142 }
143 }
144 // Обеспечиваем наличие завершающего разделителя.
145 if (search_path.back() != '/' && search_path.back() != '\\') {
146 search_path.push_back('/');
147 }
148 DIR* dir = opendir(search_path.c_str());
149 if (dir) {
150 struct dirent* entry;
151 while ((entry = readdir(dir)) != nullptr) {
152 std::string file_name = entry->d_name;
153 if (file_name == "." || file_name == "..")
154 continue;
155 std::string full_path = search_path + file_name;
156 struct stat statbuf;
157 if (stat(full_path.c_str(), &statbuf) == 0) {
158 if (S_ISDIR(statbuf.st_mode)) {
159 std::vector<std::string> sub_files = get_list_files(full_path);
160 list_files.insert(list_files.end(), sub_files.begin(), sub_files.end());
161 } else if (S_ISREG(statbuf.st_mode)) {
162 list_files.push_back(full_path);
163 }
164 }
165 }
166 closedir(dir);
167 }
168# endif
169 return list_files;
170 }
171
175 std::string get_file_name(const std::string& file_path) {
176 size_t pos = file_path.find_last_of("/\\");
177 if (pos == std::string::npos) return file_path;
178 return file_path.substr(pos + 1);
179 }
180
181#if __cplusplus >= 201703L
182
187 inline std::string make_relative(const std::string& file_path, const std::string& base_path) {
188 if (base_path.empty()) return file_path;
189 std::filesystem::path fileP = std::filesystem::u8path(file_path);
190 std::filesystem::path baseP = std::filesystem::u8path(base_path);
191 std::error_code ec; // For exception-safe operation
192 std::filesystem::path relativeP = std::filesystem::relative(fileP, baseP, ec);
193 if (ec) {
194 // If there is an error, return the original file_path
195 return file_path;
196 } else {
197 return relativeP.u8string();
198 }
199 }
200
204 void create_directories(const std::string& path) {
205# ifdef _WIN32
206 // Convert UTF-8 string to wide string for Windows
207 std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
208 std::wstring wide_path = converter.from_bytes(path);
209 std::filesystem::path dir(wide_path);
210# else
211 std::filesystem::path dir(path);
212# endif
213 if (!std::filesystem::exists(dir)) {
214 std::error_code ec;
215 if (!std::filesystem::create_directories(dir, ec)) {
216 throw std::runtime_error("Failed to create directories for path: " + path);
217 }
218 }
219 }
220
221#else
222
226 std::string root;
227 std::vector<std::string> components;
228 };
229
233 PathComponents split_path(const std::string& path) {
234 PathComponents result;
235 size_t i = 0;
236 size_t n = path.size();
237
238 // Handle root paths for Unix and Windows
239 if (n >= 1 && (path[0] == '/' || path[0] == '\\')) {
240 // Unix root "/"
241 result.root = "/";
242 ++i;
243 } else if (n >= 2 && std::isalpha(path[0]) && path[1] == ':') {
244 // Windows drive letter "C:"
245 result.root = path.substr(0, 2);
246 i = 2;
247 if (n >= 3 && (path[2] == '/' || path[2] == '\\')) {
248 // "C:/"
249 ++i;
250 }
251 }
252
253 // Split the path into components
254 while (i < n) {
255 // Skip path separators
256 while (i < n && (path[i] == '/' || path[i] == '\\')) {
257 ++i;
258 }
259 // Find the next separator
260 size_t j = i;
261 while (j < n && path[j] != '/' && path[j] != '\\') {
262 ++j;
263 }
264 if (i < j) {
265 result.components.push_back(path.substr(i, j - i));
266 i = j;
267 }
268 }
269
270 return result;
271 }
272
277 std::string make_relative(const std::string& file_path, const std::string& base_path) {
278 if (base_path.empty()) return file_path;
279 PathComponents file_pc = split_path(file_path);
280 PathComponents base_pc = split_path(base_path);
281
282 // If roots are different, return the original file_path
283 if (file_pc.root != base_pc.root) {
284 return file_path;
285 }
286
287 // Find the common prefix components
288 size_t common_size = 0;
289 while (common_size < file_pc.components.size() &&
290 common_size < base_pc.components.size() &&
291 file_pc.components[common_size] == base_pc.components[common_size]) {
292 ++common_size;
293 }
294
295 // Build the relative path components
296 std::vector<std::string> relative_components;
297
298 // Add ".." for each remaining component in base path
299 for (size_t i = common_size; i < base_pc.components.size(); ++i) {
300 relative_components.push_back("..");
301 }
302
303 // Add the remaining components from the file path
304 for (size_t i = common_size; i < file_pc.components.size(); ++i) {
305 relative_components.push_back(file_pc.components[i]);
306 }
307
308 // Join the components into a relative path string
309 std::string relative_path;
310 if (relative_components.empty()) {
311 relative_path = ".";
312 } else {
313 for (size_t i = 0; i < relative_components.size(); ++i) {
314 if (i > 0) {
315# ifdef _WIN32
316 relative_path += '\\'; // Windows
317# else
318 relative_path += '/';
319# endif
320 }
321 relative_path += relative_components[i];
322 }
323 }
324
325 return relative_path;
326 }
327
331 inline bool is_file(const std::string& path) {
332 size_t dot_pos = path.find_last_of('.');
333 size_t slash_pos = path.find_last_of("/\\");
334 return (dot_pos != std::string::npos && (slash_pos == std::string::npos || dot_pos > slash_pos));
335 }
336
340 void create_directories(const std::string& path) {
341 if (path.empty()) return;
342 PathComponents path_pc = split_path(path);
343 auto &components = path_pc.components;
344 size_t components_size = components.size();
345
346 // Check if the last component is a file
347 if (is_file(path)) {
348 --components_size;
349 }
350
351 // Build the path incrementally and create directories
352 std::string current_path = path_pc.root;
353 for (size_t i = 0; i < components_size; ++i) {
354 if (!current_path.empty() && current_path.back() != '/' && current_path.back() != '\\') {
355 current_path += '/';
356 }
357 current_path += components[i];
358
359 // Skip special components
360 if (components[i] == ".." ||
361 components[i] == "/" ||
362 components[i] == "~/") continue;
363# ifdef _WIN32
364 int ret = _mkdir(utf8_to_ansi(current_path).c_str());
365# else
366 int ret = mkdir(current_path.c_str(), 0755);
367# endif
368 int errnum = errno;
369 if (ret != 0 && errnum != EEXIST) {
370 throw std::runtime_error("Failed to create directory: " + current_path);
371 }
372 }
373 }
374
375#endif // __cplusplus >= 201703L
376
377}; // namespace logit
378
379#endif // _LOGIT_PATH_UTILS_HPP_INCLUDED
The primary namespace for the LogIt++ library.
std::vector< std::string > get_list_files(const std::string &path)
Recursively retrieves a list of all files in a directory.
std::string make_relative(const std::string &file_path, const std::string &base_path)
Computes the relative path from base_path to file_path using C++17 std::filesystem.
bool is_file(const std::string &path)
Checks if a path represents a file (by checking for an extension).
PathComponents split_path(const std::string &path)
Splits a path into its root and components.
std::string utf8_to_ansi(const std::string &utf8)
Converts a UTF-8 string to an ANSI string (Windows-specific).
void create_directories(const std::string &path)
Creates directories recursively for the given path using C++17 std::filesystem.
std::string get_file_name(const std::string &file_path)
Extracts the file name from a full file path.
namespace fs
std::string get_exec_dir()
Retrieves the directory of the executable file.
Structure to hold the root and components of a path.
std::string root
The root part of the path (e.g., "/", "C:")
std::vector< std::string > components
The components of the path.