LCOV - code coverage report
Current view: top level - core - filesystem.c (source / functions) Coverage Total Hit
Test: coverage.info Lines: 79.9 % 134 107
Test Date: 2026-10-05 04:47:18 Functions: 88.2 % 17 15

            Line data    Source code
       1              : #include "cfd/core/filesystem.h"
       2              : #include "cfd/core/cfd_status.h"
       3              : #include "cfd/core/logging.h"
       4              : 
       5              : #include <stdio.h>
       6              : #include <stdlib.h>
       7              : #include <string.h>
       8              : #include <time.h>
       9              : 
      10              : #ifdef _WIN32
      11              : #include <direct.h>
      12              : #include <io.h>
      13              : #else
      14              : #include <sys/stat.h>
      15              : #include <unistd.h>
      16              : #endif
      17              : 
      18              : //=============================================================================
      19              : // FILE SYSTEM
      20              : //=============================================================================
      21              : 
      22              : /* Create one directory level; true if it exists afterwards. */
      23          243 : static int make_one_directory(const char* path) {
      24              : #ifdef _WIN32
      25              :     if (_access(path, 0) == 0) {
      26              :         return 1;  // Directory exists
      27              :     }
      28              :     return _mkdir(path) == 0 || _access(path, 0) == 0;
      29              : #else
      30          243 :     struct stat st = {0};
      31          243 :     if (stat(path, &st) == 0) {
      32              :         return 1;  // Directory exists
      33              :     }
      34           20 :     return mkdir(path, 0755) == 0 || stat(path, &st) == 0;
      35              : #endif
      36              : }
      37              : 
      38              : /* Path separator. Only Windows treats a backslash as one; on POSIX it is an
      39              :  * ordinary filename character. */
      40              : static int is_path_sep(char c) {
      41              : #ifdef _WIN32
      42              :     return c == '/' || c == '\\';
      43              : #else
      44              :     return c == '/';
      45              : #endif
      46              : }
      47              : 
      48              : /* Creates every missing level of path, like `mkdir -p`. Creating only the last
      49              :  * level made a nested path such as ../../artifacts/output/<run> fail whenever
      50              :  * an intermediate directory was absent. A level that already exists, or appears
      51              :  * concurrently, is not an error. */
      52           84 : int ensure_directory_exists(const char* path) {
      53           84 :     if (!path || path[0] == '\0') {
      54              :         return 0;
      55              :     }
      56           84 :     char buf[1024];
      57           84 :     size_t len = strlen(path);
      58           84 :     if (len >= sizeof(buf)) {
      59              :         return 0;
      60              :     }
      61           84 :     memcpy(buf, path, len + 1);
      62              : 
      63              :     /* Skip what names a root rather than a directory to create: leading
      64              :      * separators ("/") and, on Windows, a drive ("C:") or a UNC server and
      65              :      * share ("\\server\share"). */
      66           84 :     size_t start = 0;
      67              : #ifdef _WIN32
      68              :     int unc = (len >= 2 && is_path_sep(buf[0]) && is_path_sep(buf[1]));
      69              :     if (len >= 2 && buf[1] == ':') {
      70              :         start = 2;
      71              :     }
      72              : #endif
      73           84 :     while (is_path_sep(buf[start])) {
      74            0 :         start++;
      75              :     }
      76              : #ifdef _WIN32
      77              :     if (unc) {
      78              :         for (int part = 0; part < 2; part++) { /* server, then share */
      79              :             while (buf[start] != '\0' && !is_path_sep(buf[start])) {
      80              :                 start++;
      81              :             }
      82              :             while (is_path_sep(buf[start])) {
      83              :                 start++;
      84              :             }
      85              :         }
      86              :     }
      87              : #endif
      88              : 
      89         1482 :     for (size_t i = start; i < len; i++) {
      90         1398 :         if (is_path_sep(buf[i])) {
      91          159 :             char sep = buf[i];
      92          159 :             buf[i] = '\0';
      93          159 :             int ok = make_one_directory(buf);
      94          159 :             buf[i] = sep;
      95          159 :             if (!ok) {
      96              :                 return 0;
      97              :             }
      98              :         }
      99              :     }
     100           84 :     return make_one_directory(buf);
     101              : }
     102              : 
     103              : //=============================================================================
     104              : // OUTPUT PATH CONFIGURATION
     105              : //=============================================================================
     106              : 
     107              : static char artifacts_base_path[512] = "";
     108              : static cfd_default_path_mode_t default_path_mode = CFD_PATH_CURRENT_DIR;
     109              : 
     110            1 : void cfd_set_output_base_dir(const char* path) {
     111            1 :     if (path && strlen(path) > 0) {
     112            1 :         snprintf(artifacts_base_path, sizeof(artifacts_base_path), "%s", path);
     113              :     } else {
     114            0 :         artifacts_base_path[0] = '\0';  // Reset to default
     115              :     }
     116            1 : }
     117              : 
     118            0 : void cfd_set_default_path_mode(cfd_default_path_mode_t mode) {
     119            0 :     default_path_mode = mode;
     120            0 : }
     121              : 
     122              : 
     123           72 : void cfd_get_artifacts_path(char* buffer, size_t size) {
     124           72 :     if (!buffer || size == 0) {
     125              :         return;
     126              :     }
     127              : 
     128           72 :     if (strlen(artifacts_base_path) > 0) {
     129            1 :         snprintf(buffer, size, "%s", artifacts_base_path);
     130            1 :         return;
     131              :     }
     132              : 
     133              :     // Generate default path based on mode
     134           71 :     switch (default_path_mode) {
     135              :         case CFD_PATH_CURRENT_DIR:
     136           71 :             snprintf(buffer, size, ".");
     137           71 :             break;
     138              : 
     139            0 :         case CFD_PATH_TEMP_DIR:
     140              : #ifdef _WIN32
     141              :         {
     142              :             char* temp_dir = getenv("TEMP");
     143              :             if (!temp_dir) {
     144              :                 temp_dir = getenv("TMP");
     145              :             }
     146              :             if (!temp_dir) {
     147              :                 temp_dir = "C:\\temp";
     148              :             }
     149              :             snprintf(buffer, size, "%s", temp_dir);
     150              :         }
     151              : #else
     152              :         {
     153            0 :             char* temp_dir = getenv("TMPDIR");
     154            0 :             if (!temp_dir)
     155            0 :                 temp_dir = "/tmp";
     156            0 :             snprintf(buffer, size, "%s", temp_dir);
     157              :         }
     158              : #endif
     159            0 :         break;
     160              : 
     161              :         case CFD_PATH_RELATIVE_BUILD:
     162              : #ifdef _WIN32
     163              :             snprintf(buffer, size, "..\\..\\artifacts");
     164              : #else
     165            0 :             snprintf(buffer, size, "../../artifacts");
     166              : #endif
     167            0 :             break;
     168              : 
     169              :         default:
     170            0 :             snprintf(buffer, size, ".");
     171            0 :             break;
     172              :     }
     173           71 :     buffer[size - 1] = '\0';
     174              : }
     175              : 
     176           11 : void cfd_reset_artifacts_path(void) {
     177           11 :     artifacts_base_path[0] = '\0';
     178           11 : }
     179              : 
     180              : //=============================================================================
     181              : // PATH CONSTRUCTION
     182              : //=============================================================================
     183           33 : void make_output_path(char* buffer, size_t buffer_size, const char* filename) {
     184           33 :     char base_path[512];
     185           33 :     cfd_get_artifacts_path(base_path, sizeof(base_path));
     186              : 
     187              : #ifdef _WIN32
     188              :     snprintf(buffer, buffer_size, "%s\\output\\%s", base_path, filename);
     189              : #else
     190           33 :     snprintf(buffer, buffer_size, "%s/output/%s", base_path, filename);
     191              : #endif
     192           33 : }
     193              : 
     194           37 : void make_artifacts_path(char* buffer, size_t buffer_size, const char* subdir) {
     195           37 :     char base_path[512];
     196           37 :     cfd_get_artifacts_path(base_path, sizeof(base_path));
     197              : 
     198           37 :     if (subdir && strlen(subdir) > 0) {
     199              : #ifdef _WIN32
     200              :         snprintf(buffer, buffer_size, "%s\\%s", base_path, subdir);
     201              : #else
     202           34 :         snprintf(buffer, buffer_size, "%s/%s", base_path, subdir);
     203              : #endif
     204              :     } else {
     205            3 :         snprintf(buffer, buffer_size, "%s", base_path);
     206              :     }
     207           37 : }
     208              : 
     209              : //=============================================================================
     210              : // RUN DIRECTORY MANAGEMENT
     211              : //=============================================================================
     212              : 
     213              : static char current_run_directory[512] = {0};  // Keep state, but no direct access
     214              : 
     215              : // Compose "{base_dir}/output/{timestamp_name}" into buffer and create it. A path that does not
     216              : // fit is rejected rather than truncated: buffer is left empty and nothing is created.
     217            9 : static cfd_status_t create_run_directory_internal(char* buffer, size_t buffer_size,
     218              :                                                   const char* base_dir,
     219              :                                                   const char* timestamp_name) {
     220            9 :     if (!buffer || buffer_size == 0) {
     221            0 :         cfd_set_error(CFD_ERROR_INVALID, "Invalid run directory buffer");
     222            0 :         return CFD_ERROR_INVALID;
     223              :     }
     224              : 
     225              :     // Use provided base directory
     226            9 :     const char* root_path = (base_dir && strlen(base_dir) > 0) ? base_dir : ".";
     227              : 
     228            9 :     char output_base[1024];
     229              : #ifdef _WIN32
     230              :     int base_len = snprintf(output_base, sizeof(output_base), "%s\\output", root_path);
     231              :     int path_len = snprintf(buffer, buffer_size, "%s\\output\\%s", root_path, timestamp_name);
     232              : #else
     233            9 :     int base_len = snprintf(output_base, sizeof(output_base), "%s/output", root_path);
     234            9 :     int path_len = snprintf(buffer, buffer_size, "%s/output/%s", root_path, timestamp_name);
     235              : #endif
     236            9 :     if (base_len < 0 || (size_t)base_len >= sizeof(output_base) || path_len < 0 ||
     237            9 :         (size_t)path_len >= buffer_size) {
     238            2 :         buffer[0] = '\0';
     239            2 :         cfd_set_error(CFD_ERROR_LIMIT_EXCEEDED, "Run directory path too long");
     240            2 :         CFD_LOG_ERROR("filesystem", "Run directory path too long under base '%s'", root_path);
     241            2 :         return CFD_ERROR_LIMIT_EXCEEDED;
     242              :     }
     243              : 
     244              :     // Ensure base output directory exists
     245            7 :     ensure_directory_exists(output_base);
     246              : 
     247              :     // Create run-specific directory
     248            7 :     if (!ensure_directory_exists(buffer)) {
     249            0 :         cfd_warning("Failed to create run directory, using base output directory");
     250            0 :         snprintf(buffer, buffer_size, "%s", output_base);
     251              :     }
     252              :     return CFD_SUCCESS;
     253              : }
     254              : 
     255              : // Resolve the base from the artifacts path and cache the result. The path must also fit the
     256              : // cache, so cfd_get_run_directory() never returns a truncated path.
     257            2 : static void create_cached_run_directory(char* buffer, size_t buffer_size,
     258              :                                         const char* timestamp_name) {
     259            2 :     char base_path[512];
     260            2 :     cfd_get_artifacts_path(base_path, sizeof(base_path));
     261              : 
     262            2 :     size_t capacity =
     263              :         buffer_size < sizeof(current_run_directory) ? buffer_size : sizeof(current_run_directory);
     264            2 :     cfd_status_t status =
     265            2 :         create_run_directory_internal(buffer, capacity, base_path, timestamp_name);
     266            2 :     if (status == CFD_SUCCESS) {
     267            1 :         snprintf(current_run_directory, sizeof(current_run_directory), "%s", buffer);
     268              :     }
     269            2 : }
     270              : 
     271            1 : void cfd_create_run_directory(char* buffer, size_t buffer_size) {
     272            1 :     cfd_create_run_directory_with_prefix(buffer, buffer_size, "run");
     273            1 : }
     274              : 
     275            2 : void cfd_create_run_directory_with_prefix(char* buffer, size_t buffer_size, const char* prefix) {
     276            2 :     time_t now = time(NULL);
     277            2 :     struct tm* t = localtime(&now);
     278              : 
     279              :     // Format: prefix_YYYYMMDD_HHMMSS
     280            2 :     char timestamp[64];
     281            2 :     snprintf(timestamp, sizeof(timestamp), "%s_%04d%02d%02d_%02d%02d%02d", prefix,
     282            2 :              t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec);
     283              : 
     284            2 :     create_cached_run_directory(buffer, buffer_size, timestamp);
     285            2 : }
     286              : 
     287            0 : void cfd_create_run_directory_ex(char* buffer, size_t buffer_size, const char* solver_name,
     288              :                                  size_t nx, size_t ny) {
     289            0 :     time_t now = time(NULL);
     290            0 :     struct tm* t = localtime(&now);
     291              : 
     292              :     // Format: solvername_gridsize_YYYYMMDD_HHMMSS
     293            0 :     char timestamp[128];
     294            0 :     snprintf(timestamp, sizeof(timestamp), "%s_%zux%zu_%04d%02d%02d_%02d%02d%02d",
     295            0 :              solver_name ? solver_name : "sim", nx, ny, t->tm_year + 1900, t->tm_mon + 1,
     296              :              t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec);
     297              : 
     298            0 :     create_cached_run_directory(buffer, buffer_size, timestamp);
     299            0 : }
     300              : 
     301            2 : void cfd_create_run_directory_with_base(char* buffer, size_t buffer_size, const char* base_dir,
     302              :                                         const char* prefix) {
     303            2 :     time_t now = time(NULL);
     304            2 :     struct tm* t = localtime(&now);
     305              : 
     306              :     // Format: prefix_YYYYMMDD_HHMMSS
     307            2 :     char timestamp[64];
     308            2 :     snprintf(timestamp, sizeof(timestamp), "%s_%04d%02d%02d_%02d%02d%02d", prefix,
     309            2 :              t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec);
     310              : 
     311            2 :     create_run_directory_internal(buffer, buffer_size, base_dir, timestamp);
     312            2 : }
     313              : 
     314            5 : void cfd_create_run_directory_ex_with_base(char* buffer, size_t buffer_size, const char* base_dir,
     315              :                                            const char* solver_name, size_t nx, size_t ny) {
     316            5 :     time_t now = time(NULL);
     317            5 :     struct tm* t = localtime(&now);
     318              : 
     319              :     // Format: solvername_gridsize_YYYYMMDD_HHMMSS
     320            5 :     char timestamp[128];
     321           10 :     snprintf(timestamp, sizeof(timestamp), "%s_%zux%zu_%04d%02d%02d_%02d%02d%02d",
     322            5 :              solver_name ? solver_name : "sim", nx, ny, t->tm_year + 1900, t->tm_mon + 1,
     323              :              t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec);
     324              : 
     325            5 :     create_run_directory_internal(buffer, buffer_size, base_dir, timestamp);
     326            5 : }
     327              : 
     328            2 : void cfd_get_run_directory(char* buffer, size_t size) {
     329            2 :     if (!buffer || size == 0) {
     330              :         return;
     331              :     }
     332              : 
     333            2 :     if (current_run_directory[0] != '\0') {
     334            1 :         snprintf(buffer, size, "%s", current_run_directory);
     335              :     } else {
     336            1 :         buffer[0] = '\0';
     337              :     }
     338            2 :     buffer[size - 1] = '\0';
     339              : }
     340              : 
     341           10 : void cfd_reset_run_directory(void) {
     342           10 :     current_run_directory[0] = '\0';
     343           10 : }
        

Generated by: LCOV version 2.0-1