Line data Source code
1 : !> Test environment configuration module (build_env compatibility layer)
2 : !>
3 : !> This module provides paths for test file I/O that work across different
4 : !> build systems (CMake and fpm). It is a library-level module that can be
5 : !> used by tests in any subdirectory.
6 : !>
7 : !> For fpm builds, absolute paths are determined at runtime via getcwd.
8 : !> For CMake builds, the paths are overridden by the generated test/build_env.f90.in.
9 : !>
10 : !> Usage in tests:
11 : !> ```fortran
12 : !> use build_env, only: source_dir, build_dir
13 : !> character(len=512) :: input_file
14 : !> input_file = source_dir // "/test/inputs/sample.hsd"
15 : !> ```
16 : module build_env
17 : use, intrinsic :: iso_c_binding, only: c_char, c_ptr, c_null_char, c_size_t, c_associated, &
18 : & c_null_ptr
19 : implicit none (type, external)
20 : private
21 :
22 : public :: source_dir, build_dir, build_env_init
23 :
24 : !> Path to the project source directory (set by build_env_init)
25 : character(len=:), allocatable :: source_dir
26 :
27 : !> Path to the build directory for temporary test outputs
28 : character(len=:), allocatable :: build_dir
29 :
30 : !> Buffer size for getcwd
31 : integer, parameter :: PATH_BUF_LEN = 4096
32 :
33 : interface
34 : !> C standard library getcwd (portable, standard Fortran C binding)
35 : type(c_ptr) function c_getcwd(buf, size) bind(c, name="getcwd")
36 : import :: c_ptr, c_char, c_size_t
37 : implicit none (type, external)
38 : character(kind=c_char), intent(inout) :: buf(*)
39 : integer(c_size_t), value :: size
40 : end function c_getcwd
41 : end interface
42 :
43 : contains
44 :
45 : !> Initialize paths using getcwd via C binding (call once from test main program)
46 522 : subroutine build_env_init()
47 : character(kind=c_char) :: c_buf(PATH_BUF_LEN)
48 : type(c_ptr) :: ret
49 : character(len=PATH_BUF_LEN) :: cwd
50 522 : integer :: ii
51 :
52 0 : if (allocated(source_dir)) return
53 :
54 522 : ret = c_getcwd(c_buf, int(PATH_BUF_LEN, c_size_t))
55 522 : if (c_associated(ret)) then
56 522 : cwd = " "
57 27666 : do ii = 1, PATH_BUF_LEN
58 27666 : if (c_buf(ii) == c_null_char) exit
59 27144 : cwd(ii:ii) = c_buf(ii)
60 : end do
61 522 : source_dir = trim(cwd)
62 522 : build_dir = trim(cwd) // "/build"
63 : else
64 0 : source_dir = "."
65 0 : build_dir = "build"
66 : end if
67 522 : end subroutine build_env_init
68 :
69 522 : end module build_env
|