Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -423,6 +423,11 @@ jobs:
Get-ChildItem dist/ | Select-Object Name, @{N='MB';E={[math]::Round($_.Length/1MB,2)}}

# ── 8. Smoke test runtime + Algorithm API in a clean install path ──────
# Also exercises the embedded-python path: the bundle's python/ dir
# (pure-python osgeo_utils) is exposed via PYTHONPATH, and the
# `driver gpkg validate` algorithm is run end-to-end against a freshly
# created GeoPackage. This requires a python.exe on PATH (provided by
# the windows-latest runner image).
- name: Smoke test built binaries
shell: Rscript {0}
run: |
Expand All @@ -443,6 +448,22 @@ jobs:
algs <- gdalraster::gdal_global_reg_names()
cat("Algorithm count:", length(algs), "\n")
stopifnot(length(algs) > 0)

# embedded-python algorithm smoke test (gpkg validate)
gdal_abs <- normalizePath("gdal-bundle", winslash = "/")
python_dir <- file.path(gdal_abs, "python")
stopifnot(dir.exists(python_dir))
stopifnot(file.exists(file.path(python_dir, "osgeo_utils", "samples", "validate_gpkg.py")))
Sys.setenv(PYTHONPATH = python_dir)
gpkg <- file.path(tempdir(), "smoke.gpkg")
gdalraster::ogr_ds_create("GPKG", gpkg, layer = "smoke", geom_type = "POINT", srs = "EPSG:4326")
alg <- gdalraster::gdal_alg(cmd = "driver gpkg validate")
alg$setArg("dataset", gpkg)
alg$setArg("full-check", TRUE)
ok <- alg$run()
cat("gpkg validate run:", ok, "\n")
cat("gpkg validate output:", alg$output(), "\n")
stopifnot(isTRUE(ok))
}

# ── 9. Upload gdalraster binary as workflow artifact ───────────────────
Expand Down
22 changes: 21 additions & 1 deletion R/gdal_runtime.R
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,12 @@ install_gdal_runtime <- function(
#'
#' Prepends runtime paths, sets GDAL/PROJ env vars, and preloads GDAL DLL.
#'
#' When the runtime bundle contains a `python/` directory (pure-python
#' `osgeo_utils` package from GDAL's `gdal-utils` distribution), it is
#' prepended to `PYTHONPATH` so GDAL algorithms that embed Python at runtime
#' (e.g. `gdal driver gpkg validate`) can import it. This is session-scoped
#' and does not modify machine or user environment variables.
#'
#' @param gdal_home GDAL home directory.
#' @param preload Whether to preload `libgdal-*.dll`.
#' @param quiet Suppress informational CLI output.
Expand Down Expand Up @@ -197,6 +203,7 @@ activate_gdal_runtime <- function(

gdal_data <- gdal_share_gdal_dir(gdal_home)
proj_data <- gdal_share_proj_dir(gdal_home)
python_dir <- gdal_python_dir(gdal_home)

if (dir.exists(gdal_data)) {
Sys.setenv(GDAL_DATA = gdal_data)
Expand All @@ -206,6 +213,18 @@ activate_gdal_runtime <- function(
Sys.setenv(PROJ_DATA = proj_data)
}

# expose bundled pure-python osgeo_utils to GDAL's embedded python.
# PYTHONPATH is read at Py_Initialize(), which libgdal triggers lazily on
# first use of an embedded-python algorithm, so setting it here is early
# enough. session-scoped only; never persisted to user/machine env.
if (dir.exists(python_dir)) {
py_parts <- strsplit(Sys.getenv("PYTHONPATH", unset = ""), path_sep, fixed = TRUE)[[1]]
py_parts <- py_parts[nzchar(py_parts)]
if (!python_dir %in% py_parts) {
Sys.setenv(PYTHONPATH = paste(c(python_dir, py_parts), collapse = path_sep))
}
}
Comment on lines +220 to +226

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

On Windows, path comparisons can fail due to differences in case sensitivity or slash direction (e.g., C:/path/to/python vs c:\\path\to\python). To ensure robust detection of existing PYTHONPATH entries and avoid duplicate or redundant additions, normalize both python_dir and py_parts (using tolower() and normalizePath()) before performing the %in% check.

  if (dir.exists(python_dir)) {
    py_parts <- strsplit(Sys.getenv("PYTHONPATH", unset = ""), path_sep, fixed = TRUE)[[1]]
    py_parts <- py_parts[nzchar(py_parts)]
    norm_python_dir <- tolower(normalizePath(python_dir, winslash = "/", mustWork = FALSE))
    norm_py_parts <- tolower(normalizePath(py_parts, winslash = "/", mustWork = FALSE))
    if (!norm_python_dir %in% norm_py_parts) {
      Sys.setenv(PYTHONPATH = paste(c(python_dir, py_parts), collapse = path_sep))
    }
  }


if (isTRUE(preload)) {
try(dyn.load(dll_path, local = FALSE, now = TRUE), silent = TRUE)
}
Expand All @@ -220,7 +239,8 @@ activate_gdal_runtime <- function(
gdal_bin = bin_dir,
gdal_dll = dll_path,
gdal_data = if (dir.exists(gdal_data)) gdal_data else NA_character_,
proj_data = if (dir.exists(proj_data)) proj_data else NA_character_
proj_data = if (dir.exists(proj_data)) proj_data else NA_character_,
gdal_python = if (dir.exists(python_dir)) python_dir else NA_character_
)
)
}
Expand Down
6 changes: 6 additions & 0 deletions R/utils_pkg.R
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,12 @@ gdal_share_proj_dir <- function(gdal_home = default_gdal_home()) {
file.path(gdal_home, "share", "proj")
}

#' @keywords internal
#' @noRd
gdal_python_dir <- function(gdal_home = default_gdal_home()) {
file.path(gdal_home, "python")
}

#' @keywords internal
#' @noRd
gdal_dll_candidates <- function(gdal_home = default_gdal_home()) {
Expand Down
5 changes: 5 additions & 0 deletions dev/docs/02-runtime-model.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ GDAL.

- prepends `<gdal_home>/bin` to `PATH`
- sets `GDAL_DATA`, `PROJ_LIB`, and `PROJ_DATA` when available
- prepends `<gdal_home>/python` to `PYTHONPATH` when available (exposes the
bundled pure-python `osgeo_utils` package to GDAL's embedded python, used
by algorithms like `gdal driver gpkg validate`)
- optionally preloads `libgdal-*.dll` with `dyn.load()`

This is the mechanism used today to make runtime loading reliable in typical
Expand All @@ -42,6 +45,8 @@ Expected runtime bundle structure:
- bundled non-Windows transitive dependency DLLs
- `share/gdal`
- `share/proj`
- `python/osgeo_utils` (pure-python `gdal-utils` package, version-locked to
the built GDAL tag; no compiled extensions, so no python ABI coupling)

`tools/collect_dlls.sh` performs dependency collection and closure checks in CI.

Expand Down
7 changes: 7 additions & 0 deletions man/activate_gdal_runtime.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

82 changes: 82 additions & 0 deletions tests/testthat/test-gdal-runtime.R
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,31 @@ create_runtime_zip_fixture <- function(path) {
dir.create(file.path(bundle, "bin"), recursive = TRUE, showWarnings = FALSE)
dir.create(file.path(bundle, "share", "gdal"), recursive = TRUE, showWarnings = FALSE)
dir.create(file.path(bundle, "share", "proj"), recursive = TRUE, showWarnings = FALSE)
dir.create(file.path(bundle, "python", "osgeo_utils", "samples"), recursive = TRUE, showWarnings = FALSE)

file.create(file.path(bundle, "bin", "libgdal-39.dll"))
file.create(file.path(bundle, "share", "gdal", "gdal_datum.csv"))
file.create(file.path(bundle, "share", "proj", "proj.db"))
file.create(file.path(bundle, "python", "osgeo_utils", "__init__.py"))
file.create(file.path(bundle, "python", "osgeo_utils", "samples", "validate_gpkg.py"))

old_wd <- setwd(root)
withr::defer(setwd(old_wd))
utils::zip(zipfile = path, files = "bundle")
path
}

create_gdal_home_fixture <- function(python = TRUE) {
gdal_home <- withr::local_tempdir(.local_envir = parent.frame())
dir.create(file.path(gdal_home, "bin"), recursive = TRUE, showWarnings = FALSE)
file.create(file.path(gdal_home, "bin", "libgdal-39.dll"))
if (isTRUE(python)) {
dir.create(file.path(gdal_home, "python", "osgeo_utils"), recursive = TRUE, showWarnings = FALSE)
file.create(file.path(gdal_home, "python", "osgeo_utils", "__init__.py"))
}
gdal_home
}

testthat::test_that("dll discovery supports dynamic GDAL soname", {
bin_dir <- withr::local_tempdir()
file.create(file.path(bin_dir, "libgdal-39.dll"))
Expand Down Expand Up @@ -65,6 +79,74 @@ testthat::test_that("install_gdal_runtime installs from local zip", {
testthat::expect_true(
dir.exists(file.path(gdal_home, "share", "proj"))
)
testthat::expect_true(
file.exists(file.path(gdal_home, "python", "osgeo_utils", "__init__.py"))
)
})

testthat::test_that("activate_gdal_runtime prepends bundled python dir to PYTHONPATH", {
testthat::skip_if_not(.Platform$OS.type == "windows")

gdal_home <- create_gdal_home_fixture(python = TRUE)
withr::local_envvar(PYTHONPATH = NA)

res <- gdalraster.windows::activate_gdal_runtime(
gdal_home = gdal_home,
preload = FALSE,
quiet = TRUE
)

python_dir <- file.path(normalizePath(gdal_home, winslash = "/"), "python")
testthat::expect_equal(res$gdal_python, python_dir)
testthat::expect_equal(Sys.getenv("PYTHONPATH"), python_dir)
})

testthat::test_that("activate_gdal_runtime preserves existing PYTHONPATH entries", {
testthat::skip_if_not(.Platform$OS.type == "windows")

gdal_home <- create_gdal_home_fixture(python = TRUE)
existing <- "C:/some/other/site-packages"
withr::local_envvar(PYTHONPATH = existing)

gdalraster.windows::activate_gdal_runtime(
gdal_home = gdal_home,
preload = FALSE,
quiet = TRUE
)

python_dir <- file.path(normalizePath(gdal_home, winslash = "/"), "python")
parts <- strsplit(Sys.getenv("PYTHONPATH"), .Platform$path.sep, fixed = TRUE)[[1]]
testthat::expect_equal(parts, c(python_dir, existing))
})

testthat::test_that("activate_gdal_runtime does not duplicate python dir on repeat activation", {
testthat::skip_if_not(.Platform$OS.type == "windows")

gdal_home <- create_gdal_home_fixture(python = TRUE)
withr::local_envvar(PYTHONPATH = NA)

gdalraster.windows::activate_gdal_runtime(gdal_home = gdal_home, preload = FALSE, quiet = TRUE)
gdalraster.windows::activate_gdal_runtime(gdal_home = gdal_home, preload = FALSE, quiet = TRUE)

python_dir <- file.path(normalizePath(gdal_home, winslash = "/"), "python")
parts <- strsplit(Sys.getenv("PYTHONPATH"), .Platform$path.sep, fixed = TRUE)[[1]]
testthat::expect_equal(sum(parts == python_dir), 1L)
})

testthat::test_that("activate_gdal_runtime leaves PYTHONPATH untouched without bundled python dir", {
testthat::skip_if_not(.Platform$OS.type == "windows")

gdal_home <- create_gdal_home_fixture(python = FALSE)
withr::local_envvar(PYTHONPATH = NA)

res <- gdalraster.windows::activate_gdal_runtime(
gdal_home = gdal_home,
preload = FALSE,
quiet = TRUE
)

testthat::expect_true(is.na(res$gdal_python))
testthat::expect_equal(Sys.getenv("PYTHONPATH"), "")
})

testthat::test_that("install_gdal_runtime uses fallback zip when release lookup fails", {
Expand Down
17 changes: 17 additions & 0 deletions tools/build_gdal.sh
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,23 @@ echo ""
echo ">>> cmake install → ${INSTALL_DIR}"
cmake --install build

# ── Stage pure-python GDAL utilities (osgeo_utils) ────────────────────────────
# GDAL algorithms that embed Python at runtime (e.g. `gdal driver gpkg
# validate`) import the osgeo_utils package. It is pure python (no compiled
# extensions), lives in the GDAL source tree, and is version-locked to the
# tag we just built. Staging it under <prefix>/python lets the R runtime
# expose it to the embedded interpreter via PYTHONPATH.
echo ""
echo ">>> Staging osgeo_utils (gdal-utils) → ${INSTALL_DIR}/python"
mkdir -p "${INSTALL_DIR}/python"
cp -r "${SRC_DIR}/swig/python/gdal-utils/osgeo_utils" "${INSTALL_DIR}/python/"
Comment on lines +105 to +106

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

If a previous build has already staged osgeo_utils in ${INSTALL_DIR}/python/osgeo_utils, running cp -r can merge new files with old/stale files from previous builds. To ensure a clean and reliable build, remove any existing osgeo_utils directory before copying.

Suggested change
mkdir -p "${INSTALL_DIR}/python"
cp -r "${SRC_DIR}/swig/python/gdal-utils/osgeo_utils" "${INSTALL_DIR}/python/"
mkdir -p "${INSTALL_DIR}/python"
rm -rf "${INSTALL_DIR}/python/osgeo_utils"
cp -r "${SRC_DIR}/swig/python/gdal-utils/osgeo_utils" "${INSTALL_DIR}/python/"

PY_COUNT=$(find "${INSTALL_DIR}/python/osgeo_utils" -name '*.py' | wc -l)
echo " osgeo_utils python files staged: ${PY_COUNT}"
if [[ ! -f "${INSTALL_DIR}/python/osgeo_utils/samples/validate_gpkg.py" ]]; then
echo "FATAL: osgeo_utils/samples/validate_gpkg.py missing after staging"
exit 1
fi

echo ""
echo ">>> Build complete."
echo " DLL: ${INSTALL_DIR}/bin/libgdal-39.dll"
Expand Down
12 changes: 12 additions & 0 deletions tools/collect_dlls.sh
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
# include/ — public headers (for compiling against the bundle)
# lib/ — import libraries (.dll.a) (for linking against the bundle)
# share/ — gdal/proj runtime data files
# python/ — pure-python osgeo_utils package for embedded-python algorithms
#
# The goal is that BUNDLE_DIR/bin/*.dll should load with zero external deps
# beyond standard Windows system DLLs (kernel32, msvcrt, ucrtbase, etc.)
Expand Down Expand Up @@ -43,6 +44,16 @@ if [[ -d "${INSTALL_DIR}/share" ]]; then
cp -r "${INSTALL_DIR}/share/." "${BUNDLE_DIR}/share/"
fi

# Pure-python GDAL utilities staged by build_gdal.sh. Required by GDAL
# algorithms that embed Python at runtime (e.g. `gdal driver gpkg validate`).
if [[ -d "${INSTALL_DIR}/python" ]]; then
echo ""
echo ">>> Copying python utilities (osgeo_utils)"
mkdir -p "${BUNDLE_DIR}/python"
cp -r "${INSTALL_DIR}/python/." "${BUNDLE_DIR}/python/"
Comment on lines +52 to +53

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

To prevent stale files from previous bundling attempts from persisting in the final bundle, it is safer to remove the existing ${BUNDLE_DIR}/python directory before recreating it and copying the new files.

Suggested change
mkdir -p "${BUNDLE_DIR}/python"
cp -r "${INSTALL_DIR}/python/." "${BUNDLE_DIR}/python/"
rm -rf "${BUNDLE_DIR}/python"
mkdir -p "${BUNDLE_DIR}/python"
cp -r "${INSTALL_DIR}/python/." "${BUNDLE_DIR}/python/"

echo " python files: $(find "${BUNDLE_DIR}/python" -name '*.py' | wc -l)"
fi

# ── Copy primary DLLs from install prefix ────────────────────────────────────
echo ""
echo ">>> Copying primary DLLs from install prefix"
Expand Down Expand Up @@ -209,6 +220,7 @@ ls -lh "${BUNDLE_DIR}/bin/"*.dll | awk '{printf " %-50s %s\n", $NF, $5}'
echo ""
echo "Headers (count): $(find "${BUNDLE_DIR}/include" -name '*.h' | wc -l)"
echo "Import libs: $(ls "${BUNDLE_DIR}/lib/"*.dll.a 2>/dev/null | wc -l)"
echo "Python utils: $(find "${BUNDLE_DIR}/python" -name '*.py' 2>/dev/null | wc -l) files"
echo ""
TOTAL=$(du -sh "${BUNDLE_DIR}" | cut -f1)
echo "Total bundle size: ${TOTAL}"
Loading