|
14 | 14 | #include <cstdint> |
15 | 15 | #include <cstdlib> |
16 | 16 | #include <limits> |
| 17 | +#include <regex> |
17 | 18 | #include <string> |
18 | 19 | #include <vector> |
19 | 20 |
|
20 | 21 | #ifdef _MSC_VER |
21 | 22 | #define NOMINMAX |
22 | 23 | #endif |
23 | 24 |
|
| 25 | +// Include appropriate headers based on the operating system |
| 26 | +#ifdef _WIN32 |
| 27 | +#include <direct.h> |
| 28 | +#define GetCurrentDir _getcwd |
| 29 | +#else |
| 30 | +#include <unistd.h> |
| 31 | +#define GetCurrentDir getcwd |
| 32 | +#endif |
| 33 | + |
| 34 | +std::string get_current_dir() |
| 35 | +{ |
| 36 | + char buff[FILENAME_MAX]; // FILENAME_MAX is a platform-specific macro for buffer size |
| 37 | + if (GetCurrentDir(buff, FILENAME_MAX) != NULL) |
| 38 | + { |
| 39 | + return std::string(buff); |
| 40 | + } |
| 41 | + else |
| 42 | + { |
| 43 | + // Handle error (e.g., buffer too small) |
| 44 | + return std::string(""); |
| 45 | + } |
| 46 | +} |
| 47 | + |
24 | 48 | // Helper function to cleanup test files/directories |
25 | 49 | inline void CleanupTestFiles(const std::string &path) |
26 | 50 | { |
| 51 | + // CWD is the build_dir, we will only remove child dirs of the build_dir |
| 52 | + if (path.find(get_current_dir()) == std::string::npos) |
| 53 | + { |
| 54 | + return; |
| 55 | + } |
| 56 | + |
| 57 | + // Allows: alphanumeric, spaces, hyphens, underscores, periods, forward/backslashes |
| 58 | + std::regex valid_chars("[^a-zA-Z0-9 ._/\\\\-:]"); |
| 59 | + std::string safe_path = std::regex_replace(path, valid_chars, ""); |
| 60 | + |
27 | 61 | #ifdef _WIN32 |
28 | 62 | // Windows: use rmdir for directories, del for files |
29 | 63 | // Try rmdir first (for .bp directories), fall back to del (for files) |
30 | | - std::string cmd = "rmdir /s /q \"" + path + "\" 2>nul || del /q \"" + path + "\" 2>nul"; |
| 64 | + std::string cmd = |
| 65 | + "rmdir /s /q \"" + safe_path + "\" 2>nul || del /q \"" + safe_path + "\" 2>nul"; |
31 | 66 | #else |
32 | 67 | // Unix/Linux/macOS: use rm -rf |
33 | | - std::string cmd = "rm -rf " + path; |
| 68 | + std::string cmd = "rm -rf " + safe_path; |
34 | 69 | #endif |
35 | 70 | int rc = std::system(cmd.c_str()); |
36 | 71 |
|
|
0 commit comments