diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 82d685d..0a7b709 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -4,7 +4,7 @@ # # Scope: this workflow's only responsibility is producing the GDAL runtime # bundle. Building gdalraster against it is package functionality -# (gdalraster.windows::install_gdalraster() with scoped Makevars via withr) +# (gdalraster.windows::gdal_setup() / gdal_build_gdalraster() with scoped Makevars) # and is exercised by the package's own tests, not by CI here. # # Triggers: @@ -23,10 +23,10 @@ # # Cache strategy: # MSYS2 packages : handled automatically by msys2/setup-msys2@v2 (cache: true) -# GDAL build : actions/cache@v4 keyed on GDAL version + runner OS + -# build-script hash. A re-dispatch with an unchanged version -# and scripts restores the bundle and republishes in minutes -# instead of rebuilding for ~25-40 min. +# Arrow build : actions/cache@v4 keyed on Arrow version + script hash. +# GDAL build : actions/cache@v4 keyed on GDAL/Arrow versions + runner OS +# + build-script hashes. A re-dispatch with unchanged inputs +# restores the bundle instead of rebuilding both projects. # ============================================================================ name: Build GDAL (Windows) @@ -39,7 +39,7 @@ on: required: true # current bundle baseline — keep in sync with env.GDAL_VERSION below # and the "Latest GDAL runtime release" line in README.md - default: 'v3.13.1' + default: 'v3.13.2' force_rebuild_gdal: description: 'Force full GDAL rebuild, ignoring cache' required: false @@ -69,7 +69,8 @@ permissions: # Centralise defaults for manual runs. # keep the fallback in sync with the gdal_version input default above env: - GDAL_VERSION: ${{ github.event.inputs.gdal_version || 'v3.13.1' }} + GDAL_VERSION: ${{ github.event.inputs.gdal_version || 'v3.13.2' }} + ARROW_VERSION: '25.0.0' # ───────────────────────────────────────────────────────────────────────────── # JOB 0 — Scheduled upstream release check (schedule trigger only) @@ -215,6 +216,7 @@ jobs: path-type: minimal install: >- git + make mingw-w64-ucrt-x86_64-toolchain mingw-w64-ucrt-x86_64-cmake mingw-w64-ucrt-x86_64-ninja @@ -228,10 +230,11 @@ jobs: mingw-w64-ucrt-x86_64-sqlite3 mingw-w64-ucrt-x86_64-curl mingw-w64-ucrt-x86_64-zlib + mingw-w64-ucrt-x86_64-lz4 + mingw-w64-ucrt-x86_64-zstd mingw-w64-ucrt-x86_64-muparser mingw-w64-ucrt-x86_64-hdf5 mingw-w64-ucrt-x86_64-netcdf - mingw-w64-ucrt-x86_64-arrow mingw-w64-ucrt-x86_64-geos mingw-w64-ucrt-x86_64-libspatialite mingw-w64-ucrt-x86_64-openjpeg2 @@ -255,18 +258,39 @@ jobs: mingw-w64-ucrt-x86_64-ntldd \ | sed -n '1,260p' - # ── 3. GDAL build cache (keyed on version + script hash) ───────────── - # This lets the R package job re-run without rebuilding GDAL. - # Key includes a hash of the build script so any script change - # invalidates the cache and triggers a fresh build. + # ── 3. GDAL and static Arrow build caches ──────────────────────────── - name: Restore GDAL build cache id: gdal-cache-restore uses: actions/cache/restore@v4 with: path: gdal-bundle - key: gdal-bundle-${{ steps.names.outputs.gdal_ver }}-${{ runner.os }}-${{ hashFiles('tools/build_gdal.sh', 'tools/collect_dlls.sh') }} + key: gdal-bundle-${{ steps.names.outputs.gdal_ver }}-arrow-${{ env.ARROW_VERSION }}-${{ runner.os }}-${{ hashFiles('tools/build_arrow.sh', 'tools/build_gdal.sh', 'tools/collect_dlls.sh', 'tools/patches/gdal-static-target-cycles.patch') }} + + - name: Restore static Arrow build cache + id: arrow-cache-restore + if: steps.gdal-cache-restore.outputs.cache-hit != 'true' || github.event.inputs.force_rebuild_gdal == 'true' + uses: actions/cache/restore@v4 + with: + path: arrow-install + key: arrow-static-${{ env.ARROW_VERSION }}-${{ runner.os }}-${{ hashFiles('tools/build_arrow.sh') }} + + # ── 4. Build static Arrow and GDAL from source ──────────────────────── + - name: Build static Apache Arrow + id: build-arrow + if: (steps.gdal-cache-restore.outputs.cache-hit != 'true' || github.event.inputs.force_rebuild_gdal == 'true') && steps.arrow-cache-restore.outputs.cache-hit != 'true' + shell: msys2 {0} + env: + ARROW_VER: ${{ env.ARROW_VERSION }} + ARROW_INSTALL_DIR: ${{ github.workspace }}/arrow-install + run: bash tools/build_arrow.sh + + - name: Save static Arrow build cache + if: steps.build-arrow.outcome == 'success' + uses: actions/cache/save@v4 + with: + path: arrow-install + key: arrow-static-${{ env.ARROW_VERSION }}-${{ runner.os }}-${{ hashFiles('tools/build_arrow.sh') }} - # ── 4. Build GDAL from source (skipped on cache hit) ───────────────── - name: Build GDAL from source id: build-gdal if: steps.gdal-cache-restore.outputs.cache-hit != 'true' || github.event.inputs.force_rebuild_gdal == 'true' @@ -275,6 +299,7 @@ jobs: GDAL_VER: ${{ steps.names.outputs.gdal_ver }} BUNDLE_DIR: ${{ github.workspace }}/gdal-bundle INSTALL_DIR: ${{ github.workspace }}/gdal-install + ARROW_INSTALL_DIR: ${{ github.workspace }}/arrow-install run: bash tools/build_gdal.sh # ── 5. Collect DLLs into self-contained bundle (skipped on cache hit) ─ @@ -284,6 +309,8 @@ jobs: env: BUNDLE_DIR: ${{ github.workspace }}/gdal-bundle INSTALL_DIR: ${{ github.workspace }}/gdal-install + GDAL_VER: ${{ steps.names.outputs.gdal_ver }} + RELEASE_TAG: ${{ steps.names.outputs.release_tag }} run: bash tools/collect_dlls.sh # ── 6. Save GDAL bundle to cache (only when freshly built) ─────────── @@ -292,7 +319,7 @@ jobs: uses: actions/cache/save@v4 with: path: gdal-bundle - key: gdal-bundle-${{ steps.names.outputs.gdal_ver }}-${{ runner.os }}-${{ hashFiles('tools/build_gdal.sh', 'tools/collect_dlls.sh') }} + key: gdal-bundle-${{ steps.names.outputs.gdal_ver }}-arrow-${{ env.ARROW_VERSION }}-${{ runner.os }}-${{ hashFiles('tools/build_arrow.sh', 'tools/build_gdal.sh', 'tools/collect_dlls.sh', 'tools/patches/gdal-static-target-cycles.patch') }} # ── 7. Verify bundle integrity ──────────────────────────────────────── # Asserts all bundle contract pieces consumed by gdalraster.windows: @@ -363,6 +390,17 @@ jobs: } Write-Host "✓ All $((Get-ChildItem "$bin\*.dll").Count) bundled DLLs load cleanly (no DllMain failures)" + - name: Verify shared Arrow dependency ban + shell: pwsh + run: | + $banned = Get-ChildItem "gdal-bundle\bin\*.dll" | + Where-Object Name -Match '^(libarrow|libparquet|libthrift)' + if ($banned) { + Write-Error ("FATAL: shared Arrow dependency DLLs found:`n " + (($banned.Name) -join "`n ")) + exit 1 + } + Write-Host "✓ No shared Arrow, Parquet, or Thrift DLLs in bundle" + # ── 8. Upload bundle as workflow artifact (always) ──────────────────── # compression-level: 0 — DLLs are already-compressed PE binaries. # Re-compressing wastes 30-60s and gains <5%. @@ -392,8 +430,61 @@ jobs: $mb = [math]::Round((Get-Item $zip).Length / 1MB, 1) Write-Host "Release asset: ${zip} (${mb} MB)" echo "zip_name=${zip}" >> $env:GITHUB_OUTPUT + echo "zip_path=$((Get-Item $zip).FullName)" >> $env:GITHUB_OUTPUT echo "zip_mb=${mb}" >> $env:GITHUB_OUTPUT + # ── 10. TLS regression gate ─────────────────────────────────────────── + # This must run before release publication. It builds gdalraster against + # the candidate bundle, loads TLS-heavy native modules in a fresh R + # process, and only then performs the process's first GDAL Parquet open. + - uses: r-lib/actions/setup-r@v2 + with: + r-version: 'release' + use-public-rspm: true + + - uses: r-lib/actions/setup-r-dependencies@v2 + with: + extra-packages: >- + any::pak + any::httpuv + any::later + any::gifski + any::nanoparquet + local::. + + - name: Install candidate runtime and build vendored gdalraster + shell: Rscript {0} + env: + BUNDLE_ZIP: ${{ steps.make-zip.outputs.zip_path }} + GDAL_TLS_HOME: ${{ runner.temp }}/gdal-tls-runtime + GDALRASTER_TLS_LIB: ${{ runner.temp }}/gdalraster-tls-lib + GDAL_BUNDLE_TAG: ${{ steps.names.outputs.release_tag }} + run: | + gdalraster.windows::gdal_install_runtime( + tag = Sys.getenv("GDAL_BUNDLE_TAG"), + local_zip = Sys.getenv("BUNDLE_ZIP"), + gdal_home = Sys.getenv("GDAL_TLS_HOME"), + force = TRUE + ) + gdalraster.windows::gdal_build_gdalraster( + gdal_home = Sys.getenv("GDAL_TLS_HOME"), + lib = Sys.getenv("GDALRASTER_TLS_LIB"), + force = TRUE, + enable_python = TRUE + ) + stopifnot(isTRUE(gdalraster.windows::gdal_verify( + lib = Sys.getenv("GDALRASTER_TLS_LIB"), + python = TRUE + ))) + + - name: Test first Parquet open in TLS-noisy process + shell: Rscript --vanilla {0} + env: + GDALRASTER_TLS_LIB: ${{ runner.temp }}/gdalraster-tls-lib + run: | + source("tools/test_arrow_tls.R", echo = TRUE) + + # ── 11. Publish only after every gate passes ─────────────────────────── - name: Publish GDAL bundle to GitHub Release if: startsWith(github.ref, 'refs/tags/') || github.event.inputs.publish_release == 'true' uses: softprops/action-gh-release@v2 @@ -415,8 +506,10 @@ jobs: | `GDAL_HIDE_INTERNAL_SYMBOLS` | `ON` | Cleaner export table | | `--kill-at` | (linker) | Correct stdcall symbol decoration for MinGW DLLs | | Static GCC/stdc++/winpthread | (linker) | No Rtools or MSYS2 required at runtime | + | Static Apache Arrow ${{ env.ARROW_VERSION }} | (linker) | Arrow/Parquet/Thrift folded into libgdal; mimalloc/jemalloc disabled | | `GDAL_ENABLE_DRIVER_PDF` | `OFF` | MSYS2 libpodofo.dll fails DllMain (ERROR_DLL_INIT_FAILED 1114) in any process, making libgdal unloadable; poppler/podofo/pdfium backends all disabled | | Loadability gate | (CI) | Every bundled DLL is LoadLibrary-tested in CI before publishing | + | TLS regression gate | (CI) | First Parquet open succeeds after loading httpuv/later and a Rust cdylib | ### Runtime bundle asset Download: @@ -430,13 +523,15 @@ jobs: ### R package usage (local machine) ```r - gdalraster.windows::install_gdal_runtime( - repo = "${{ github.repository }}", + pak::pak("${{ github.repository }}") + gdalraster.windows::gdal_setup( + user_lib = TRUE, tag = "${{ startsWith(github.ref, 'refs/tags/') && github.ref_name || steps.names.outputs.release_tag }}" ) + library(gdalraster) ``` - # ── 10. Build transparency summary ──────────────────────────────────── + # ── 12. Build transparency summary ──────────────────────────────────── # Rendered on the run's summary page so the outcome (cache vs fresh # build, bundle composition, where the output landed) is visible at a # glance without digging through step logs. diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml index 811a2cb..645a31e 100644 --- a/.github/workflows/e2e.yml +++ b/.github/workflows/e2e.yml @@ -1,28 +1,4 @@ -# ============================================================================= -# e2e.yml — End-to-end verification of the full user workflow on a clean -# Windows machine (#20). -# -# Proves the documented workflow exactly as a user machine would run it: -# 1. install the package (local checkout) -# 2. install_gdal_runtime() — published GDAL runtime bundle -# 3. install_gdalraster() — source build against the bundle -# 4. verify_gdalraster_runtime() — Algorithm API registry is populated -# 5. add_gdal_rprofile_hook() — startup hook, verified in a fresh -# R session via plain library(gdalraster) -# -# This workflow only consumes exported package functionality — build, link, -# and activation logic are never reimplemented in CI (see AGENTS.md -# responsibility split). gdalraster's own R dependencies are installed as -# CRAN binaries so the only from-source compile is gdalraster itself. -# -# Triggers: -# - workflow_dispatch : manually, optionally pinning a runtime release tag -# - schedule : weekly (Mondays 08:00 UTC, after the upstream check) -# - release published : gdal-v* bundle releases, so every new bundle is -# proven against gdalraster automatically -# ============================================================================= - -name: E2E Runtime Verification +name: E2E Self-Contained Verification on: workflow_dispatch: @@ -40,15 +16,14 @@ permissions: read-all jobs: e2e: - name: "E2E: runtime + gdalraster + hook" - # release trigger fires for package releases (v*) too; only bundle - # releases are relevant here + name: "E2E: setup and fresh-session load" if: github.event_name != 'release' || startsWith(github.event.release.tag_name, 'gdal-v') runs-on: windows-latest timeout-minutes: 90 env: GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} RUNTIME_TAG: ${{ github.event_name == 'release' && github.event.release.tag_name || github.event.inputs.runtime_tag || 'latest' }} + steps: - uses: actions/checkout@v6 @@ -57,75 +32,92 @@ jobs: r-version: 'release' use-public-rspm: true - # installs gdalraster.windows (local checkout) plus its dependencies - uses: r-lib/actions/setup-r-dependencies@v2 with: extra-packages: any::pak, local::. - - name: Install GDAL runtime bundle - shell: Rscript {0} - run: | - tag <- Sys.getenv("RUNTIME_TAG", unset = "latest") - if (!nzchar(tag)) tag <- "latest" - gdalraster.windows::install_gdal_runtime(tag = tag) - - - name: Install gdalraster R dependencies (CRAN binaries) + - name: Install gdalraster R dependencies shell: Rscript {0} run: | - src <- file.path(tempdir(), "gdalraster-src.tar.gz") + archive <- file.path(tempdir(), "gdalraster-src.tar.gz") utils::download.file( "https://codeload.github.com/firelab/gdalraster/tar.gz/HEAD", - destfile = src, mode = "wb", quiet = TRUE + archive, + mode = "wb", + quiet = TRUE ) - exdir <- file.path(tempdir(), "gdalraster-src") - utils::untar(src, exdir = exdir) - pkg_dir <- list.dirs(exdir, recursive = FALSE)[[1]] - pak::local_install_deps(pkg_dir) + source_dir <- file.path(tempdir(), "gdalraster-src") + utils::untar(archive, exdir = source_dir) + pak::local_install_deps(list.dirs(source_dir, recursive = FALSE)[[1]]) - - name: Build gdalraster from source against the bundle + - name: Run package setup shell: Rscript {0} run: | - gdalraster.windows::install_gdalraster() + tag <- Sys.getenv("RUNTIME_TAG", unset = "latest") + if (!nzchar(tag)) tag <- "latest" + gdalraster.windows::gdal_setup( + user_lib = TRUE, + tag = tag, + verify = TRUE + ) - - name: Verify algorithm API (explicit load) + - name: Verify plain fresh-session self-containment shell: Rscript {0} + env: + GDAL_DATA: '' + PROJ_DATA: '' + PROJ_LIB: '' + PYTHONPATH: '' + GDALRASTER_WINDOWS_GDAL_HOME: '' run: | - ok <- gdalraster.windows::verify_gdalraster_runtime() - stopifnot(isTRUE(ok)) + library(gdalraster) - - name: Verify algorithm API (startup hook, fresh session) - shell: Rscript {0} - run: | - rprofile <- file.path(getwd(), "e2e-hook.Rprofile") - gdalraster.windows::add_gdal_rprofile_hook(rprofile = rprofile) + algorithms <- gdalraster::gdal_global_reg_names() + stopifnot(length(algorithms) > 0L) - script <- file.path(getwd(), "e2e-hook-check.R") - writeLines( - c( - "library(gdalraster)", - "n <- length(gdalraster::gdal_global_reg_names())", - "cat('algorithm registry entries:', n, '\n')", - "stopifnot(n > 0L)" - ), - con = script - ) + formats <- gdalraster::gdal_formats()$short_name + required <- c("Arrow", "Parquet", "HDF5", "netCDF") + stopifnot(all(vapply( + required, + function(driver) any(grepl(driver, formats, ignore.case = TRUE)), + logical(1) + ))) + stopifnot(isTRUE(gdalraster::has_geos())) + stopifnot(nzchar(gdalraster::srs_to_wkt("EPSG:4326"))) + + cat("GDAL:", gdalraster::gdal_version()[[1]], "\n") + cat("algorithm registry entries:", length(algorithms), "\n") - status <- withr::with_envvar( - c(R_PROFILE_USER = rprofile), - system2(file.path(R.home("bin"), "Rscript.exe"), args = script) + - name: Verify embedded-Python GeoPackage validator + shell: Rscript {0} + env: + PYTHONPATH: '' + run: | + library(gdalraster) + gpkg <- file.path(tempdir(), "verify.gpkg") + gdalraster::ogr_ds_create( + format = "GPKG", + dsn = gpkg, + layer = "points", + geom_type = "Point", + fld_name = "id", + fld_type = "OFTInteger", + return_obj = FALSE ) - stopifnot(identical(status, 0L)) + validator <- gdalraster::gdal_alg(cmd = "driver gpkg validate") + validator$setArg("dataset", gpkg) + validator$setArg("full-check", TRUE) + stopifnot(isTRUE(validator$run())) + validator$output() - name: Write summary if: always() shell: pwsh run: | @" - ## E2E runtime verification + ## E2E self-contained verification - | Item | Value | - |------|-------| - | Runtime tag | ``$env:RUNTIME_TAG`` | - | Trigger | ``${{ github.event_name }}`` | - | Result | ${{ job.status }} | + - Runtime tag: ``$env:RUNTIME_TAG`` + - Trigger: ``${{ github.event_name }}`` + - Result: ${{ job.status }} "@ | Out-File -Append -Encoding utf8 $env:GITHUB_STEP_SUMMARY diff --git a/.github/workflows/edge-cases.yml b/.github/workflows/edge-cases.yml new file mode 100644 index 0000000..02698f9 --- /dev/null +++ b/.github/workflows/edge-cases.yml @@ -0,0 +1,175 @@ +name: Dirty-Machine Edge Cases + +on: + workflow_dispatch: + inputs: + runtime_tag: + description: 'GDAL runtime release tag' + required: false + default: 'latest' + +permissions: read-all + +jobs: + scenarios: + name: "Edge: ${{ matrix.scenario }}" + runs-on: windows-latest + timeout-minutes: 100 + strategy: + fail-fast: false + matrix: + scenario: + - adversarial-path + - legacy-profile + - self-lock-overwrite + - locked-package + - foreign-gdalraster + - no-python + env: + GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} + RUNTIME_TAG: ${{ github.event.inputs.runtime_tag || 'latest' }} + SCENARIO: ${{ matrix.scenario }} + + steps: + - uses: actions/checkout@v6 + + - uses: r-lib/actions/setup-r@v2 + with: + r-version: 'release' + use-public-rspm: true + + - uses: r-lib/actions/setup-r-dependencies@v2 + with: + extra-packages: any::pak, local::., any::gdalraster + + - name: Install source-build dependencies + shell: Rscript {0} + run: | + archive <- file.path(tempdir(), "gdalraster-src.tar.gz") + utils::download.file( + "https://codeload.github.com/firelab/gdalraster/tar.gz/HEAD", + archive, + mode = "wb", + quiet = TRUE + ) + source_dir <- file.path(tempdir(), "gdalraster-src") + utils::untar(archive, exdir = source_dir) + pak::local_install_deps(list.dirs(source_dir, recursive = FALSE)[[1]]) + + - name: Set up vendored package + shell: Rscript {0} + run: | + tag <- Sys.getenv("RUNTIME_TAG", unset = "latest") + scenario <- Sys.getenv("SCENARIO") + gdalraster.windows::gdal_setup( + user_lib = scenario != "foreign-gdalraster", + tag = tag, + verify = scenario != "foreign-gdalraster" + ) + + - name: Construct adversarial PATH + if: matrix.scenario == 'adversarial-path' + shell: pwsh + run: | + $root = Join-Path $env:RUNNER_TEMP "older-gdal" + New-Item -ItemType Directory -Force -Path $root | Out-Null + gh release download gdal-v3.13.1 ` + --repo jimbrig/gdalraster.windows ` + --pattern "*.zip" ` + --dir $root + $zip = Get-ChildItem $root -Filter "*.zip" | Select-Object -First 1 + Expand-Archive -Path $zip.FullName -DestinationPath $root -Force + $dll = Get-ChildItem $root -Recurse -Filter "libgdal-*.dll" | + Select-Object -First 1 + "PATH=$($dll.DirectoryName);$env:PATH" | Out-File -Append -Encoding utf8 $env:GITHUB_ENV + + - name: Assert scenario behavior + shell: Rscript {0} + run: | + scenario <- Sys.getenv("SCENARIO") + + if (scenario == "adversarial-path") { + library(gdalraster) + manifest <- read.dcf(file.path( + find.package("gdalraster"), + "gdalraster.windows-build.dcf" + )) + version <- gdalraster::gdal_version()[[1]] + stopifnot(grepl(manifest[1, "GDAL-Version"], version, fixed = TRUE)) + } + + if (scenario == "legacy-profile") { + writeLines( + "# >>> gdalraster.windows hook >>>\nensure_gdal_runtime()", + path.expand("~/.Rprofile") + ) + state <- gdalraster.windows::gdal_sitrep( + user_lib = TRUE, + network = FALSE, + quiet = TRUE + ) + stopifnot(isTRUE(state$legacy_hook)) + library(gdalraster) + stopifnot(length(gdalraster::gdal_global_reg_names()) > 0L) + } + + if (scenario == "self-lock-overwrite") { + home <- gdalraster.windows::gdal_home() + dyn.load( + gdalraster.windows:::gdal_dll_path(home), + local = FALSE, + now = TRUE + ) + httr2::request("https://api.github.com") |> + httr2::req_perform() + gdalraster.windows::gdal_install_runtime( + tag = Sys.getenv("RUNTIME_TAG", unset = "latest"), + force = TRUE + ) + stopifnot(file.exists(file.path(home, "MANIFEST.dcf"))) + } + + if (scenario == "locked-package") { + package_dir <- find.package("gdalraster") + dll <- list.files( + file.path(package_dir, "libs", "x64"), + pattern = "^gdalraster\\.dll$", + full.names = TRUE + )[[1]] + connection <- file(dll, open = "rb") + on.exit(close(connection), add = TRUE) + staged <- file.path(tempdir(), "staged", "gdalraster") + dir.create(staged, recursive = TRUE) + writeLines("new", file.path(staged, "marker")) + error <- tryCatch( + gdalraster.windows:::replace_package_tree(staged, package_dir), + error = identity + ) + stopifnot(inherits(error, "error"), dir.exists(package_dir)) + } + + if (scenario == "foreign-gdalraster") { + state <- gdalraster.windows::gdal_sitrep( + network = FALSE, + quiet = TRUE + ) + stopifnot( + isTRUE(state$gdalraster_installed), + isTRUE(state$foreign_gdalraster) + ) + } + + if (scenario == "no-python") { + gdalraster.windows:::remove_managed_python_pth() + result <- gdalraster.windows::gdal_enable_python( + lib = .libPaths()[[1]], + python = "Z:/missing/python.exe", + quiet = TRUE + ) + stopifnot(is.null(result)) + stopifnot(gdalraster.windows::gdal_verify( + user_lib = TRUE, + python = FALSE, + quiet = TRUE + )) + } diff --git a/AGENTS.md b/AGENTS.md index e7adf39..2695ea8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,93 +2,83 @@ ## primary outcome -Provide a reliable Windows workflow for using `gdalraster` against a -self-contained GDAL runtime built in CI. +Provide a reliable Windows workflow for building a self-contained +`gdalraster` package against the GDAL runtime produced by this repository. Primary user flow: ```r pak::pak("jimbrig/gdalraster.windows") -gdalraster.windows::install_gdal_runtime() -gdalraster.windows::install_gdalraster() -gdalraster.windows::load_gdalraster() -gdalraster::gdal_global_reg_names() -``` - -Auto-bootstrap flow (when runtime and source-built `gdalraster` are already -installed): +gdalraster.windows::gdal_setup(user_lib = TRUE) -```r -library(gdalraster.windows) +# every later session library(gdalraster) gdalraster::gdal_global_reg_names() ``` -Also support explicit runtime activation: - -```r -gdalraster.windows::load_gdal_dll() -library(gdalraster) -gdalraster::gdal_global_reg_names() -``` +The non-destructive setup default uses an isolated package-managed library. +Users opt into replacement in `.libPaths()[1]` with `user_lib = TRUE`. ## required system behavior -1. Build modern GDAL (currently 3.13+) from source in Windows CI using MSYS2 UCRT64 / Rtools45-compatible MinGW toolchain. -2. Build with required features for this project, including `muparser`, and keep runtime self-contained. -3. Produce a standalone GDAL runtime bundle archive with: - - a top-level GDAL runtime DLL (`libgdal-*.dll`) - - all required non-Windows dependent DLLs - - required runtime data directories (`share/gdal`, `share/proj`) - - pure-python GDAL utilities (`python/osgeo_utils`) for embedded-python - algorithms (e.g. `gdal driver gpkg validate`) -4. Build `gdalraster` from source against that bundled GDAL runtime. -5. Ensure runtime loading is configured so `gdalraster` resolves bundled DLL - dependencies at runtime (without relying on a matching user-installed - Rtools environment), and so GDAL's embedded python can import bundled - `osgeo_utils` (session-scoped `PYTHONPATH`). -6. Verify success with `gdalraster::gdal_global_reg_names()` returning non-empty output and the `driver gpkg validate` algorithm running end-to-end. -7. Keep installs non-destructive by default: - - runtime installs under package-managed user data paths - - source builds target an isolated library path unless explicitly overridden +1. Build modern GDAL from source in Windows CI using the MSYS2 UCRT64 / + Rtools-compatible MinGW toolchain. +2. Build required features, including `muparser`, and keep the runtime + self-contained. +3. Publish a standalone GDAL SDK bundle containing: + - a top-level GDAL runtime DLL; + - all required non-Windows dependency DLLs; + - headers and import libraries; + - `share/gdal` and `share/proj`; and + - `python/osgeo_utils`. +4. Install and stamp the SDK idempotently. +5. Build `gdalraster` from source against the SDK with scoped Makevars. +6. Vendor the DLL closure, data, and Python utilities into the installed + `gdalraster` package. +7. Use a managed system-CPython `.pth` for embedded-Python algorithms; never + persist or export `PYTHONPATH`. +8. Verify in fresh processes that the Algorithm API, required drivers, first + Parquet open, CRS support, and GeoPackage validator work. +9. Keep installs non-destructive by default. ## responsibility split -- The build workflow's only responsibility is the GDAL runtime bundle: build, - verify the bundle contract, and publish durable artifacts (workflow artifact - + release asset). A scheduled job in the same workflow checks upstream OSGeo/gdal - releases and opens a tracking issue when a newer GDAL exists (never builds - or publishes on its own). -- Building `gdalraster` against the bundle is package functionality - (`install_gdalraster()` with scoped Makevars via `withr`), exercised on user - machines and by package tests — never reimplemented inside CI. -- The e2e workflow ([`.github/workflows/e2e.yml`](.github/workflows/e2e.yml)) - proves the full user workflow on a clean Windows runner by consuming the - exported package functions (`install_gdal_runtime()`, - `install_gdalraster()`, `verify_gdalraster_runtime()`, - `add_gdal_rprofile_hook()`) exactly as a user machine would; it runs on - dispatch, weekly, and whenever a `gdal-v*` bundle release is published. - -## source of truth - -- CI workflow and scripts are authoritative for build/release behavior: - - [`.github/workflows/build.yml`](.github/workflows/build.yml) - - [`tools/build_gdal.sh`](tools/build_gdal.sh) - - [`tools/collect_dlls.sh`](tools/collect_dlls.sh) - -## R package implementation constraints - -- use modern package-style R with explicit namespacing. -- use `cli` for user-facing messaging and `cli::cli_abort()` for errors. -- use `rlang::caller_env()` and `rlang::caller_arg()` in validators/errors. -- use `withr` for scoped state (`with_makevars`, env vars, lib paths); avoid leaking persistent session/user config. -- default source-install target for `gdalraster` must be non-destructive (isolated library path), not overwrite existing user/global installs unless explicitly requested. -- keep docs implementation-anchored and general; avoid session-specific claims. +- The build workflow and scripts own only the GDAL bundle: + `.github/workflows/build.yml`, `tools/build_gdal.sh`, and + `tools/collect_dlls.sh`. +- The R package owns runtime installation, provenance, source compilation, + vendoring, Python provisioning, setup/update/status/uninstall, and + fresh-process verification. +- `.github/workflows/e2e.yml` consumes exported package functions on a clean + Windows runner and proves plain `library(gdalraster)` in a new session. +- `.github/workflows/edge-cases.yml` constructs adversarial machine states and + checks isolation and failure behavior. + +## package architecture + +The managed GDAL runtime is a build-time SDK. Runtime files are copied into the +installed `gdalraster` package: + +- `libs/x64`: `gdalraster.dll`, `libgdal-*.dll`, and dependencies; +- `gdal` and `proj`: matching runtime data; +- `python`: pure-Python `osgeo_utils`; and +- `gdalraster.windows-build.dcf`: build provenance. + +There is no runtime activation API, auto-bootstrap, `.Rprofile` hook, +`PATH` mutation, DLL preload, or GDAL/PROJ/Python environment export. + +## R implementation constraints + +- Use modern package-style R with explicit namespacing. +- Use `cli` for user-facing messages and `cli::cli_abort()` for errors. +- Use `rlang::caller_env()` and `rlang::caller_arg()` in validators. +- Use `withr` for scoped state. +- Stage complete package replacements before changing an installed package. +- Preserve the isolated library as the default build destination. +- Never add Parquet initialization or session-order workarounds; Arrow/TLS + correctness belongs to the bundle build. ## documentation hierarchy -- canonical user-facing docs: `vignettes/` (published via pkgdown) and - roxygen help pages. Any user-facing behavior change MUST update these. -- `dev/docs/` is non-normative maintainer/agent scratch context; it may lag - the implementation and must never be treated as a source of truth over - vignettes, roxygen, or code. +Canonical user-facing behavior lives in `vignettes/`, roxygen help, and the +README. `dev/docs/` is non-normative scratch context and may lag code. diff --git a/DESCRIPTION b/DESCRIPTION index 9325bdf..791beb9 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,12 +1,13 @@ Package: gdalraster.windows -Title: Windows GDAL Runtime and gdalraster Bootstrap Tools -Version: 0.3.1 +Title: Self-Contained gdalraster Builds for Windows +Version: 0.4.0 Authors@R: person("Jimmy", "Briggs", , "jimmy.briggs@jimbrig.com", role = c("aut", "cre"), comment = c(ORCID = "0000-0002-7489-8787")) -Description: Installs and activates a self-contained GDAL runtime on - Windows and provides helpers to install gdalraster from source against - that GDAL instead of the default Rtools GDAL. +Description: Installs a self-contained GDAL build runtime on Windows and + builds a vendored gdalraster package against it. The resulting package + carries its native dependency closure and runtime data, so it loads in + fresh R sessions without activation hooks or environment changes. License: MIT + file LICENSE URL: https://github.com/jimbrig/gdalraster.windows, https://docs.jimbrig.com/gdalraster.windows/ @@ -32,4 +33,4 @@ Config/testthat/edition: 3 Encoding: UTF-8 Language: en-US Roxygen: list(markdown = TRUE) -RoxygenNote: 8.0.0 +Config/roxygen2/version: 8.1.0 diff --git a/NAMESPACE b/NAMESPACE index 2a77423..815059e 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -1,35 +1,24 @@ # Generated by roxygen2: do not edit by hand -export(activate_gdal_runtime) -export(add_gdal_rprofile_hook) -export(configure_gdal_home) +export(gdal_build_gdalraster) +export(gdal_enable_python) export(gdal_home) -export(gdal_rprofile_snippet) -export(install_gdal_runtime) -export(install_gdalraster) -export(load_gdal_dll) -export(load_gdalraster) -export(verify_gdalraster_runtime) -importFrom(cli,cli_alert_info) -importFrom(cli,cli_alert_warning) -importFrom(cli,cli_inform) +export(gdal_install_runtime) +export(gdal_setup) +export(gdal_sitrep) +export(gdal_uninstall) +export(gdal_update) +export(gdal_verify) importFrom(gitcreds,gitcreds_get) -importFrom(httr2,req_auth_bearer_token) -importFrom(httr2,req_error) -importFrom(httr2,req_perform) -importFrom(httr2,req_user_agent) -importFrom(httr2,request) -importFrom(httr2,resp_body_json) -importFrom(httr2,resp_body_raw) -importFrom(httr2,resp_status) +importFrom(httr2, + req_auth_bearer_token, + req_error, + req_perform, + req_user_agent, + request, + resp_body_json, + resp_status +) importFrom(pkgbuild,has_build_tools) -importFrom(rlang,"%||%") -importFrom(rlang,local_use_cli) -importFrom(rlang,new_environment) -importFrom(rlang,on_load) -importFrom(rlang,run_on_load) importFrom(rlang,try_fetch) -importFrom(stats,setNames) importFrom(utils,packageVersion) -importFrom(withr,with_envvar) -importFrom(withr,with_makevars) diff --git a/NEWS.md b/NEWS.md index 1588d41..fc31320 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,3 +1,62 @@ +# gdalraster.windows 0.4.0 + +## Breaking redesign + +- `gdal_build_gdalraster()` now stages and installs a fully self-contained + `gdalraster` package. GDAL and dependency DLLs are vendored beside + `gdalraster.dll`; matching GDAL/PROJ data and pure-Python `osgeo_utils` are + vendored into the package. +- Added provenance manifests for installed GDAL SDKs and built `gdalraster` + packages. Runtime installation is idempotent, and setup detects stale builds + after a bundle update. +- Added the porcelain API: `gdal_setup()`, `gdal_update()`, `gdal_sitrep()`, + `gdal_verify()`, and `gdal_uninstall()`. +- Added `gdal_enable_python()`, which provisions a managed system-CPython + `.pth` file without setting `PYTHONPATH`. +- Removed `activate_gdal_runtime()`, `load_gdal_dll()`, `load_gdalraster()`, + `configure_gdal_home()`, `gdal_rprofile_snippet()`, + `add_gdal_rprofile_hook()`, `install_gdal_runtime()`, + `install_gdalraster()`, and `verify_gdalraster_runtime()`. There are no old + aliases. +- Removed load-time bootstrap, `PATH` mutation, DLL preloading, GDAL/PROJ + environment exports, and profile-hook machinery. + +## GDAL runtime bundle + +- Baseline runtime is now GDAL **v3.13.2** (`gdal-v3.13.2`). +- Apache Arrow / Parquet / Thrift are built statically and folded into + `libgdal-*.dll`. Shared `libarrow*.dll`, `libparquet*.dll`, and + `libthrift*.dll` are banned from the published closure. Arrow's + mimalloc/jemalloc allocators are disabled. This removes the MinGW + emulated-TLS first-Parquet-open crash class from the import graph (#38). +- Bundle CI gates now include LoadLibrary smoke testing, the shared-Arrow ban, + `gdal_verify()`, and a TLS-noisy first Parquet open (httpuv/later + a Rust + cdylib) before release publication. +- Published bundles embed `MANIFEST.dcf` for provenance-aware installs. + +## Verification and CI + +- `gdal_verify()` runs in fresh processes and checks the Algorithm API, GEOS, + CRS resolution, Arrow/Parquet/HDF5/netCDF registration, a first Parquet open + against a bundled smoke fixture, and the GeoPackage Python validator when + Python is ready. +- The e2e workflow now proves plain `library(gdalraster)` in a separate session. + A dirty-machine scenario workflow covers competing GDALs, legacy hooks, + self-lock overwrite, locked package replacement, foreign installs, and + no-Python operation. +- There is no Parquet initialization workaround in the package. The Arrow/TLS + correction is owned by the GDAL bundle build and is enforced through + first-open verification. + +## Migration + +1. Remove legacy managed blocks from `~/.Rprofile` and personal calls to the + removed activation helpers. +2. Remove persistent GDAL-related `PATH`, `GDAL_DATA`, `PROJ_DATA`, `PROJ_LIB`, + and `PYTHONPATH` workarounds. +3. Run `gdal_setup(user_lib = TRUE)` once for plain + `library(gdalraster)` discovery, or omit `user_lib` for an isolated install. + # gdalraster.windows 0.3.1 ## Package diff --git a/R/aaa.R b/R/aaa.R index 3fa4079..0fd1e5c 100644 --- a/R/aaa.R +++ b/R/aaa.R @@ -47,3 +47,18 @@ #' @noRd #' @keywords internal .gdal_dll_fallback <- "libgdal-39.dll" + +#' Managed embedded-Python path file +#' @noRd +#' @keywords internal +.python_pth_name <- "gdalraster-windows-osgeo-utils.pth" + +#' Marker identifying a path file owned by this package +#' @noRd +#' @keywords internal +.python_pth_marker <- "# managed by gdalraster.windows" + +#' Required GDAL format drivers checked by gdal_verify() +#' @noRd +#' @keywords internal +.required_gdal_drivers <- c("Arrow", "Parquet", "HDF5", "netCDF") diff --git a/R/gdal_build.R b/R/gdal_build.R new file mode 100644 index 0000000..a103d0e --- /dev/null +++ b/R/gdal_build.R @@ -0,0 +1,330 @@ +#' Build a self-contained gdalraster package +#' +#' Compiles `gdalraster` against the managed GDAL SDK, vendors the bundle's +#' DLL dependency closure, GDAL/PROJ data, and pure-Python utilities into the +#' installed package, then records build provenance. +#' +#' @param gdal_home Installed GDAL build runtime. +#' @param lib Destination library. The default is an isolated package-managed +#' library. +#' @param user_lib Install into `.libPaths()[1]`. This is destructive when an +#' existing `gdalraster` is installed there and requires `force = TRUE` in +#' non-interactive sessions. +#' @param source_tarball Optional local `gdalraster` source tarball. +#' @param repo Upstream source repository. +#' @param ref Git reference used for the source archive. +#' @param upgrade Install missing R dependencies before compiling. +#' @param repos CRAN-like repositories used when `upgrade = TRUE`. +#' @param force Replace an existing `gdalraster` package. +#' @param enable_python Provision the managed embedded-Python `.pth` file after +#' installation when possible. +#' +#' @return Invisibly, the destination library. +#' @export +gdal_build_gdalraster <- function( + gdal_home = default_gdal_home(), + lib = NULL, + user_lib = FALSE, + source_tarball = NULL, + repo = .gdalraster_repo, + ref = "HEAD", + upgrade = FALSE, + repos = getOption("repos"), + force = FALSE, + enable_python = TRUE +) { + abort_if_not_windows() + abort_if_no_build_tools() + check_flag(user_lib) + check_flag(upgrade) + check_flag(force) + check_flag(enable_python) + check_optional_string(lib) + check_optional_string(source_tarball) + check_string(repo) + check_string(ref) + + gdal_home <- normalizePath(gdal_home, winslash = "/", mustWork = FALSE) + validate_runtime_contract(gdal_home) + bundle <- installed_bundle_manifest(gdal_home) + if (is.null(bundle)) { + cli::cli_abort( + c( + "The GDAL runtime has no provenance manifest.", + "i" = "Reinstall it with {.fn gdal_install_runtime}." + ), + call = rlang::caller_env() + ) + } + + lib <- resolve_gdalraster_lib(lib = lib, user_lib = user_lib) + package_dir <- file.path(lib, "gdalraster") + if ("gdalraster" %in% loadedNamespaces()) { + cli::cli_abort( + c( + "Cannot replace {.pkg gdalraster} while it is loaded.", + "i" = "Restart R, load only {.pkg gdalraster.windows}, and retry." + ), + call = rlang::caller_env() + ) + } + if (dir.exists(package_dir) && !isTRUE(force)) { + if (rlang::is_interactive()) { + replace <- utils::askYesNo( + paste0("Replace the existing gdalraster package in ", lib, "?"), + default = FALSE + ) + if (!isTRUE(replace)) { + cli::cli_abort("Build cancelled.", call = rlang::caller_env()) + } + } else { + cli::cli_abort( + c( + "{.pkg gdalraster} is already installed at {.path {package_dir}}.", + "i" = "Set {.code force = TRUE} to replace it." + ), + call = rlang::caller_env() + ) + } + } + + tarball <- resolve_gdalraster_source( + source_tarball = source_tarball, + repo = repo, + ref = ref + ) + dir.create(lib, recursive = TRUE, showWarnings = FALSE) + + if (isTRUE(upgrade)) { + install_source_dependencies(tarball, lib = lib, repos = repos) + } + + stage_lib <- tempfile(".gdalraster-stage-", tmpdir = dirname(lib)) + dir.create(stage_lib, recursive = TRUE, showWarnings = FALSE) + withr::defer(unlink(stage_lib, recursive = TRUE, force = TRUE)) + + makevars <- c( + GDAL_HOME = gdal_home, + PKG_CPPFLAGS = paste0("-I\"", file.path(gdal_home, "include"), "\""), + PKG_LIBS = paste0( + "-L\"", file.path(gdal_home, "lib"), + "\" -lgdal -Wl,--allow-multiple-definition" + ) + ) + build_env <- c( + PATH = paste(gdal_bin_dir(gdal_home), Sys.getenv("PATH"), sep = .Platform$path.sep), + GDAL_DATA = gdal_share_gdal_dir(gdal_home), + PROJ_LIB = gdal_share_proj_dir(gdal_home), + PROJ_DATA = gdal_share_proj_dir(gdal_home) + ) + + cli::cli_alert_info("Building {.pkg gdalraster} against {.val {manifest_value(bundle, 'Bundle-Tag')}}.") + rlang::try_fetch( + withr::with_libpaths( + new = c(lib, .libPaths()), + action = "replace", + code = withr::with_makevars( + new = makevars, + assignment = "=", + code = withr::with_envvar( + new = build_env, + code = utils::install.packages( + tarball, + repos = NULL, + type = "source", + lib = stage_lib, + INSTALL_opts = "--no-test-load" + ) + ) + ) + ), + error = function(cnd) { + cli::cli_abort( + "Failed to build {.pkg gdalraster}.", + parent = cnd, + call = rlang::caller_env() + ) + } + ) + + staged_package <- file.path(stage_lib, "gdalraster") + if (!dir.exists(staged_package)) { + cli::cli_abort( + "The source build did not produce an installed {.pkg gdalraster} package.", + call = rlang::caller_env() + ) + } + + vendor_gdalraster(staged_package, gdal_home) + write_manifest( + list( + `Bundle-Tag` = manifest_value(bundle, "Bundle-Tag"), + `GDAL-Version` = manifest_value(bundle, "GDAL-Version"), + `Built-At` = format(Sys.time(), tz = "UTC", usetz = TRUE), + `R-Version` = as.character(getRversion()), + Platform = R.version$platform, + Compiler = R.version$compiler, + `Builder-Version` = pkg_version() + ), + build_manifest_path(staged_package) + ) + + replace_package_tree(staged_package, package_dir) + if (isTRUE(enable_python)) { + gdal_enable_python(lib = lib, quiet = TRUE) + } + + cli::cli_alert_success("Installed self-contained {.pkg gdalraster} at {.path {package_dir}}.") + invisible(lib) +} + +#' @keywords internal +#' @noRd +resolve_gdalraster_lib <- function(lib = NULL, user_lib = FALSE) { + if (isTRUE(user_lib)) { + return(normalizePath(.libPaths()[[1L]], winslash = "/", mustWork = FALSE)) + } + lib <- if (is.null(lib)) default_gdalraster_lib() else lib + normalizePath(lib, winslash = "/", mustWork = FALSE) +} + +#' @keywords internal +#' @noRd +resolve_gdalraster_source <- function(source_tarball, repo, ref) { + if (!is.null(source_tarball)) { + abort_if_missing_file(source_tarball, "source_tarball") + return(normalizePath(source_tarball, winslash = "/", mustWork = TRUE)) + } + + destination <- tempfile("gdalraster-", fileext = ".tar.gz") + request <- httr2::request(paste0("https://codeload.github.com/", repo, "/tar.gz/", ref)) + request <- httr2::req_user_agent(request, paste0(pkg_name(), "/", pkg_version())) + request <- httr2::req_error( + request, + is_error = function(response) httr2::resp_status(response) >= 400L + ) + response <- httr2::req_perform(request) + writeBin(httr2::resp_body_raw(response), destination) + destination +} + +#' @keywords internal +#' @noRd +install_source_dependencies <- function(tarball, lib, repos) { + members <- utils::untar(tarball, list = TRUE) + description <- members[grepl("(^|/)DESCRIPTION$", members)] + if (length(description) < 1L) { + cli::cli_abort("The source archive has no {.file DESCRIPTION} file.") + } + + extract <- tempfile("gdalraster-description-") + dir.create(extract, recursive = TRUE, showWarnings = FALSE) + withr::defer(unlink(extract, recursive = TRUE, force = TRUE)) + utils::untar(tarball, files = description[[1L]], exdir = extract) + dcf <- read.dcf(file.path(extract, description[[1L]])) + fields <- intersect(c("Depends", "Imports", "LinkingTo"), colnames(dcf)) + specifications <- unlist(strsplit( + paste(dcf[1L, fields], collapse = ","), + ",", + fixed = TRUE + )) + packages <- trimws(sub("\\s*\\(.*\\)\\s*$", "", specifications)) + packages <- unique(packages[nzchar(packages) & packages != "R"]) + installed <- rownames(utils::installed.packages()) + missing <- setdiff(packages, installed) + if (length(missing) > 0L) { + utils::install.packages(missing, repos = repos, lib = lib, dependencies = TRUE) + } + invisible(missing) +} + +#' @keywords internal +#' @noRd +validate_runtime_contract <- function(gdal_home) { + required_dirs <- c( + file.path(gdal_home, "bin"), + file.path(gdal_home, "include"), + file.path(gdal_home, "lib"), + file.path(gdal_home, "share", "gdal"), + file.path(gdal_home, "share", "proj"), + file.path(gdal_home, "python", "osgeo_utils") + ) + missing <- required_dirs[!dir.exists(required_dirs)] + if (length(gdal_dll_candidates(gdal_home)) < 1L || length(missing) > 0L) { + cli::cli_abort( + c( + "The GDAL runtime bundle is incomplete.", + "x" = "Missing: {paste(missing, collapse = ', ')}", + "i" = "Reinstall it with {.fn gdal_install_runtime}." + ), + call = rlang::caller_env() + ) + } + invisible(TRUE) +} + +#' @keywords internal +#' @noRd +vendor_gdalraster <- function(package_dir, gdal_home) { + dlls <- list.files( + gdal_bin_dir(gdal_home), + pattern = "\\.dll$", + ignore.case = TRUE, + full.names = TRUE + ) + if (length(dlls) < 1L) { + cli::cli_abort("The runtime bundle contains no DLLs to vendor.") + } + dll_destination <- file.path(package_dir, "libs", "x64") + dir.create(dll_destination, recursive = TRUE, showWarnings = FALSE) + copied <- file.copy(dlls, dll_destination, overwrite = TRUE, copy.mode = TRUE) + if (!all(copied)) { + cli::cli_abort("Failed to vendor the complete GDAL DLL closure.") + } + + trees <- c( + gdal = gdal_share_gdal_dir(gdal_home), + proj = gdal_share_proj_dir(gdal_home), + python = gdal_python_dir(gdal_home) + ) + for (name in names(trees)) { + destination <- file.path(package_dir, name) + unlink(destination, recursive = TRUE, force = TRUE) + dir.create(destination, recursive = TRUE, showWarnings = FALSE) + copy_tree(trees[[name]], destination) + } + invisible(package_dir) +} + +#' @keywords internal +#' @noRd +replace_package_tree <- function(staged_package, package_dir) { + backup <- paste0(package_dir, ".previous-", Sys.getpid()) + unlink(backup, recursive = TRUE, force = TRUE) + + had_existing <- dir.exists(package_dir) + if (had_existing && !isTRUE(suppressWarnings(file.rename(package_dir, backup)))) { + cli::cli_abort( + c( + "Could not replace {.pkg gdalraster}; its package directory is locked.", + "i" = "Close sessions using {.pkg gdalraster} and retry.", + "i" = "The existing package was left unchanged." + ), + call = rlang::caller_env() + ) + } + + installed <- isTRUE(suppressWarnings(file.rename(staged_package, package_dir))) + if (!installed) { + if (had_existing) { + suppressWarnings(file.rename(backup, package_dir)) + } + cli::cli_abort( + "Could not move the staged {.pkg gdalraster} package into {.path {dirname(package_dir)}}.", + call = rlang::caller_env() + ) + } + + unlink(backup, recursive = TRUE, force = TRUE) + invisible(package_dir) +} diff --git a/R/gdal_python.R b/R/gdal_python.R new file mode 100644 index 0000000..2ec14e0 --- /dev/null +++ b/R/gdal_python.R @@ -0,0 +1,157 @@ +#' Enable GDAL embedded-Python utilities +#' +#' Writes a managed `.pth` file into the system CPython `site-packages` +#' directory. The file points to the pure-Python `osgeo_utils` vendored inside +#' the installed `gdalraster` package. This does not modify `PYTHONPATH` and +#' does not affect isolated virtual environments. +#' +#' @param lib Library containing the self-contained `gdalraster` package. +#' @param python Optional path to the CPython executable GDAL embeds. +#' @param site_packages Optional explicit `site-packages` directory. +#' @param quiet Suppress status messages. +#' +#' @return Invisibly, the `.pth` path, or `NULL` when no system CPython can be +#' located. +#' @export +gdal_enable_python <- function( + lib = default_gdalraster_lib(), + python = NULL, + site_packages = NULL, + quiet = FALSE +) { + abort_if_not_windows() + check_string(lib) + check_optional_string(python) + check_optional_string(site_packages) + check_flag(quiet) + + package_python <- file.path( + normalizePath(lib, winslash = "/", mustWork = FALSE), + "gdalraster", + "python" + ) + if (!dir.exists(file.path(package_python, "osgeo_utils"))) { + cli::cli_abort( + c( + "Vendored {.pkg osgeo_utils} was not found at {.path {package_python}}.", + "i" = "Rebuild with {.fn gdal_build_gdalraster}." + ), + call = rlang::caller_env() + ) + } + + if (is.null(site_packages)) { + site_packages <- find_python_site_packages(python) + } + if (is.null(site_packages)) { + if (!isTRUE(quiet)) { + cli::cli_alert_warning( + "No system CPython was found; core {.pkg gdalraster} is ready, but embedded-Python algorithms are not enabled." + ) + } + return(invisible(NULL)) + } + + site_packages <- normalizePath(site_packages, winslash = "/", mustWork = FALSE) + dir.create(site_packages, recursive = TRUE, showWarnings = FALSE) + pth <- file.path(site_packages, .python_pth_name) + writeLines( + c(.python_pth_marker, normalizePath(package_python, winslash = "/", mustWork = TRUE)), + pth, + useBytes = TRUE + ) + if (!isTRUE(quiet)) { + cli::cli_alert_success("Enabled embedded-Python utilities via {.path {pth}}.") + } + invisible(pth) +} + +#' @keywords internal +#' @noRd +find_python_site_packages <- function(python = NULL) { + commands <- if (!is.null(python)) { + list(list(command = python, prefix = character())) + } else { + paths <- Sys.which(c("python", "python3", "py")) + paths <- unique(unname(paths[nzchar(paths)])) + lapply(paths, function(path) { + list( + command = path, + prefix = if (identical(tolower(basename(path)), "py.exe")) "-3" else character() + ) + }) + } + + expression <- paste0( + "import sysconfig; ", + "print(sysconfig.get_paths().get('purelib', ''))" + ) + for (candidate in commands) { + output <- suppressWarnings( + tryCatch( + system2( + candidate$command, + args = c(candidate$prefix, "-c", shQuote(expression)), + stdout = TRUE, + stderr = FALSE + ), + error = function(cnd) character() + ) + ) + output <- trimws(output) + output <- output[nzchar(output)] + if (length(output) > 0L && dir.exists(output[[length(output)]])) { + return(normalizePath(output[[length(output)]], winslash = "/", mustWork = TRUE)) + } + } + NULL +} + +#' @keywords internal +#' @noRd +known_python_site_packages <- function() { + discovered <- find_python_site_packages() + local_app_data <- Sys.getenv("LOCALAPPDATA", unset = "") + patterns <- c( + "C:/Python*/Lib/site-packages", + if (nzchar(local_app_data)) { + file.path(local_app_data, "Programs", "Python", "Python*", "Lib", "site-packages") + } else { + character() + } + ) + unique(c(discovered, unlist(lapply(patterns, Sys.glob), use.names = FALSE))) +} + +#' @keywords internal +#' @noRd +managed_python_pth_files <- function() { + sites <- known_python_site_packages() + paths <- file.path(sites, .python_pth_name) + paths[file.exists(paths)] +} + +#' @keywords internal +#' @noRd +pth_target <- function(path) { + if (!file.exists(path)) { + return(NA_character_) + } + lines <- readLines(path, warn = FALSE) + if (length(lines) < 2L || !identical(lines[[1L]], .python_pth_marker)) { + return(NA_character_) + } + lines[[2L]] +} + +#' @keywords internal +#' @noRd +remove_managed_python_pth <- function() { + paths <- managed_python_pth_files() + for (path in paths) { + if (!is.na(pth_target(path))) { + unlink(path, force = TRUE) + } + } + invisible(paths) +} diff --git a/R/gdal_runtime.R b/R/gdal_runtime.R index 6273083..73cee2f 100644 --- a/R/gdal_runtime.R +++ b/R/gdal_runtime.R @@ -1,798 +1,274 @@ -#' Resolve active GDAL home path +#' Resolve the managed GDAL runtime directory #' -#' Returns the currently configured GDAL runtime home used by this package. +#' Resolution order is the `gdalraster.windows.gdal_home` option, the +#' `GDALRASTER_WINDOWS_GDAL_HOME` environment variable, then the package-managed +#' user data directory. #' -#' Resolution order: -#' 1) `options(gdalraster.windows.gdal_home = "...")` -#' 2) `GDALRASTER_WINDOWS_GDAL_HOME` environment variable -#' 3) package-managed user data directory (`tools::R_user_dir()`) -#' -#' @return A single string path. +#' @return A single path. #' @export gdal_home <- function() { default_gdal_home() } -#' Configure GDAL home for current session -#' -#' Sets GDAL home for this session using either an R option or environment -#' variable. This does not write to user profile files. +#' Install a self-contained GDAL build runtime #' -#' @param path GDAL home directory path. -#' @param mode Either `"option"` or `"env"`. -#' -#' @return Invisibly returns the normalized GDAL home path. -#' @export -configure_gdal_home <- function(path, mode = c("option", "env")) { - abort_if_not_windows() - - mode <- match.arg(mode) - if (!is.character(path) || length(path) != 1L || !nzchar(path)) { - cli::cli_abort("{.arg path} must be a single non-empty string.") - } - - path <- normalizePath(path, winslash = "/", mustWork = FALSE) - - if (identical(mode, "option")) { - options(gdalraster.windows.gdal_home = path) - } else { - Sys.setenv(GDALRASTER_WINDOWS_GDAL_HOME = path) - } - - invisible(path) -} - -#' Install precompiled GDAL runtime +#' Installs a release bundle used to compile [gdal_build_gdalraster()]. The +#' installed runtime is a build-time SDK; packages produced by +#' [gdal_build_gdalraster()] vendor everything needed at run time. #' -#' Installs the GDAL runtime into `gdal_home` from one of: +#' The installer is idempotent. When the requested bundle tag is already +#' recorded in `MANIFEST.dcf`, installation is skipped unless `force = TRUE`. #' -#' - `local_zip` (highest precedence), -#' - GitHub release asset lookup/download, -#' - `fallback_zip` when release lookup/download fails. +#' @param repo GitHub repository that publishes bundle releases. +#' @param tag Bundle release tag or `"latest"`. +#' @param asset_pattern Regular expression selecting a bundle zip asset. +#' @param gdal_home Destination runtime directory. +#' @param force Reinstall an existing runtime. +#' @param local_zip Optional local bundle zip. This takes precedence over a +#' release download. +#' @param fallback_zip Optional local zip used if release resolution or download +#' fails. #' -#' The selected zip must contain a GDAL root with `bin/libgdal-*.dll`. -#' -#' @section Offline / air-gapped installation: -#' On machines without network access, download the release asset manually -#' from , transfer it -#' to the target machine, and install directly: -#' -#' ```r -#' gdalraster.windows::install_gdal_runtime( -#' local_zip = "C:/Downloads/gdal-ucrt64-v3.13.1-windows-x64.zip" -#' ) -#' ``` -#' -#' Note that no fallback zip is shipped with the package (a full runtime -#' bundle is too large to vendor), so the fallback path only applies when you -#' provide a `fallback_zip` yourself. -#' -#' @section Overwriting an installed runtime: -#' With `overwrite = TRUE`, the existing `gdal_home` is deleted before the new -#' runtime is copied in. Runtime DLLs that were preloaded into the current -#' session (the package auto-bootstrap does this at load time when a runtime -#' is present) are unloaded first, but the session usually cannot fully -#' release its own locks anyway: runtime activation prepends `bin` to `PATH`, -#' so DLLs loaded later in the session (the release download itself loads the -#' curl package, which maps the runtime's `zlib1.dll`) resolve dependencies -#' from the runtime directory outside R's control. Mapped DLLs cannot be -#' deleted but can be renamed, so such leftovers are moved into a stale -#' sibling directory -#' (`.stale--`) and the install proceeds; stale -#' directories are deleted opportunistically by later installs once their -#' locks are gone. When this happens, restart R before building or loading -#' `gdalraster` so the new runtime — not the still-mapped old DLLs — is used. -#' -#' Overwriting is refused outright while `gdalraster` is loaded (its DLL pins -#' the whole runtime in the process); reinstalling then requires a fresh R -#' session. If files are locked by *other* processes (another R session, a -#' File Explorer preview pane), neither deletion nor the move-aside is -#' possible and the install aborts cleanly instead of leaving a -#' partially-replaced runtime. -#' -#' @param repo GitHub repo slug publishing the runtime bundle releases. -#' Defaults to `"jimbrig/gdalraster.windows"`. -#' @param tag Release tag or `"latest"`. With `"latest"`, the newest release -#' that publishes a runtime bundle asset (matching `asset_pattern`) is -#' selected; releases without a bundle asset — such as R package releases -#' (`v*`) — are skipped, so GitHub's "latest release" pointer does not need -#' to be a GDAL bundle release. -#' @param asset_pattern Regex used to select the release asset. Defaults to -#' the runtime bundle zip naming convention -#' (`gdal-(bundle|ucrt64)-.*\.zip$`). -#' @param gdal_home Destination GDAL home directory. -#' @param overwrite Whether to replace existing `gdal_home`. -#' @param local_zip Optional local GDAL runtime zip to install directly. -#' @param fallback_zip Optional fallback zip path used when release download -#' fails. When `NULL` (default), a vendored zip at -#' `inst/extdata/gdal-ucrt64-fallback.zip` is used if present; none ships -#' with the package, so by default no fallback is attempted. -#' -#' @return Invisibly returns installed GDAL home path. +#' @return Invisibly, the installed runtime directory. #' @export -#' -#' @importFrom httr2 request req_user_agent req_error req_perform resp_body_raw resp_status -install_gdal_runtime <- function( +gdal_install_runtime <- function( repo = .bundle_repo, tag = "latest", asset_pattern = .bundle_asset_pattern, gdal_home = default_gdal_home(), - overwrite = FALSE, + force = FALSE, local_zip = NULL, fallback_zip = NULL ) { abort_if_not_windows() - - if (!is.character(asset_pattern) || length(asset_pattern) != 1L || !nzchar(asset_pattern)) { - cli::cli_abort("{.arg asset_pattern} must be a single non-empty regex string.") - } - - if (!is.logical(overwrite) || length(overwrite) != 1L || is.na(overwrite)) { - cli::cli_abort("{.arg overwrite} must be TRUE or FALSE.") - } - - if (is.null(fallback_zip)) { - fallback_zip <- packaged_fallback_zip() - } - - if (!is.null(local_zip) && (!is.character(local_zip) || length(local_zip) != 1L || !nzchar(local_zip))) { - cli::cli_abort("{.arg local_zip} must be NULL or a single non-empty path.") - } - - if (!is.null(fallback_zip) && (!is.character(fallback_zip) || length(fallback_zip) != 1L || !nzchar(fallback_zip))) { - cli::cli_abort("{.arg fallback_zip} must be NULL or a single non-empty path.") - } + check_string(repo) + check_string(tag) + check_string(asset_pattern) + check_flag(force) + check_optional_string(local_zip) + check_optional_string(fallback_zip) gdal_home <- normalizePath(gdal_home, winslash = "/", mustWork = FALSE) + cleanup_stale_runtimes(gdal_home) + installed <- installed_bundle_manifest(gdal_home) + asset <- NULL - # fail fast on the destination before any download work - if (dir.exists(gdal_home)) { - if (!isTRUE(overwrite)) { - cli::cli_abort( - c( - "{.arg gdal_home} already exists and {.arg overwrite} is FALSE: {.path {gdal_home}}", - "i" = "Rerun with {.code overwrite = TRUE} to replace the installed runtime." - ) - ) - } - if ("gdalraster" %in% loadedNamespaces()) { - cli::cli_abort( - c( - "Cannot overwrite {.arg gdal_home} while {.pkg gdalraster} is loaded.", - "x" = "{.pkg gdalraster} pins the runtime DLLs in this R process, so they cannot be deleted.", - "i" = "Restart R and run {.fn gdalraster.windows::install_gdal_runtime} before loading {.pkg gdalraster}." - ) - ) - } - } - - tmp_zip <- tempfile(pattern = "gdal-runtime-", fileext = ".zip") - tmp_dir <- tempfile(pattern = "gdal-runtime-extract-") - dir.create(tmp_dir, recursive = TRUE, showWarnings = FALSE) - - zip_path <- NULL - if (!is.null(local_zip)) { - local_zip <- normalizePath(local_zip, winslash = "/", mustWork = FALSE) - abort_if_missing_file(local_zip, "local_zip", call = rlang::caller_env()) - cli::cli_alert_info("using local runtime zip {.path {local_zip}}") - zip_path <- local_zip - } else { - zip_path <- rlang::try_fetch( - { - asset <- resolve_release_asset(repo = repo, tag = tag, asset_pattern = asset_pattern) - cli::cli_alert_info( - "downloading gdal runtime asset {.val {asset$name}} from {.val {repo}} ({.val {asset$tag}})" - ) - - req <- httr2::request(asset$url) - req <- httr2::req_user_agent(req, paste0(pkg_name(), "/", pkg_version())) - req <- httr2::req_error(req, is_error = function(resp) httr2::resp_status(resp) >= 400L) - resp <- httr2::req_perform(req) - writeBin(httr2::resp_body_raw(resp), con = tmp_zip) - tmp_zip - }, + if (is.null(local_zip)) { + asset <- rlang::try_fetch( + resolve_release_asset(repo = repo, tag = tag, asset_pattern = asset_pattern), error = function(cnd) { - fallback_exists <- !is.null(fallback_zip) && file.exists(fallback_zip) - if (!fallback_exists) { + fallback <- if (is.null(fallback_zip)) packaged_fallback_zip() else fallback_zip + if (is.null(fallback) || !file.exists(fallback)) { cli::cli_abort( c( - "Failed to download GDAL runtime from GitHub release and no local fallback is available.", + "Failed to resolve the GDAL runtime release and no fallback is available.", "x" = "{conditionMessage(cnd)}", - "i" = "To install offline, download the release asset from {.url https://github.com/{repo}/releases}", - "i" = "then install it directly: {.code install_gdal_runtime(local_zip = \"path/to/asset.zip\")}" + "i" = "Download a bundle from {.url https://github.com/{repo}/releases} and pass it with {.arg local_zip}." ), parent = cnd, call = rlang::caller_env() ) } - - cli::cli_alert_warning( - "release download failed; using fallback runtime zip {.path {fallback_zip}}" + list( + name = basename(fallback), + tag = "fallback", + local_path = normalizePath(fallback, winslash = "/", mustWork = TRUE) ) - normalizePath(fallback_zip, winslash = "/", mustWork = TRUE) } ) - } - utils::unzip(zip_path, exdir = tmp_dir) - gdal_root <- detect_gdal_root(tmp_dir) - - moved_aside <- FALSE - if (dir.exists(gdal_home)) { - moved_aside <- remove_gdal_home(gdal_home) + if ( + !isTRUE(force) && + dir.exists(gdal_home) && + identical(manifest_value(installed, "Bundle-Tag"), asset$tag) + ) { + cli::cli_alert_success("GDAL runtime {.val {asset$tag}} is already installed.") + return(invisible(gdal_home)) + } } - dir.create(gdal_home, recursive = TRUE, showWarnings = FALSE) - copy_tree(gdal_root, gdal_home) - - cli::cli_alert_success("installed gdal runtime to {.path {gdal_home}}") - if (isTRUE(moved_aside)) { + if ( + dir.exists(gdal_home) && + !isTRUE(force) && + is.null(local_zip) && + identical(tag, "latest") + ) { cli::cli_alert_warning( - paste( - "this session still maps DLLs from the previous runtime", - "(they were moved aside and will be cleaned up by a later install)." + paste0( + "GDAL runtime ", manifest_value(installed, "Bundle-Tag", "unknown"), + " is installed; ", asset$tag, " is available. Run gdal_update() to upgrade." ) ) - cli::cli_inform( - c("i" = "Restart R before building or loading {.pkg gdalraster} so the new runtime is used.") - ) - } - invisible(gdal_home) -} - -#' Activate GDAL runtime for current R session -#' -#' 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. -#' -#' When `preload = TRUE` and the GDAL DLL cannot be loaded (most commonly -#' because a dependency DLL is missing), activation fails with an error -#' rather than deferring the failure to `library(gdalraster)`, where the -#' Windows loader reports only a generic "module could not be found". -#' -#' @param gdal_home GDAL home directory. -#' @param preload Whether to preload `libgdal-*.dll`. -#' @param quiet Suppress informational CLI output. -#' -#' @return Invisibly returns a list with configured paths. -#' @export -activate_gdal_runtime <- function( - gdal_home = default_gdal_home(), - preload = TRUE, - quiet = FALSE -) { - abort_if_not_windows() - - gdal_home <- normalizePath(gdal_home, winslash = "/", mustWork = FALSE) - abort_if_missing_dir(gdal_home, "gdal_home") - - bin_dir <- gdal_bin_dir(gdal_home) - abort_if_missing_dir(bin_dir, "gdal_home/bin") - - dll_path <- gdal_dll_path(gdal_home) - abort_if_missing_file(dll_path, "gdal_home/bin/libgdal-*.dll") - - path_sep <- .Platform$path.sep - current_path <- Sys.getenv("PATH", unset = "") - path_parts <- strsplit(current_path, split = path_sep, fixed = TRUE)[[1]] - path_parts <- path_parts[nzchar(path_parts)] - - if (!bin_dir %in% path_parts) { - Sys.setenv(PATH = paste(c(bin_dir, path_parts), collapse = path_sep)) - } - - 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) - } - if (dir.exists(proj_data)) { - Sys.setenv(PROJ_LIB = proj_data) - 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)) - } - } - - # preload failures must be loud: a swallowed failure here surfaces later as - # an uninformative LoadLibrary error when gdalraster.dll is loaded, hiding - # the actual cause (typically a missing dependency DLL of libgdal). - if (isTRUE(preload)) { - rlang::try_fetch( - dyn.load(dll_path, local = FALSE, now = TRUE), - error = function(cnd) { - cli::cli_abort( - c( - "Failed to preload the GDAL runtime DLL.", - "x" = "{conditionMessage(cnd)}", - "i" = "DLL: {.path {dll_path}}", - "i" = paste( - "On Windows this usually means a dependency DLL of", - "{.file {basename(dll_path)}} could not be found." - ), - "i" = "See {.code vignette(\"troubleshooting\", package = \"gdalraster.windows\")}." - ), - parent = cnd - ) - } - ) - } - - if (!isTRUE(quiet)) { - cli::cli_alert_success("gdal runtime activated from {.path {gdal_home}}") + return(invisible(gdal_home)) } - invisible( - list( - gdal_home = gdal_home, - 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_, - gdal_python = if (dir.exists(python_dir)) python_dir else NA_character_ - ) - ) -} - -#' Load GDAL DLL from runtime bundle -#' -#' Convenience wrapper over [activate_gdal_runtime()] that ensures the GDAL -#' runtime is activated and the main GDAL DLL is preloaded in the current -#' session. -#' -#' @param gdal_home GDAL home directory. -#' @param quiet Suppress informational CLI output. -#' -#' @return Invisibly returns activation metadata. -#' @export -load_gdal_dll <- function(gdal_home = default_gdal_home(), quiet = FALSE) { - activate_gdal_runtime(gdal_home = gdal_home, preload = TRUE, quiet = quiet) -} - -#' Install gdalraster from source against bundled GDAL -#' -#' Downloads or uses a local gdalraster source tarball and installs it from -#' source into a dedicated library path (default) so existing user libraries -#' are not overwritten. To install into your regular user library instead -#' (so plain `library(gdalraster)` resolves the source build without this -#' package's load helpers), pass it explicitly, e.g. -#' `install_gdalraster(lib = .libPaths()[1])`. -#' -#' @section Prerequisites: -#' This is a source compilation, so -#' [Rtools](https://cran.r-project.org/bin/windows/Rtools/) matching your R -#' version must be installed (the one thing the prebuilt runtime bundle cannot -#' eliminate). The function checks for a toolchain up front and aborts with -#' guidance when none is found. The GDAL runtime bundle itself must already be -#' installed via [install_gdal_runtime()]. -#' -#' @section Upgrading: -#' After installing a new runtime bundle version -#' (`install_gdal_runtime(overwrite = TRUE)`), rerun this function — the -#' previous gdalraster build is bound to the previous bundle's GDAL and must -#' be recompiled against the new one. -#' -#' @section Bundled data files: -#' Upstream gdalraster's `Makevars.win` copies GDAL and PROJ data directories -#' into the package from the Rtools static libraries, which generally lag the -#' bundle's GDAL. After the source install succeeds, this function replaces -#' the installed package's `gdal/` and `proj/` data directories with the -#' runtime bundle's `share/gdal` and `share/proj` so the data files match the -#' GDAL version the package was compiled against. -#' -#' @param gdal_home GDAL home directory used for compile/link flags. -#' @param lib Destination library path for installing gdalraster. Defaults to -#' an isolated package-managed library; pass `.libPaths()[1]` to install -#' into your default user library. -#' @param source_tarball Optional local path to `gdalraster_*.tar.gz`. -#' @param repo Source GitHub repo slug for gdalraster. Defaults to -#' `"firelab/gdalraster"`. -#' @param ref Git ref (branch, tag, commit) used when downloading from GitHub. -#' @param upgrade When `TRUE`, missing R package dependencies of gdalraster are -#' installed from `repos` before the source build. Has no effect on the -#' compile/link flags used to build gdalraster itself. -#' @param repos CRAN-like repositories used to satisfy R package dependencies -#' when `upgrade = TRUE`. Ignored when `upgrade = FALSE`. -#' -#' @return Invisibly returns installed library path. -#' @export -#' -#' @importFrom httr2 request req_user_agent req_error req_perform resp_body_raw resp_status -#' @importFrom withr with_makevars with_envvar -install_gdalraster <- function( - gdal_home = default_gdal_home(), - lib = default_gdalraster_lib(), - source_tarball = NULL, - repo = .gdalraster_repo, - ref = "HEAD", - upgrade = FALSE, - repos = getOption("repos") -) { - abort_if_not_windows() - abort_if_no_build_tools() - activate_gdal_runtime(gdal_home = gdal_home, preload = TRUE, quiet = TRUE) - - if (!is.character(lib) || length(lib) != 1L || !nzchar(lib)) { + if (dir.exists(gdal_home) && !isTRUE(force) && is.null(local_zip)) { cli::cli_abort( - "{.arg lib} must be a single non-empty path.", + c( + "A different or untracked GDAL runtime is installed at {.path {gdal_home}}.", + "i" = "Run {.fn gdal_update} or set {.code force = TRUE} to replace it." + ), call = rlang::caller_env() ) } - if (!is.null(source_tarball)) { - if (!is.character(source_tarball) || length(source_tarball) != 1L || !nzchar(source_tarball)) { - cli::cli_abort( - "{.arg source_tarball} must be NULL or a single file path.", - call = rlang::caller_env() - ) - } - abort_if_missing_file(source_tarball, "source_tarball", call = rlang::caller_env()) - tarball <- normalizePath(source_tarball, winslash = "/", mustWork = TRUE) + zip_path <- if (!is.null(local_zip)) { + abort_if_missing_file(local_zip, "local_zip") + normalizePath(local_zip, winslash = "/", mustWork = TRUE) + } else if (!is.null(asset[["local_path"]])) { + cli::cli_alert_warning("Release lookup failed; using {.file {asset$name}}.") + asset$local_path } else { - if (!is.character(repo) || length(repo) != 1L || !nzchar(repo)) { - cli::cli_abort( - "{.arg repo} must be a single non-empty string like {.val 'owner/name'}.", - call = rlang::caller_env() - ) - } - if (!is.character(ref) || length(ref) != 1L || !nzchar(ref)) { - cli::cli_abort( - "{.arg ref} must be a single non-empty git ref.", - call = rlang::caller_env() - ) + download_release_asset(asset, repo = repo) + } + + extract_dir <- tempfile("gdal-runtime-extract-") + dir.create(extract_dir, recursive = TRUE, showWarnings = FALSE) + withr::defer(unlink(extract_dir, recursive = TRUE, force = TRUE)) + utils::unzip(zip_path, exdir = extract_dir) + source_root <- detect_gdal_root(extract_dir) + embedded <- read_manifest(file.path(source_root, "MANIFEST.dcf")) + + selected_tag <- manifest_value( + embedded, + "Bundle-Tag", + default = if (!is.null(asset[["tag"]])) { + asset$tag + } else if (identical(tag, "latest")) { + "local" + } else { + tag } - - tarball <- tempfile(pattern = "gdalraster-", fileext = ".tar.gz") - src_url <- paste0("https://codeload.github.com/", repo, "/tar.gz/", ref) - req <- httr2::request(src_url) - req <- httr2::req_user_agent(req, paste0(pkg_name(), "/", pkg_version())) - req <- httr2::req_error(req, is_error = function(resp) httr2::resp_status(resp) >= 400L) - resp <- httr2::req_perform(req) - writeBin(httr2::resp_body_raw(resp), con = tarball) - } - - lib <- normalizePath(lib, winslash = "/", mustWork = FALSE) - dir.create(lib, recursive = TRUE, showWarnings = FALSE) - - gdal_home <- normalizePath(gdal_home, winslash = "/", mustWork = FALSE) - makevars <- c( - GDAL_HOME = gdal_home, - PKG_CPPFLAGS = paste0("-I\"", file.path(gdal_home, "include"), "\""), - PKG_LIBS = paste0("-L\"", file.path(gdal_home, "lib"), "\" -lgdal -Wl,--allow-multiple-definition") - ) - - path_sep <- .Platform$path.sep - old_path <- Sys.getenv("PATH", unset = "") - runtime_path <- paste(c(gdal_bin_dir(gdal_home), old_path), collapse = path_sep) - env_vars <- c( - PATH = runtime_path, - GDAL_DATA = gdal_share_gdal_dir(gdal_home), - PROJ_LIB = gdal_share_proj_dir(gdal_home), - PROJ_DATA = gdal_share_proj_dir(gdal_home) ) + selected_asset <- if (is.null(asset[["name"]])) basename(zip_path) else asset$name - cli::cli_alert_info("installing {.pkg gdalraster} from source into {.path {lib}}") - - # When upgrade = TRUE, install gdalraster's R package dependencies from CRAN - # first so they are available for the source build. This must be a separate - # step because install.packages() must be called with repos = NULL below - # (required for local-file installation; with repos != NULL R treats the - # tarball path as a package name to look up and never installs from the file). - if (isTRUE(upgrade)) { - rlang::try_fetch( - utils::install.packages( - pkgs = "gdalraster", - repos = repos, - type = "source", - lib = lib, - dependencies = TRUE, - INSTALL_opts = c("--no-test-load") - ), - error = function(cnd) { - cli::cli_alert_warning( - "Could not pre-install {.pkg gdalraster} dependencies: {conditionMessage(cnd)}" - ) - } - ) + if ( + !isTRUE(force) && + dir.exists(gdal_home) && + identical(manifest_value(installed, "Bundle-Tag"), selected_tag) + ) { + cli::cli_alert_success("GDAL runtime {.val {selected_tag}} is already installed.") + return(invisible(gdal_home)) } - rlang::try_fetch( - withr::with_makevars(new = makevars, assignment = "=", { - withr::with_envvar(env_vars, { - # repos = NULL is required here: when repos is non-NULL, install.packages() - # treats the tarball path as a package name to look up in the repository - # rather than as a local file, producing a "not available for this version - # of R" warning and silently skipping the install. - utils::install.packages( - pkgs = tarball, - repos = NULL, - type = "source", - lib = lib, - INSTALL_opts = c("--no-test-load") - ) - }) - }), - error = function(cnd) { - cli::cli_abort( - c( - "Failed to install {.pkg gdalraster} from source.", - "x" = "{conditionMessage(cnd)}" - ), - parent = cnd, - call = rlang::caller_env() - ) - } - ) - - if (!dir.exists(file.path(lib, "gdalraster"))) { + if (dir.exists(gdal_home) && !isTRUE(force)) { cli::cli_abort( c( - "gdalraster source install did not produce an installed package.", - "i" = "Library path: {.path {lib}}" + "GDAL runtime {.val {manifest_value(installed, 'Bundle-Tag', 'unknown')}} is already installed.", + "i" = "Requested bundle: {.val {selected_tag}}.", + "i" = "Set {.code force = TRUE} to replace it." ), call = rlang::caller_env() ) } - synced <- sync_gdalraster_share_data(lib = lib, gdal_home = gdal_home) - if (length(synced) > 0L) { - cli::cli_alert_info( - "replaced packaged {.field {synced}} data with the bundle's GDAL/PROJ data" - ) + moved_aside <- FALSE + if (dir.exists(gdal_home)) { + moved_aside <- remove_gdal_home(gdal_home) } - cli::cli_alert_success("installed {.pkg gdalraster} to {.path {lib}}") - invisible(lib) -} - -#' Load gdalraster using bundled GDAL runtime -#' -#' Activates bundled GDAL runtime, prepends `lib` to `.libPaths()`, and attaches -#' gdalraster for use in the current R session. -#' -#' @param lib Library path containing the gdalraster source install. -#' @param gdal_home GDAL home directory. -#' @param quiet Suppress informational CLI output. -#' -#' @return Invisibly returns TRUE if gdalraster was attached. -#' @export -load_gdalraster <- function( - lib = default_gdalraster_lib(), - gdal_home = default_gdal_home(), - quiet = FALSE -) { - abort_if_not_windows() - - lib <- normalizePath(lib, winslash = "/", mustWork = FALSE) - abort_if_missing_dir(lib, "lib", call = rlang::caller_env()) + dir.create(gdal_home, recursive = TRUE, showWarnings = FALSE) + copy_tree(source_root, gdal_home) - if (!dir.exists(file.path(lib, "gdalraster"))) { - cli::cli_abort( - c( - "No {.pkg gdalraster} install found in {.arg lib}.", - "i" = "Run {.fn gdalraster.windows::install_gdalraster} first." - ), - call = rlang::caller_env() + manifest <- if (is.null(embedded)) { + bundle_manifest( + tag = selected_tag, + gdal_version = gdal_version_from_tag(selected_tag), + asset_name = selected_asset ) + } else { + embedded } + manifest[["Bundle-Tag"]] <- selected_tag + manifest[["Asset-Name"]] <- selected_asset + manifest[["Installed-At"]] <- format(Sys.time(), tz = "UTC", usetz = TRUE) + manifest[["Installer-Version"]] <- pkg_version() + write_manifest(manifest, bundle_manifest_path(gdal_home)) - activate_gdal_runtime(gdal_home = gdal_home, preload = TRUE, quiet = quiet) - - .libPaths(c(lib, .libPaths())) - base::library("gdalraster", character.only = TRUE, lib.loc = lib) - invisible(TRUE) -} - -#' Verify gdalraster algorithm API availability -#' -#' Attempts to load `gdalraster` and checks the global algorithm registry. -#' -#' @param lib.loc Optional library location used for loading `gdalraster`. -#' @param activate_runtime Whether to run [activate_gdal_runtime()] first. -#' @param gdal_home GDAL home used when `activate_runtime = TRUE`. -#' @param quiet If `TRUE`, suppress sitrep CLI output. -#' -#' @return `TRUE` when algorithm API is available, otherwise `FALSE` -#' (including when runtime activation itself fails). -#' @export -verify_gdalraster_runtime <- function( - lib.loc = NULL, - activate_runtime = TRUE, - gdal_home = default_gdal_home(), - quiet = FALSE -) { - abort_if_not_windows() - - if (isTRUE(activate_runtime)) { - activated <- rlang::try_fetch( - { - activate_gdal_runtime(gdal_home = gdal_home, preload = TRUE, quiet = TRUE) - TRUE - }, - error = function(cnd) { - if (!isTRUE(quiet)) { - cli::cli_alert_danger( - "gdal runtime activation failed: {conditionMessage(cnd)}" - ) - } - FALSE - } + cli::cli_alert_success("Installed GDAL runtime {.val {selected_tag}}.") + if (isTRUE(moved_aside)) { + cli::cli_alert_warning( + "Mapped files from the previous runtime were moved aside; restart R before building." ) - if (!activated) { - return(FALSE) - } } - - if (!has_gdalraster_namespace()) { - if (!isTRUE(quiet)) { - cli::cli_alert_warning("{.pkg gdalraster} is not installed.") - cli::cli_inform("Run {.fn gdalraster.windows::install_gdalraster} first.") - } - return(FALSE) - } - - ok <- rlang::try_fetch( - { - suppressMessages(base::library("gdalraster", character.only = TRUE, lib.loc = lib.loc)) - alg_names <- gdalraster::gdal_global_reg_names() - version <- gdalraster::gdal_version()[[1]] - list(ok = length(alg_names) > 0L, version = version, count = length(alg_names)) - }, - error = function(cnd) { - if (!isTRUE(quiet)) { - cli::cli_alert_danger("gdalraster verification failed: {conditionMessage(cnd)}") - } - list(ok = FALSE, version = NA_character_, count = 0L) - } - ) - - if (!isTRUE(quiet)) { - if (isTRUE(ok$ok)) { - cli::cli_alert_success("gdalraster is ready ({.val {ok$version}})") - cli::cli_inform( - c( - "i" = "algorithm registry entries: {.val {ok$count}}", - "i" = "runtime home: {.path {normalizePath(gdal_home, winslash = '/', mustWork = FALSE)}}" - ) - ) - } else { - cli::cli_alert_warning("gdalraster loaded, but algorithm API is not available.") - cli::cli_inform( - c( - "i" = "gdal version: {.val {ok$version}}", - "i" = "algorithm registry entries: {.val {ok$count}}" - ) - ) - } - } - - isTRUE(ok$ok) + invisible(gdal_home) } #' @keywords internal #' @noRd -has_gdalraster_namespace <- function() { - requireNamespace("gdalraster", quietly = TRUE) +download_release_asset <- function(asset, repo) { + destination <- tempfile("gdal-runtime-", fileext = ".zip") + cli::cli_alert_info( + "Downloading {.file {asset$name}} from {.val {repo}} ({.val {asset$tag}})." + ) + request <- httr2::request(asset$url) + request <- httr2::req_user_agent(request, paste0(pkg_name(), "/", pkg_version())) + request <- httr2::req_error( + request, + is_error = function(response) httr2::resp_status(response) >= 400L + ) + response <- httr2::req_perform(request) + writeBin(httr2::resp_body_raw(response), destination) + destination } #' @keywords internal #' @noRd detect_gdal_root <- function(extract_dir) { - dll_candidates <- list.files( - path = extract_dir, - pattern = "^libgdal-[0-9]+\\.dll$", - all.files = TRUE, + dlls <- list.files( + extract_dir, + pattern = .gdal_dll_pattern, recursive = TRUE, full.names = TRUE ) - - if (length(dll_candidates) < 1L) { - cli::cli_abort( - "Could not find {.file libgdal-*.dll} in extracted release asset." - ) + if (length(dlls) < 1L) { + cli::cli_abort("Could not find {.file libgdal-*.dll} in the bundle.") } - - normalizePath(dirname(dirname(dll_candidates[[1]])), winslash = "/", mustWork = TRUE) + normalizePath(dirname(dirname(dlls[[1L]])), winslash = "/", mustWork = TRUE) } -#' Remove an existing GDAL home directory, releasing this session's own locks -#' -#' The `.onLoad` auto-bootstrap preloads `libgdal-*.dll` from `gdal_home`, so -#' the current R process itself typically holds the file locks that would make -#' deletion fail. DLLs this session loaded from under `gdal_home` are unloaded -#' first (safe while `gdalraster` is not loaded, which is validated before the -#' download), but that alone cannot release everything: activation prepends -#' the runtime's `bin` to `PATH`, so any DLL the process loads afterwards can -#' resolve its dependencies from there by module name (demonstrably, the -#' release download itself loads the curl package, which maps the runtime's -#' `zlib1.dll`). Such mappings live outside R's DLL registry and cannot be -#' `dyn.unload()`ed, so the session cannot fully unlock its own runtime. -#' -#' Mapped DLLs cannot be deleted, but they *can* be renamed on the same -#' volume, so any leftovers after `unlink()` are moved into a stale sibling -#' directory (`.stale--`) which later installs -#' delete opportunistically once the locks are gone. Only files locked by -#' *other* processes without delete sharing (File Explorer preview panes, -#' other R sessions) can still block the move, and that is the only case -#' left that aborts. -#' -#' @return Invisibly, `TRUE` when leftovers were moved aside (the session -#' still maps old runtime DLLs), `FALSE` when the runtime was fully deleted. #' @keywords internal #' @noRd remove_gdal_home <- function(gdal_home, call = rlang::caller_env()) { cleanup_stale_runtimes(gdal_home) - - for (dll in loaded_runtime_dlls(gdal_home)) { - try(dyn.unload(dll), silent = TRUE) - } - unlink(gdal_home, recursive = TRUE, force = TRUE) - if (!dir.exists(gdal_home)) { return(invisible(FALSE)) } stale_dir <- stale_runtime_dir(gdal_home) - moved <- move_tree_aside(gdal_home, stale_dir) - - if (!moved) { + if (!move_tree_aside(gdal_home, stale_dir)) { cli::cli_abort( c( - "Could not fully delete or move aside the existing runtime at {.path {gdal_home}}.", + "Could not fully delete or move aside the runtime at {.path {gdal_home}}.", "x" = "One or more files are locked by another process.", - "i" = paste( - "Common culprits: other R sessions using the runtime, or", - "File Explorer windows/preview panes open on the directory." - ), - "i" = "Close them (or identify lockers with PowerToys File Locksmith / Resource Monitor) and rerun." + "i" = "Close other R sessions and File Explorer windows using this directory, then retry." ), call = call ) } - invisible(TRUE) } -#' Move every file under `from` into `to` via same-volume rename, then remove -#' the emptied tree. Returns TRUE only when `from` is fully gone. #' @keywords internal #' @noRd move_tree_aside <- function(from, to) { entries <- list.files( - path = from, + from, all.files = TRUE, no.. = TRUE, recursive = TRUE, include.dirs = FALSE ) - ok <- TRUE for (entry in entries) { - src <- file.path(from, entry) - dst <- file.path(to, entry) - dir.create(dirname(dst), recursive = TRUE, showWarnings = FALSE) - if (!isTRUE(suppressWarnings(file.rename(src, dst)))) { + source <- file.path(from, entry) + destination <- file.path(to, entry) + dir.create(dirname(destination), recursive = TRUE, showWarnings = FALSE) + if (!isTRUE(suppressWarnings(file.rename(source, destination)))) { ok <- FALSE } } - unlink(from, recursive = TRUE, force = TRUE) ok && !dir.exists(from) } @@ -801,24 +277,23 @@ move_tree_aside <- function(from, to) { #' @noRd copy_tree <- function(from, to) { entries <- list.files( - path = from, + from, all.files = TRUE, no.. = TRUE, recursive = TRUE, include.dirs = TRUE ) - for (entry in entries) { - src <- file.path(from, entry) - dst <- file.path(to, entry) - if (dir.exists(src)) { - dir.create(dst, recursive = TRUE, showWarnings = FALSE) + source <- file.path(from, entry) + destination <- file.path(to, entry) + if (dir.exists(source)) { + dir.create(destination, recursive = TRUE, showWarnings = FALSE) } else { - dir.create(dirname(dst), recursive = TRUE, showWarnings = FALSE) - ok <- file.copy(from = src, to = dst, overwrite = TRUE, copy.mode = TRUE) - if (!isTRUE(ok)) { - cli::cli_abort("Failed to copy {.path {src}} to {.path {dst}}.") + dir.create(dirname(destination), recursive = TRUE, showWarnings = FALSE) + if (!isTRUE(file.copy(source, destination, overwrite = TRUE, copy.mode = TRUE))) { + cli::cli_abort("Failed to copy {.path {source}} to {.path {destination}}.") } } } + invisible(to) } diff --git a/R/gdal_setup.R b/R/gdal_setup.R new file mode 100644 index 0000000..c536609 --- /dev/null +++ b/R/gdal_setup.R @@ -0,0 +1,227 @@ +#' Set up a self-contained gdalraster installation +#' +#' Installs the GDAL build runtime when needed, builds and vendors +#' `gdalraster`, provisions embedded Python when available, and verifies the +#' result in fresh processes. +#' +#' @param lib Destination library for `gdalraster`. +#' @param user_lib Use `.libPaths()[1]` instead of the isolated managed library. +#' @param update Upgrade the runtime to the requested/latest bundle and rebuild. +#' @param force Reinstall and rebuild even when provenance is current. +#' @param tag Runtime bundle release tag or `"latest"`. +#' @param local_zip Optional local runtime bundle. +#' @param fallback_zip Optional local fallback runtime bundle. +#' @param source_tarball Optional local `gdalraster` source tarball. +#' @param upgrade Install `gdalraster` R dependencies before compiling. +#' @param verify Run [gdal_verify()] after setup. +#' +#' @return Invisibly, a list describing performed actions. +#' @export +gdal_setup <- function( + lib = NULL, + user_lib = FALSE, + update = FALSE, + force = FALSE, + tag = "latest", + local_zip = NULL, + fallback_zip = NULL, + source_tarball = NULL, + upgrade = FALSE, + verify = TRUE +) { + abort_if_not_windows() + check_flag(user_lib) + check_flag(update) + check_flag(force) + check_flag(upgrade) + check_flag(verify) + check_string(tag) + check_optional_string(lib) + check_optional_string(local_zip) + check_optional_string(fallback_zip) + check_optional_string(source_tarball) + + lib <- resolve_gdalraster_lib(lib, user_lib) + before <- gdal_sitrep(lib = lib, network = FALSE, quiet = TRUE) + install_runtime <- !before$runtime_installed || isTRUE(update) || isTRUE(force) + build_package <- !before$gdalraster_installed || + !before$build_current || + isTRUE(update) || + isTRUE(force) + + cli::cli_h2("Setup plan") + cli::cli_inform(c( + "1" = "{if (install_runtime) 'Install or refresh' else 'Keep'} the GDAL build runtime", + "2" = "{if (build_package) 'Build and vendor' else 'Keep'} {.pkg gdalraster}", + "3" = "Provision embedded-Python utilities when CPython is available", + "4" = "{if (verify) 'Run' else 'Skip'} fresh-process verification" + )) + + if (rlang::is_interactive()) { + proceed <- utils::askYesNo("Proceed with this setup plan?", default = TRUE) + if (!isTRUE(proceed)) { + cli::cli_abort("Setup cancelled.", call = rlang::caller_env()) + } + } + + actions <- character() + if (install_runtime) { + gdal_install_runtime( + tag = tag, + gdal_home = default_gdal_home(), + force = isTRUE(update) || isTRUE(force), + local_zip = local_zip, + fallback_zip = fallback_zip + ) + actions <- c(actions, "runtime") + } + + after_runtime <- gdal_sitrep(lib = lib, network = FALSE, quiet = TRUE) + if (!before$runtime_installed && after_runtime$runtime_installed) { + build_package <- TRUE + } + if (!identical(before$bundle_tag, after_runtime$bundle_tag)) { + build_package <- TRUE + } + + if (build_package) { + gdal_build_gdalraster( + gdal_home = default_gdal_home(), + lib = lib, + user_lib = FALSE, + source_tarball = source_tarball, + upgrade = upgrade, + force = after_runtime$gdalraster_installed || isTRUE(force) || isTRUE(update), + enable_python = TRUE + ) + actions <- c(actions, "gdalraster") + } else if (after_runtime$gdalraster_installed) { + gdal_enable_python(lib = lib, quiet = TRUE) + } + + verified <- if (isTRUE(verify)) { + gdal_verify(lib = lib, quiet = TRUE) + } else { + NA + } + if (isTRUE(verify) && !isTRUE(verified)) { + cli::cli_abort( + c( + "Setup completed, but fresh-process verification failed.", + "i" = "Run {.fn gdal_sitrep} and {.fn gdal_verify} for details." + ), + call = rlang::caller_env() + ) + } + + cli::cli_h2("Setup complete") + cli::cli_inform(c( + "v" = "runtime: {manifest_value(installed_bundle_manifest(), 'Bundle-Tag')}", + "v" = "gdalraster library: {.path {lib}}", + "v" = "verification: {.val {verified}}" + )) + invisible(list(actions = unique(actions), lib = lib, verified = verified)) +} + +#' Update the GDAL runtime and rebuild gdalraster +#' +#' @inheritParams gdal_setup +#' +#' @return The result of [gdal_setup()], invisibly. +#' @export +gdal_update <- function( + lib = NULL, + user_lib = FALSE, + tag = "latest", + local_zip = NULL, + fallback_zip = NULL, + source_tarball = NULL, + upgrade = FALSE, + verify = TRUE +) { + gdal_setup( + lib = lib, + user_lib = user_lib, + update = TRUE, + force = TRUE, + tag = tag, + local_zip = local_zip, + fallback_zip = fallback_zip, + source_tarball = source_tarball, + upgrade = upgrade, + verify = verify + ) +} + +#' Uninstall managed GDAL resources +#' +#' @param lib Library containing the managed `gdalraster` package. +#' @param user_lib Use `.libPaths()[1]`. +#' @param runtime Remove the GDAL build runtime. +#' @param package Remove the managed `gdalraster` package. +#' @param python Remove managed embedded-Python `.pth` files. +#' @param force Confirm removal in non-interactive sessions. +#' +#' @return Invisibly, the removed paths. +#' @export +gdal_uninstall <- function( + lib = NULL, + user_lib = FALSE, + runtime = TRUE, + package = TRUE, + python = TRUE, + force = FALSE +) { + abort_if_not_windows() + check_flag(user_lib) + check_flag(runtime) + check_flag(package) + check_flag(python) + check_flag(force) + check_optional_string(lib) + + lib <- resolve_gdalraster_lib(lib, user_lib) + package_dir <- file.path(lib, "gdalraster") + targets_exist <- (runtime && dir.exists(default_gdal_home())) || + (package && dir.exists(package_dir)) || + (python && length(managed_python_pth_files()) > 0L) + + if (!targets_exist) { + cli::cli_alert_info("No managed GDAL resources were found.") + return(invisible(character())) + } + if (!isTRUE(force)) { + if (!rlang::is_interactive()) { + cli::cli_abort( + "Set {.code force = TRUE} to uninstall managed resources non-interactively.", + call = rlang::caller_env() + ) + } + proceed <- utils::askYesNo("Remove the selected managed GDAL resources?", default = FALSE) + if (!isTRUE(proceed)) { + cli::cli_abort("Uninstall cancelled.", call = rlang::caller_env()) + } + } + + removed <- character() + if (isTRUE(python)) { + removed <- c(removed, remove_managed_python_pth()) + } + if (isTRUE(package) && dir.exists(package_dir)) { + unlink(package_dir, recursive = TRUE, force = TRUE) + if (dir.exists(package_dir)) { + cli::cli_abort( + "Could not remove {.path {package_dir}}; close sessions using {.pkg gdalraster}.", + call = rlang::caller_env() + ) + } + removed <- c(removed, package_dir) + } + if (isTRUE(runtime) && dir.exists(default_gdal_home())) { + remove_gdal_home(default_gdal_home()) + removed <- c(removed, default_gdal_home()) + } + + cli::cli_alert_success("Removed managed GDAL resources.") + invisible(unique(removed)) +} diff --git a/R/gdal_sitrep.R b/R/gdal_sitrep.R new file mode 100644 index 0000000..499a7c7 --- /dev/null +++ b/R/gdal_sitrep.R @@ -0,0 +1,171 @@ +#' Report GDAL and gdalraster installation state +#' +#' Reports bundle and build provenance, staleness, embedded-Python +#' provisioning, and common collision risks without changing the session. +#' +#' @param lib Library expected to contain the managed `gdalraster` build. +#' @param user_lib Inspect `.libPaths()[1]` instead of the isolated library. +#' @param network Query GitHub for the latest bundle release. +#' @param quiet Return state without printing it. +#' +#' @return Invisibly, a named list describing installation state. +#' @export +gdal_sitrep <- function( + lib = NULL, + user_lib = FALSE, + network = rlang::is_interactive(), + quiet = FALSE +) { + check_flag(user_lib) + check_flag(network) + check_flag(quiet) + check_optional_string(lib) + + home <- default_gdal_home() + lib <- resolve_gdalraster_lib(lib, user_lib) + package_dir <- file.path(lib, "gdalraster") + bundle <- installed_bundle_manifest(home) + build <- read_manifest(build_manifest_path(package_dir)) + latest <- if (isTRUE(network)) { + tryCatch( + resolve_release_asset( + repo = .bundle_repo, + tag = "latest", + asset_pattern = .bundle_asset_pattern + )$tag, + error = function(cnd) NA_character_ + ) + } else { + NA_character_ + } + + pth_files <- managed_python_pth_files() + pth_targets <- vapply(pth_files, pth_target, character(1)) + package_python <- normalizePath( + file.path(package_dir, "python"), + winslash = "/", + mustWork = FALSE + ) + python_ready <- any(!is.na(pth_targets) & identical_paths(pth_targets, package_python)) + python_stale <- pth_files[is.na(pth_targets) | !dir.exists(pth_targets)] + + path_gdal <- path_gdal_dlls() + loaded_gdal <- loaded_gdal_dlls() + legacy_hook <- legacy_hook_detected() + visible_gdalraster <- suppressWarnings(system.file(package = "gdalraster")) + foreign_gdalraster <- nzchar(visible_gdalraster) && + !identical_paths(visible_gdalraster, package_dir) + + state <- list( + gdal_home = home, + runtime_installed = dir.exists(home) && length(gdal_dll_candidates(home)) > 0L, + bundle_tag = manifest_value(bundle, "Bundle-Tag"), + gdal_version = manifest_value(bundle, "GDAL-Version"), + latest_tag = latest, + update_available = !is.na(latest) && + !identical(latest, manifest_value(bundle, "Bundle-Tag")), + lib = lib, + package_dir = package_dir, + gdalraster_installed = dir.exists(package_dir), + build_tag = manifest_value(build, "Bundle-Tag"), + build_current = build_is_current(bundle, build), + python_ready = python_ready, + python_pth = pth_files, + python_stale = python_stale, + path_gdal = path_gdal, + loaded_gdal = loaded_gdal, + legacy_hook = legacy_hook, + foreign_gdalraster = foreign_gdalraster, + visible_gdalraster = visible_gdalraster + ) + + if (!isTRUE(quiet)) { + print_gdal_sitrep(state) + } + invisible(state) +} + +#' @keywords internal +#' @noRd +print_gdal_sitrep <- function(state) { + cli::cli_h2("gdalraster.windows") + cli::cli_inform(c( + "*" = "runtime: {if (state$runtime_installed) state$bundle_tag else 'not installed'}", + "*" = "gdalraster: {if (state$gdalraster_installed) state$build_tag else 'not installed'}", + "*" = "build current: {.val {state$build_current}}", + "*" = "embedded Python: {.val {state$python_ready}}" + )) + + warnings <- character() + if (isTRUE(state$update_available)) { + warnings <- c(warnings, paste0("bundle ", state$latest_tag, " is available")) + } + if (length(state$path_gdal) > 0L) { + warnings <- c(warnings, "other libgdal DLLs are present on PATH") + } + if (length(state$loaded_gdal) > 0L) { + warnings <- c(warnings, "a libgdal DLL is already loaded in this session") + } + if (isTRUE(state$legacy_hook)) { + warnings <- c(warnings, "a legacy gdalraster.windows .Rprofile hook was detected") + } + if (isTRUE(state$foreign_gdalraster)) { + warnings <- c(warnings, "a different gdalraster installation is visible on .libPaths()") + } + if (length(state$python_stale) > 0L) { + warnings <- c(warnings, "a managed Python .pth file has a stale target") + } + if (length(warnings) > 0L) { + cli::cli_inform(stats::setNames(as.list(warnings), rep("!", length(warnings)))) + } + + if (!isTRUE(state$runtime_installed) || !isTRUE(state$gdalraster_installed)) { + cli::cli_inform(c("i" = "Run {.fn gdal_setup} to complete setup.")) + } else if (!isTRUE(state$build_current)) { + cli::cli_inform(c("i" = "Run {.fn gdal_update} to rebuild against the installed bundle.")) + } else { + cli::cli_inform(c("i" = "Run {.fn gdal_verify} for fresh-process verification.")) + } +} + +#' @keywords internal +#' @noRd +identical_paths <- function(x, y) { + tolower(normalizePath(x, winslash = "/", mustWork = FALSE)) == + tolower(normalizePath(y, winslash = "/", mustWork = FALSE)) +} + +#' @keywords internal +#' @noRd +path_gdal_dlls <- function() { + parts <- strsplit(Sys.getenv("PATH", unset = ""), .Platform$path.sep, fixed = TRUE)[[1L]] + parts <- unique(parts[nzchar(parts) & dir.exists(parts)]) + unique(unlist(lapply( + parts, + list.files, + pattern = .gdal_dll_pattern, + full.names = TRUE + ), use.names = FALSE)) +} + +#' @keywords internal +#' @noRd +loaded_gdal_dlls <- function() { + paths <- vapply( + getLoadedDLLs(), + function(dll) dll[["path"]], + character(1) + ) + unname(paths[grepl(.gdal_dll_pattern, basename(paths), ignore.case = TRUE)]) +} + +#' @keywords internal +#' @noRd +legacy_hook_detected <- function(rprofile = "~/.Rprofile") { + path <- path.expand(rprofile) + if (!file.exists(path)) { + return(FALSE) + } + text <- paste(readLines(path, warn = FALSE), collapse = "\n") + grepl("gdalraster.windows hook|load_gdal_dll|ensure_gdal_runtime", text) +} diff --git a/R/gdal_verify.R b/R/gdal_verify.R new file mode 100644 index 0000000..4ffcbd3 --- /dev/null +++ b/R/gdal_verify.R @@ -0,0 +1,162 @@ +#' Verify the self-contained gdalraster installation +#' +#' Runs verification in fresh `Rscript --vanilla` processes. Checks the GDAL +#' Algorithm API, GEOS and CRS support, Arrow/Parquet/HDF5/netCDF driver +#' registration, a first Parquet dataset open, and the GeoPackage Python +#' validator when embedded Python has been provisioned. +#' +#' @param lib Library containing the managed `gdalraster` package. +#' @param user_lib Use `.libPaths()[1]`. +#' @param python Run the embedded-Python validation when its managed `.pth` +#' file is ready. +#' @param quiet Suppress verification output. +#' +#' @return `TRUE` on success and `FALSE` on failure. +#' @export +gdal_verify <- function( + lib = NULL, + user_lib = FALSE, + python = TRUE, + quiet = FALSE +) { + abort_if_not_windows() + check_flag(user_lib) + check_flag(python) + check_flag(quiet) + check_optional_string(lib) + + lib <- resolve_gdalraster_lib(lib, user_lib) + package_dir <- file.path(lib, "gdalraster") + if (!dir.exists(package_dir)) { + if (!isTRUE(quiet)) { + cli::cli_alert_danger("{.pkg gdalraster} is not installed at {.path {package_dir}}.") + } + return(FALSE) + } + + work <- tempfile("gdal-verify-") + dir.create(work, recursive = TRUE, showWarnings = FALSE) + withr::defer(unlink(work, recursive = TRUE, force = TRUE)) + parquet <- file.path(work, "first-open.parquet") + run_python <- isTRUE(python) && python_is_ready(package_dir) + + fixture <- pkg_sys("extdata", "smoke.parquet") + if (!nzchar(fixture) || !file.exists(fixture)) { + if (!isTRUE(quiet)) { + cli::cli_alert_danger( + "Bundled Parquet smoke fixture is missing from {.pkg gdalraster.windows}." + ) + } + return(FALSE) + } + if (!file.copy(fixture, parquet, overwrite = TRUE)) { + if (!isTRUE(quiet)) { + cli::cli_alert_danger("Failed to stage the Parquet smoke fixture.") + } + return(FALSE) + } + + verify <- c( + sprintf("library(gdalraster, lib.loc = %s)", deparse(lib)), + "algorithms <- gdalraster::gdal_global_reg_names()", + "stopifnot(length(algorithms) > 0L)", + "formats <- gdalraster::gdal_formats()$short_name", + sprintf("required <- %s", deparse(.required_gdal_drivers)), + paste0( + "stopifnot(all(vapply(required, function(driver) ", + "any(grepl(driver, formats, ignore.case = TRUE)), logical(1))))" + ), + "stopifnot(isTRUE(gdalraster::has_geos()))", + "stopifnot(nzchar(gdalraster::srs_to_wkt('EPSG:4326')))", + sprintf("parquet <- %s", deparse(parquet)), + "info <- gdalraster::ogrinfo(parquet, cout = FALSE)", + "stopifnot(length(info) > 0L)", + if (run_python) { + c( + sprintf("gpkg <- %s", deparse(file.path(work, "verify.gpkg"))), + paste0( + "gdalraster::ogr_ds_create(", + "format = 'GPKG', dsn = gpkg, layer = 'points', ", + "geom_type = 'Point', fld_name = 'id', fld_type = 'OFTInteger', ", + "return_obj = FALSE)" + ), + "validator <- gdalraster::gdal_alg(cmd = 'driver gpkg validate')", + "validator$setArg('dataset', gpkg)", + "validator$setArg('full-check', TRUE)", + "stopifnot(isTRUE(validator$run()))", + "validator$output()" + ) + } else { + "cat('embedded_python=skipped\\n')" + }, + paste0( + "cat('algorithms=', length(algorithms), ", + "' drivers=', paste(required, collapse = ','), '\\n', sep = '')" + ) + ) + checked <- run_fresh_rscript(verify) + ok <- identical(checked$status, 0L) + + if (!isTRUE(quiet)) { + if (ok) { + cli::cli_alert_success("Fresh-process GDAL verification passed.") + if (!run_python && isTRUE(python)) { + cli::cli_alert_warning( + "Embedded-Python validation was skipped because no ready managed {.file .pth} file was found." + ) + } + } else { + cli::cli_alert_danger("Fresh-process GDAL verification failed.") + cli::cli_inform(c("x" = "{paste(checked$output, collapse = '\n')}")) + } + } + ok +} + +#' @keywords internal +#' @noRd +python_is_ready <- function(package_dir) { + target <- normalizePath( + file.path(package_dir, "python"), + winslash = "/", + mustWork = FALSE + ) + paths <- managed_python_pth_files() + targets <- vapply(paths, pth_target, character(1)) + any(!is.na(targets) & identical_paths(targets, target)) +} + +#' @keywords internal +#' @noRd +run_fresh_rscript <- function(code) { + script <- tempfile("gdal-verify-", fileext = ".R") + stdout <- tempfile("gdal-verify-", fileext = ".out") + stderr <- tempfile("gdal-verify-", fileext = ".err") + writeLines(code, script, useBytes = TRUE) + rscript <- file.path(R.home("bin"), "Rscript.exe") + if (!file.exists(rscript)) { + rscript <- Sys.which("Rscript") + } + + status <- withr::with_envvar( + c( + GDAL_DATA = NA, + PROJ_DATA = NA, + PROJ_LIB = NA, + PYTHONPATH = NA, + GDALRASTER_WINDOWS_GDAL_HOME = NA + ), + system2( + rscript, + args = c("--vanilla", shQuote(script)), + stdout = stdout, + stderr = stderr, + wait = TRUE + ) + ) + output <- c( + if (file.exists(stdout)) readLines(stdout, warn = FALSE) else character(), + if (file.exists(stderr)) readLines(stderr, warn = FALSE) else character() + ) + list(status = as.integer(status), output = output) +} diff --git a/R/gdalraster.windows-package.R b/R/gdalraster.windows-package.R index 2584f02..0cc9deb 100644 --- a/R/gdalraster.windows-package.R +++ b/R/gdalraster.windows-package.R @@ -1,7 +1,2 @@ #' @keywords internal "_PACKAGE" - -## usethis namespace: start -#' @importFrom rlang %||% -## usethis namespace: end -NULL diff --git a/R/manifest.R b/R/manifest.R new file mode 100644 index 0000000..b3be334 --- /dev/null +++ b/R/manifest.R @@ -0,0 +1,103 @@ +#' @keywords internal +#' @noRd +bundle_manifest_path <- function(gdal_home = default_gdal_home()) { + file.path(gdal_home, "MANIFEST.dcf") +} + +#' @keywords internal +#' @noRd +build_manifest_path <- function(pkg_dir) { + file.path(pkg_dir, "gdalraster.windows-build.dcf") +} + +#' @keywords internal +#' @noRd +read_manifest <- function(path) { + if (!file.exists(path)) { + return(NULL) + } + + manifest <- tryCatch( + read.dcf(path), + error = function(cnd) NULL + ) + if (is.null(manifest) || nrow(manifest) != 1L) { + return(NULL) + } + + stats::setNames(as.list(manifest[1L, , drop = TRUE]), colnames(manifest)) +} + +#' @keywords internal +#' @noRd +write_manifest <- function(fields, path) { + if (!is.list(fields) || is.null(names(fields)) || any(!nzchar(names(fields)))) { + cli::cli_abort( + "{.arg fields} must be a named list.", + call = rlang::caller_env() + ) + } + + values <- vapply( + fields, + function(value) paste(as.character(value), collapse = ", "), + character(1) + ) + dir.create(dirname(path), recursive = TRUE, showWarnings = FALSE) + write.dcf(as.data.frame(as.list(values), check.names = FALSE), file = path) + invisible(path) +} + +#' @keywords internal +#' @noRd +manifest_value <- function(manifest, field, default = NA_character_) { + if (is.null(manifest) || is.null(manifest[[field]]) || !nzchar(manifest[[field]])) { + return(default) + } + as.character(manifest[[field]]) +} + +#' @keywords internal +#' @noRd +bundle_manifest <- function( + tag, + gdal_version = NA_character_, + asset_name = NA_character_ +) { + list( + `Bundle-Tag` = tag, + `GDAL-Version` = gdal_version, + `Asset-Name` = asset_name, + `Installed-At` = format(Sys.time(), tz = "UTC", usetz = TRUE), + `Installer-Version` = pkg_version() + ) +} + +#' @keywords internal +#' @noRd +gdal_version_from_tag <- function(tag) { + if (!is.character(tag) || length(tag) != 1L || !nzchar(tag)) { + return(NA_character_) + } + sub("^gdal-v", "", tag) +} + +#' @keywords internal +#' @noRd +installed_bundle_manifest <- function(gdal_home = default_gdal_home()) { + read_manifest(bundle_manifest_path(gdal_home)) +} + +#' @keywords internal +#' @noRd +installed_build_manifest <- function(lib = default_gdalraster_lib()) { + read_manifest(build_manifest_path(file.path(lib, "gdalraster"))) +} + +#' @keywords internal +#' @noRd +build_is_current <- function(bundle, build) { + bundle_tag <- manifest_value(bundle, "Bundle-Tag") + build_tag <- manifest_value(build, "Bundle-Tag") + !is.na(bundle_tag) && !is.na(build_tag) && identical(bundle_tag, build_tag) +} diff --git a/R/startup_hook.R b/R/startup_hook.R deleted file mode 100644 index a24bf93..0000000 --- a/R/startup_hook.R +++ /dev/null @@ -1,124 +0,0 @@ -#' Build an .Rprofile hook snippet for bundled GDAL -#' -#' Returns R code that loads the bundled GDAL DLL before attaching -#' `gdalraster`, and prepends the custom `lib` path so `library(gdalraster)` -#' resolves to the source build installed by [install_gdalraster()]. -#' -#' @param gdal_home GDAL home directory. -#' @param lib Library path containing the custom gdalraster install. -#' -#' @return A single string containing R code. -#' @export -gdal_rprofile_snippet <- function( - gdal_home = default_gdal_home(), - lib = default_gdalraster_lib() -) { - abort_if_not_windows() - - if (!is.character(gdal_home) || length(gdal_home) != 1L || !nzchar(gdal_home)) { - cli::cli_abort( - "{.arg gdal_home} must be a single non-empty path.", - call = rlang::caller_env() - ) - } - if (!is.character(lib) || length(lib) != 1L || !nzchar(lib)) { - cli::cli_abort( - "{.arg lib} must be a single non-empty path.", - call = rlang::caller_env() - ) - } - - gdal_home <- normalizePath(gdal_home, winslash = "/", mustWork = FALSE) - lib <- normalizePath(lib, winslash = "/", mustWork = FALSE) - - paste( - c( - "if (.Platform$OS.type == \"windows\" && requireNamespace(\"gdalraster.windows\", quietly = TRUE)) {", - paste0(" try(gdalraster.windows::load_gdal_dll(gdal_home = \"", gdal_home, "\", quiet = TRUE), silent = TRUE)"), - paste0(" if (dir.exists(\"", lib, "\") && !(\"", lib, "\" %in% .libPaths())) {"), - paste0(" .libPaths(c(\"", lib, "\", .libPaths()))"), - " }", - "}" - ), - collapse = "\n" - ) -} - -#' Add or update an .Rprofile hook for bundled GDAL -#' -#' Writes a managed hook block into an `.Rprofile` file. The block loads the -#' bundled GDAL DLL before package attach and prepends the custom gdalraster -#' library path. -#' -#' @param rprofile Target `.Rprofile` path. -#' @param gdal_home GDAL home directory. -#' @param lib Library path containing the custom gdalraster install. -#' @param dry_run If `TRUE`, return the updated file contents without writing. -#' -#' @return Invisibly returns the updated `.Rprofile` text. -#' @export -add_gdal_rprofile_hook <- function( - rprofile = "~/.Rprofile", - gdal_home = default_gdal_home(), - lib = default_gdalraster_lib(), - dry_run = FALSE -) { - abort_if_not_windows() - - if (!is.character(rprofile) || length(rprofile) != 1L || !nzchar(rprofile)) { - cli::cli_abort( - "{.arg rprofile} must be a single non-empty path.", - call = rlang::caller_env() - ) - } - if (!is.logical(dry_run) || length(dry_run) != 1L || is.na(dry_run)) { - cli::cli_abort( - "{.arg dry_run} must be TRUE or FALSE.", - call = rlang::caller_env() - ) - } - - rprofile <- path.expand(rprofile) - dir.create(dirname(rprofile), recursive = TRUE, showWarnings = FALSE) - - start_marker <- "# >>> gdalraster.windows hook >>>" - end_marker <- "# <<< gdalraster.windows hook <<<" - hook <- gdal_rprofile_snippet(gdal_home = gdal_home, lib = lib) - block <- c(start_marker, hook, end_marker) - - lines <- if (file.exists(rprofile)) readLines(rprofile, warn = FALSE) else character() - start_idx <- match(start_marker, lines) - end_idx <- match(end_marker, lines) - - if (xor(is.na(start_idx), is.na(end_idx))) { - cli::cli_abort( - "Found incomplete managed hook block in {.path {rprofile}}.", - call = rlang::caller_env() - ) - } - if (!is.na(start_idx) && !is.na(end_idx) && end_idx <= start_idx) { - cli::cli_abort( - "Managed hook markers are out of order in {.path {rprofile}}.", - call = rlang::caller_env() - ) - } - - updated <- if (is.na(start_idx)) { - if (length(lines) > 0L && nzchar(lines[[length(lines)]])) { - c(lines, "", block) - } else { - c(lines, block) - } - } else { - head_lines <- if (start_idx > 1L) lines[seq_len(start_idx - 1L)] else character() - tail_lines <- if (end_idx < length(lines)) lines[seq.int(end_idx + 1L, length(lines))] else character() - c(head_lines, block, tail_lines) - } - - if (!isTRUE(dry_run)) { - writeLines(updated, con = rprofile, useBytes = TRUE) - cli::cli_alert_success("updated {.path {rprofile}} with gdal startup hook") - } - - invisible(paste(updated, collapse = "\n")) -} diff --git a/R/startup_status.R b/R/startup_status.R deleted file mode 100644 index f8c3761..0000000 --- a/R/startup_status.R +++ /dev/null @@ -1,103 +0,0 @@ -# startup state ----------------------------------------------------------------------------------------------- - -#' @keywords internal -#' @noRd -runtime_sitrep <- function() { - home <- default_gdal_home() - bin <- gdal_bin_dir(home) - dll <- gdal_dll_path(home) - lib <- default_gdalraster_lib() - has_custom <- dir.exists(file.path(lib, "gdalraster")) - - list( - gdal_home = home, - gdal_bin = bin, - gdal_dll = dll, - custom_lib = lib, - gdal_home_exists = dir.exists(home), - gdal_dll_exists = file.exists(dll), - custom_lib_exists = dir.exists(lib), - custom_gdalraster_exists = has_custom, - gdalraster_loaded = "gdalraster" %in% loadedNamespaces() - ) -} - -#' @keywords internal -#' @noRd -startup_sitrep_enabled <- function() { - opt <- getOption("gdalraster.windows.startup.sitrep", default = interactive()) - isTRUE(opt) -} - -#' @keywords internal -#' @noRd -startup_bootstrap <- function() { - st <- runtime_sitrep() - - # stale sibling dirs hold old runtime files a previous overwrite could not - # delete (they were mapped into that session); a fresh session no longer - # maps them, so this is the reliable point to reclaim the space - try(cleanup_stale_runtimes(st$gdal_home), silent = TRUE) - - if (st$gdal_home_exists && st$gdal_dll_exists) { - try(activate_gdal_runtime(gdal_home = st$gdal_home, preload = TRUE, quiet = TRUE), silent = TRUE) - } - - if (st$custom_lib_exists && !st$custom_lib %in% .libPaths()) { - .libPaths(c(st$custom_lib, .libPaths())) - } - - auto_load <- getOption("gdalraster.windows.auto_load_gdalraster", default = FALSE) - if (!isTRUE(auto_load)) { - return(invisible(runtime_sitrep())) - } - - st <- runtime_sitrep() - if (st$gdalraster_loaded) { - return(invisible(st)) - } - - if (st$custom_gdalraster_exists) { - try(base::library("gdalraster", character.only = TRUE, lib.loc = st$custom_lib), silent = TRUE) - } - - invisible(runtime_sitrep()) -} - -#' @keywords internal -#' @noRd -pkg_startup_msg <- function() { - st <- runtime_sitrep() - base <- paste0(pkg_name(), " v", pkg_version()) - - if (st$gdalraster_loaded && st$gdal_dll_exists) { - return(c( - base, - paste0("runtime: ", st$gdal_home), - paste0("gdal dll: ", basename(st$gdal_dll)), - paste0("gdalraster lib: ", st$custom_lib) - )) - } - - next_steps <- c(base, "streamline status: setup needed") - if (!st$gdal_dll_exists) { - next_steps <- c( - next_steps, - "run: gdalraster.windows::install_gdal_runtime()" - ) - } - if (!st$custom_gdalraster_exists) { - next_steps <- c( - next_steps, - "run: gdalraster.windows::install_gdalraster()" - ) - } - next_steps <- c( - next_steps, - "run: gdalraster.windows::load_gdal_dll()", - "run: gdalraster.windows::load_gdalraster()", - "check: gdalraster::gdal_global_reg_names()" - ) - - next_steps -} diff --git a/R/utils_pkg.R b/R/utils_pkg.R index 6cbca0e..d6ea5c9 100644 --- a/R/utils_pkg.R +++ b/R/utils_pkg.R @@ -88,21 +88,6 @@ gdal_dll_path <- function(gdal_home = default_gdal_home()) { dlls[[1]] } -#' @keywords internal -#' @noRd -loaded_runtime_dlls <- function(gdal_home = default_gdal_home()) { - prefix <- paste0( - tolower(normalizePath(gdal_home, winslash = "/", mustWork = FALSE)), - "/" - ) - paths <- vapply( - getLoadedDLLs(), - function(dll) normalizePath(dll[["path"]], winslash = "/", mustWork = FALSE), - character(1) - ) - unname(paths[startsWith(tolower(paths), prefix)]) -} - #' Unique sibling directory used to move aside runtime files that are still #' mapped into a process and therefore cannot be deleted (only renamed) #' @keywords internal @@ -143,45 +128,6 @@ cleanup_stale_runtimes <- function(gdal_home) { invisible(stale) } -#' Replace the installed gdalraster package's GDAL/PROJ data directories with -#' the bundle's share data. Upstream Makevars.win populates inst/gdal and -#' inst/proj from the Rtools static tree, so a source build compiled against -#' the bundle GDAL otherwise ships data files from a different GDAL/PROJ -#' version (upstream .onLoad activates them via GDAL_DATA and -#' proj_search_paths()) -#' @keywords internal -#' @noRd -sync_gdalraster_share_data <- function(lib, gdal_home = default_gdal_home()) { - pkg_dir <- file.path(lib, "gdalraster") - sources <- c( - gdal = gdal_share_gdal_dir(gdal_home), - proj = gdal_share_proj_dir(gdal_home) - ) - - synced <- character() - for (name in names(sources)) { - src <- sources[[name]] - if (!dir.exists(src)) { - cli::cli_alert_warning( - "bundle data directory not found, keeping packaged {.path {name}} data: {.path {src}}" - ) - next - } - - dest <- file.path(pkg_dir, name) - unlink(dest, recursive = TRUE, force = TRUE) - dir.create(dest, recursive = TRUE, showWarnings = FALSE) - file.copy( - from = list.files(src, full.names = TRUE), - to = dest, - recursive = TRUE - ) - synced <- c(synced, name) - } - - invisible(synced) -} - #' @keywords internal #' @noRd default_gdalraster_lib <- function() { @@ -226,7 +172,7 @@ abort_if_no_build_tools <- function(call = rlang::caller_env()) { cli::cli_abort( c( "No working Windows build toolchain (Rtools) was found.", - "x" = "{.fn install_gdalraster} compiles gdalraster from source, which requires Rtools.", + "x" = "{.fn gdal_build_gdalraster} compiles gdalraster from source, which requires Rtools.", "i" = "Install the Rtools version matching your R ({.val {as.character(getRversion())}}) from {.url https://cran.r-project.org/bin/windows/Rtools/} and restart R.", "i" = "Run {.code pkgbuild::check_build_tools(debug = TRUE)} for detection diagnostics." ), @@ -234,6 +180,37 @@ abort_if_no_build_tools <- function(call = rlang::caller_env()) { ) } +#' @keywords internal +#' @noRd +check_string <- function(x, arg = rlang::caller_arg(x), call = rlang::caller_env()) { + if (!is.character(x) || length(x) != 1L || is.na(x) || !nzchar(x)) { + cli::cli_abort("{.arg {arg}} must be a single non-empty string.", call = call) + } + invisible(x) +} + +#' @keywords internal +#' @noRd +check_optional_string <- function( + x, + arg = rlang::caller_arg(x), + call = rlang::caller_env() +) { + if (!is.null(x)) { + check_string(x, arg = arg, call = call) + } + invisible(x) +} + +#' @keywords internal +#' @noRd +check_flag <- function(x, arg = rlang::caller_arg(x), call = rlang::caller_env()) { + if (!is.logical(x) || length(x) != 1L || is.na(x)) { + cli::cli_abort("{.arg {arg}} must be {.val TRUE} or {.val FALSE}.", call = call) + } + invisible(x) +} + #' @keywords internal #' @noRd abort_if_missing_dir <- function(path, arg, call = rlang::caller_env()) { @@ -290,7 +267,7 @@ gitcreds_pat <- function() { rlang::try_fetch( { creds <- gitcreds::gitcreds_get(url = "https://github.com") - creds$password %||% "" + if (is.null(creds$password)) "" else creds$password }, error = function(cnd) "" ) diff --git a/R/zzz.R b/R/zzz.R index a2735ec..78f399b 100644 --- a/R/zzz.R +++ b/R/zzz.R @@ -1,76 +1,23 @@ -# ------------------------------------------------------------------------ -# -# Title : package onLoad and onAttach -# By : Jimmy Briggs -# Date : 2026-05-23 -# -# ------------------------------------------------------------------------ - -# environment ----------------------------------------------------------------------------------------------------- - #' @keywords internal #' @noRd -#' @importFrom rlang new_environment -.pkg_env <- rlang::new_environment() - -# initializers ---------------------------------------------------------------------------------------------------- - -#' @keywords internal -#' @noRd -#' @importFrom rlang on_load local_use_cli -rlang::on_load({ - init_pkg_env() - rlang::local_use_cli() -}) - -# onLoad ---------------------------------------------------------------------------------------------------------- - -#' @keywords internal -#' @noRd -#' @importFrom rlang run_on_load -.onLoad <- function(libname, pkgname) { - rlang::run_on_load() - - auto_bootstrap <- getOption("gdalraster.windows.auto_bootstrap", default = TRUE) - if (isTRUE(auto_bootstrap)) { - try(startup_bootstrap(), silent = TRUE) - } -} - -# onAttach -------------------------------------------------------------------------------------------------------- - -#' @keywords internal -#' @noRd -#' @importFrom cli cli_alert_info cli_inform cli_alert_warning cli_alert_info -#' @importFrom stats setNames .onAttach <- function(libname, pkgname) { - if (!startup_sitrep_enabled()) { - return(invisible(NULL)) + bundle <- installed_bundle_manifest() + build <- installed_build_manifest() + if (!build_is_current(bundle, build)) { + build <- installed_build_manifest(.libPaths()[[1L]]) } - - st <- runtime_sitrep() - msg <- pkg_startup_msg() - if (st$gdalraster_loaded && !st$custom_gdalraster_exists) { - cli::cli_alert_info(msg[[1]]) - if (length(msg) > 1L) { - cli::cli_inform(stats::setNames(as.list(msg[-1]), rep("i", length(msg) - 1L))) - } - cli::cli_alert_warning( - paste( - "gdalraster was already loaded before gdalraster.windows;", - "restart session for full bootstrap control." + if (build_is_current(bundle, build)) { + packageStartupMessage( + cli::format_inline( + "{.pkg gdalraster.windows} is ready; run {.fn gdal_verify} for a fresh-process check." + ) + ) + } else { + packageStartupMessage( + cli::format_inline( + "{.pkg gdalraster.windows} setup is incomplete; run {.fn gdal_sitrep} or {.fn gdal_setup}." ) ) - return(invisible(NULL)) - } - cli::cli_alert_info(msg[[1]]) - if (length(msg) > 1L) { - cli::cli_inform(stats::setNames(as.list(msg[-1]), rep("i", length(msg) - 1L))) } -} - -# onUnload -------------------------------------------------------------------------------------------------------- - -.onUnload <- function(libpath) { - # rlang::try_fetch({ ... }, error = function(e) NULL) + invisible(NULL) } diff --git a/README.md b/README.md index 8a690c3..40eb5ba 100644 --- a/README.md +++ b/README.md @@ -1,332 +1,109 @@ -# gdalraster.windows gdalraster.windows website +# gdalraster.windows - [![R CMD CHECK](https://github.com/jimbrig/gdalraster.windows/actions/workflows/check.yml/badge.svg)](https://github.com/jimbrig/gdalraster.windows/actions/workflows/check.yml) [![Build GDAL (Windows)](https://github.com/jimbrig/gdalraster.windows/actions/workflows/build.yml/badge.svg)](https://github.com/jimbrig/gdalraster.windows/actions/workflows/build.yml) -[![E2E Runtime Verification](https://github.com/jimbrig/gdalraster.windows/actions/workflows/e2e.yml/badge.svg)](https://github.com/jimbrig/gdalraster.windows/actions/workflows/e2e.yml) -[![Build Package Website](https://github.com/jimbrig/gdalraster.windows/actions/workflows/pkgdown.yml/badge.svg)](https://github.com/jimbrig/gdalraster.windows/actions/workflows/pkgdown.yml) -[![Automate Changelog](https://github.com/jimbrig/gdalraster.windows/actions/workflows/changelog.yml/badge.svg)](https://github.com/jimbrig/gdalraster.windows/actions/workflows/changelog.yml) - +[![E2E](https://github.com/jimbrig/gdalraster.windows/actions/workflows/e2e.yml/badge.svg)](https://github.com/jimbrig/gdalraster.windows/actions/workflows/e2e.yml) -> [!NOTE] -> Self-contained [GDAL](https://gdal.org/) runtime tooling for Windows. - -`gdalraster.windows` is an R package with companion CI scripts that build and -publish a Windows GDAL runtime bundle. - -The package helps you: - -- install that runtime locally -- build [`gdalraster`](https://firelab.github.io/gdalraster/) from source against it -- load and verify `gdalraster` in a Windows session - -By default, installs are isolated under package-managed user directories. +`gdalraster.windows` builds a self-contained +[`gdalraster`](https://firelab.github.io/gdalraster/) package against a modern +GDAL runtime published by this repository. -Full documentation is available at -[docs.jimbrig.com/gdalraster.windows](https://docs.jimbrig.com/gdalraster.windows/). +The installed `gdalraster` vendors GDAL and dependency DLLs, matching GDAL/PROJ +data, and `osgeo_utils`. Later sessions require no activation helper, +`.Rprofile` hook, `PATH` edit, or GDAL environment variables. -Latest GDAL runtime release: -[gdal-v3.13.1](https://github.com/jimbrig/gdalraster.windows/releases/tag/gdal-v3.13.1) +## Requirements -## Prerequisites +- Windows with R. +- [Rtools](https://cran.r-project.org/bin/windows/Rtools/) matching R. -- Windows with R installed -- [Rtools](https://cran.r-project.org/bin/windows/Rtools/) matching your R version — `install_gdalraster()` compiles gdalraster from source against the bundled GDAL, which is the one step the prebuilt runtime cannot eliminate (the function checks for a toolchain up front and tells you if one is missing) +## Setup -## Installation +To install the self-contained build into the regular user library: ```r pak::pak("jimbrig/gdalraster.windows") +gdalraster.windows::gdal_setup(user_lib = TRUE) ``` -## Quick Start - -```r -# 1) install runtime bundle (defaults to latest release asset) -gdalraster.windows::install_gdal_runtime() - -# 2) build gdalraster from source against that runtime -gdalraster.windows::install_gdalraster() - -# 3) load and verify -library(gdalraster.windows) -gdalraster::gdal_global_reg_names() -``` - -## Offline / Air-Gapped Installation - -`install_gdal_runtime()` downloads the runtime bundle from GitHub Releases by -default. On machines without network access (or to pin an exact asset), pass a -local zip directly: - -```r -# 1) download the release asset on a connected machine: -# https://github.com/jimbrig/gdalraster.windows/releases -# 2) transfer to the target machine -# 3) install from the local zip -gdalraster.windows::install_gdal_runtime( - local_zip = "C:/Downloads/gdal-ucrt64-v3.13.1-windows-x64.zip" -) -``` - -A `fallback_zip` argument is also supported: when a release download fails and -a fallback zip exists, it is installed instead. - -## Common Flows - -If runtime and custom `gdalraster` install are already present: +Then, in any fresh session: ```r -library(gdalraster.windows) library(gdalraster) gdalraster::gdal_global_reg_names() ``` -Explicit load flow is also supported: +The default remains non-destructive and targets an isolated managed library: ```r -gdalraster.windows::load_gdal_dll() -gdalraster.windows::load_gdalraster() -gdalraster::gdal_global_reg_names() +gdalraster.windows::gdal_setup() ``` -Runtime verification helper: +Pass `user_lib = TRUE` when plain `library(gdalraster)` discovery is required. + +## Status, verification, and updates ```r -gdalraster.windows::verify_gdalraster_runtime() +gdalraster.windows::gdal_sitrep(user_lib = TRUE) +gdalraster.windows::gdal_verify(user_lib = TRUE) +gdalraster.windows::gdal_update(user_lib = TRUE) ``` -## What This Repository Contains - -- An R helper package (`gdalraster.windows`) -- A Windows CI build pipeline for GDAL - ([`.github/workflows/build.yml`](https://github.com/jimbrig/gdalraster.windows/blob/main/.github/workflows/build.yml)) -- Build and bundle scripts: - - [`tools/build_gdal.sh`](https://github.com/jimbrig/gdalraster.windows/blob/main/tools/build_gdal.sh) - - [`tools/collect_dlls.sh`](https://github.com/jimbrig/gdalraster.windows/blob/main/tools/collect_dlls.sh) +Verification runs in fresh processes and checks: -The package and build scripts are designed to work together. +- the GDAL Algorithm API registry; +- Arrow, Parquet, HDF5, and netCDF drivers; +- GEOS and CRS resolution; +- a first Parquet dataset open; and +- `gdal driver gpkg validate` when embedded Python is ready. -### Building a new GDAL version - -The runtime bundle is reproducible entirely from this repository. To build -and publish a new GDAL release, push a tag (or dispatch the workflow with a -`gdal_version` input): - -```bash -git tag gdal-v3.14.0 && git push origin gdal-v3.14.0 -``` - -The tag drives the GDAL source checkout, cache key, asset name, and release -tag. See the -[Architecture article](https://docs.jimbrig.com/gdalraster.windows/articles/architecture.html) -for the full procedure, including local (non-CI) reproduction. - -## Optional startup hook (`.Rprofile`) +## Offline installation ```r -# writes a managed hook block that loads the GDAL DLL and prepends -# the custom gdalraster library path at session startup -gdalraster.windows::add_gdal_rprofile_hook() +gdalraster.windows::gdal_setup( + user_lib = TRUE, + local_zip = "C:/Downloads/gdal-bundle-v3.13.2-windows-x64.zip" +) ``` -## Why This Exists - -This repository started from practical Windows failures where -`gdalraster::gdal_global_reg_names()` could be empty under some toolchain -states. It now provides a maintained runtime path that is isolated by default. - -## Technical Architecture - -This section is the technical rationale for the current design. - -### 1) Root problem: static registration + MXE/static builds - -GDAL's Algorithm API uses static C++ registration. Under some Windows build -states (notably specific Rtools/MXE combinations), the top-level algorithm -registry has been observed to load but return no names. In practice this means -`gdalraster::gdal_global_reg_names()` can return `character(0)` even when GDAL -is present. - -This project solves that by controlling both the GDAL build profile and runtime -loading path, then rebuilding `gdalraster` against that known runtime. - -### 2) Toolchain stack in plain terms - -- **[MinGW-w64](https://www.mingw-w64.org/)**: GCC-based Windows compiler - toolchain for native `.exe`/`.dll`. -- **[MSYS2](https://www.msys2.org/)**: package manager + shell environment - used to assemble toolchains and dependencies (`pacman`). -- **[UCRT64](https://www.msys2.org/docs/environments/)**: MSYS2 toolchain - target using Microsoft's Universal CRT. -- **[Rtools45](https://cran.r-project.org/bin/windows/Rtools/rtools45/rtools.html)**: - Windows R package build toolchain, also UCRT-based. - -The practical requirement is to keep compile/runtime toolchains compatible -(MinGW/UCRT alignment) to avoid C/C++ runtime and ABI mismatch problems. - -### 3) Static vs dynamic linking in this repository - -- Some runtime pieces are linked statically (for portability of GCC runtime bits). -- GDAL itself is delivered as a shared runtime DLL (`libgdal-*.dll`) with - transitive dependencies bundled alongside it. - -In other words: this project is not "single-file static GDAL", it is a -self-contained runtime bundle with controlled dependency closure. +Bundle assets are published at +. -### 4) C++ ABI compatibility (why source rebuild is required) +## Design -`gdalraster` binds to GDAL C++ APIs via compiled code. Even when headers match, -ABI mismatches can break at runtime if binaries are built with incompatible -compiler/runtime combinations. - -That is why this package installs `gdalraster` from source against the bundled -GDAL headers/import libs rather than assuming an arbitrary prebuilt binary is -compatible. - -### 5) Key CMake/linker flags used and why - -Current build uses flags in -[`tools/build_gdal.sh`](https://github.com/jimbrig/gdalraster.windows/blob/main/tools/build_gdal.sh), -including: - -- `-DGDAL_USE_MUPARSER=ON` for - [muparser](https://beltoforion.de/en/muparser/)-enabled algorithm - functionality -- `-DGDAL_HIDE_INTERNAL_SYMBOLS=ON` to reduce export-surface pressure on Windows -- `-Wl,--kill-at` for Windows/MinGW export naming behavior -- `-static-libgcc -static-libstdc++` and static `winpthread` handling to reduce - external runtime fragility - -These flags are practical stability choices from observed Windows build/runtime -behavior, not arbitrary tuning. - -### 6) Why `collect_dlls.sh` is essential - -Building `libgdal-*.dll` is not sufficient by itself. Runtime success depends on -all non-Windows transitive DLL dependencies being present. - -[`tools/collect_dlls.sh`](https://github.com/jimbrig/gdalraster.windows/blob/main/tools/collect_dlls.sh) -performs recursive dependency inspection with -[ntldd](https://github.com/LRN/ntldd) (`ntldd -R`), copies required UCRT64 -DLLs into the bundle, and fails when unresolved external non-Windows -dependencies remain. - -### 7) Windows DLL load order and preloading - -Compile-time link success does not guarantee runtime load success. Windows still -needs to resolve `libgdal-*.dll` and its dependency tree in the active process. - -`activate_gdal_runtime()` addresses this by: - -- prepending bundle `bin/` to `PATH` -- setting GDAL/PROJ data env vars -- prepending bundle `python/` to `PYTHONPATH` (see section 9) -- optionally preloading `libgdal-*.dll` with `dyn.load(..., local = FALSE, now = TRUE)` - -This is why explicit runtime activation exists in addition to source builds. - -### 8) GDAL/PROJ data directories - -GDAL and PROJ require runtime data files (`share/gdal`, `share/proj`). -Without these, CRS and related functionality can fail even when DLL loading -succeeds. - -`activate_gdal_runtime()` sets: - -- `GDAL_DATA` -- `PROJ_LIB` -- `PROJ_DATA` - -from the installed bundle when available. - -### 9) Embedded Python utilities (`osgeo_utils`) - -Some GDAL CLI algorithms are implemented in Python rather than C++. For -example, `gdal driver gpkg validate` is a thin C++ entry point in `libgdal` -that embeds a CPython interpreter at runtime: GDAL locates a `python.exe` on -`PATH`, dynamically loads the matching `libpython` DLL, calls -`Py_Initialize()`, and imports `osgeo_utils.samples.validate_gpkg`. - -`osgeo_utils` is the pure-Python package shipped by GDAL's -[`gdal-utils`](https://github.com/OSGeo/gdal/tree/master/swig/python/gdal-utils) -distribution (`swig/python/gdal-utils/` in the GDAL source tree). Because it -contains no compiled extension modules, it has no CPython ABI coupling — any -embedded interpreter version can import it. - -The runtime bundle ships this package under `python/osgeo_utils`, -version-locked to the built GDAL tag. `activate_gdal_runtime()` prepends -`/python` to `PYTHONPATH` (session-scoped; never persisted to user -or machine environment) so the embedded interpreter can resolve it. -`PYTHONPATH` is read at `Py_Initialize()`, which `libgdal` triggers lazily on -first use of an embedded-python algorithm, so activation-time configuration is -early enough. - -Without this, such algorithms fail with: +The package uses the downloaded bundle as a build-time SDK. After compiling +`gdalraster`, it stages and vendors: ```text -GDAL FAILURE 1: ... ModuleNotFoundError: No module named 'osgeo_utils' +gdalraster/ + libs/x64/ # gdalraster.dll + GDAL dependency closure + gdal/ # matching GDAL data + proj/ # matching PROJ data + python/osgeo_utils/ # embedded-Python algorithms + gdalraster.windows-build.dcf ``` -Note: the compiled `osgeo` SWIG bindings (`from osgeo import gdal`) are -intentionally **not** built or bundled (`BUILD_PYTHON_BINDINGS` stays off — -no Python/SWIG in the build environment). They would pin the bundle to a -single CPython version/ABI. The Python-implemented validators degrade -gracefully without them (e.g. `validate_gpkg` skips only tiled gridded -coverage checks). - -### 10) Compile-time paths vs runtime paths - -These are separate concerns: - -- **Compile-time**: headers/libs via Makevars (`PKG_CPPFLAGS`, `PKG_LIBS`) -- **Runtime**: DLL resolution via process environment and loader state - -This package scopes compile-time settings to install calls (`withr`), then -manages runtime activation separately for session reliability. - -### 11) Optional `.Rprofile` startup hook - -For users who want persistence, `add_gdal_rprofile_hook()` writes a managed -startup block that can load runtime context early in each session. - -This is optional by design; default behavior stays non-destructive and local. - -## Upstream Context - -- [firelab/gdalraster#826](https://github.com/firelab/gdalraster/issues/826) — algorithm-registry failure mode on Windows -- [firelab/gdalraster#858](https://github.com/firelab/gdalraster/issues/858) — enabling muparser in the Rtools GDAL build -- [firelab/gdalraster#982](https://github.com/firelab/gdalraster/issues/982) — working Windows workflow this package productized -- [OSGeo/gdal#13592](https://github.com/OSGeo/gdal/pull/13592) — upstream registration fix (GDAL 3.12.2) -- [Rtools45 news](https://cran.r-project.org/bin/windows/Rtools/rtools45/news.html) — muparser added to the Rtools GDAL build in release 6768 +The SDK has its own `MANIFEST.dcf`. Comparing bundle tags lets +`gdal_sitrep()` detect a stale build after a runtime update. -## Package Guide +Embedded Python is provisioned through a managed `.pth` in system CPython's +`site-packages`; the package never sets `PYTHONPATH`. -- [Getting Started](https://docs.jimbrig.com/gdalraster.windows/articles/getting-started.html) — install, load, and verify the full workflow -- [Runtime Guide](https://docs.jimbrig.com/gdalraster.windows/articles/runtime-guide.html) — session activation, configuration, source builds, and startup hooks -- [Architecture](https://docs.jimbrig.com/gdalraster.windows/articles/architecture.html) — why the package exists and how the runtime bundle is built -- [Troubleshooting](https://docs.jimbrig.com/gdalraster.windows/articles/troubleshooting.html) — common failure modes and fixes -- [Function reference](https://docs.jimbrig.com/gdalraster.windows/reference/index.html) +## Repository responsibilities -## Testing +- `.github/workflows/build.yml`, `tools/build_gdal.sh`, and + `tools/collect_dlls.sh` build and publish the GDAL bundle. +- The R package installs the SDK, builds and vendors `gdalraster`, provisions + Python, and verifies the user workflow. +- `.github/workflows/e2e.yml` proves fresh-session self-containment. +- `.github/workflows/edge-cases.yml` exercises dirty-machine failure modes. -Run fast tests: - -```r -testthat::test_dir("tests/testthat") -``` - -Run clean-room isolation checks: - -```r -testthat::test_file("tests/testthat/test-e2e-clean-room.R") -``` - -Run full end-to-end clean-room flow (opt-in): - -```powershell -$env:GDALRASTER_WINDOWS_RUN_E2E="true" -Rscript -e "testthat::test_file('tests/testthat/test-e2e-clean-room.R')" -``` +See the published +[Getting Started](https://docs.jimbrig.com/gdalraster.windows/articles/getting-started.html), +[Runtime Guide](https://docs.jimbrig.com/gdalraster.windows/articles/runtime-guide.html), +[Architecture](https://docs.jimbrig.com/gdalraster.windows/articles/architecture.html), +and +[Troubleshooting](https://docs.jimbrig.com/gdalraster.windows/articles/troubleshooting.html) +articles for details. diff --git a/_pkgdown.yml b/_pkgdown.yml index f1e86e1..d3bcb18 100644 --- a/_pkgdown.yml +++ b/_pkgdown.yml @@ -11,7 +11,7 @@ template: home: title: gdalraster.windows - description: Installs and activates a self-contained GDAL runtime & gdalraster package on Windows. + description: Builds and verifies a self-contained vendored gdalraster package on Windows. navbar: bg: "#2b4a2b" @@ -34,22 +34,18 @@ navbar: href: articles/troubleshooting.html reference: - - title: Runtime Setup - desc: Setup the necessary runtime environment for gdalraster on Windows. + - title: Setup and Maintenance + desc: Install, update, inspect, verify, and remove managed resources. contents: - - gdal_home - - configure_gdal_home - - install_gdal_runtime - - activate_gdal_runtime - - load_gdal_dll - - title: gdalraster Integration - desc: Integrate gdalraster with the GDAL runtime on Windows. - contents: - - install_gdalraster - - load_gdalraster - - verify_gdalraster_runtime - - title: Startup Hooks - desc: Configure R to automatically load the GDAL runtime and gdalraster package on startup. + - gdal_setup + - gdal_update + - gdal_sitrep + - gdal_verify + - gdal_uninstall + - title: Plumbing + desc: Install the build SDK, compile the vendored package, and provision Python. contents: - - gdal_rprofile_snippet - - add_gdal_rprofile_hook + - gdal_home + - gdal_install_runtime + - gdal_build_gdalraster + - gdal_enable_python diff --git a/dev/scripts/local_release_verify.R b/dev/scripts/local_release_verify.R new file mode 100644 index 0000000..1309e37 --- /dev/null +++ b/dev/scripts/local_release_verify.R @@ -0,0 +1,93 @@ +# non-interactive local verification for 0.4.0 + gdal-v3.13.2 +options(warn = 1) +stopifnot(!interactive()) + +library(gdalraster.windows) + +cat("== gdal_setup(user_lib=TRUE, tag=gdal-v3.13.2) ==\n") +gdal_setup( + user_lib = TRUE, + tag = "gdal-v3.13.2", + force = TRUE, + update = TRUE, + verify = TRUE +) + +cat("== sitrep ==\n") +print(gdal_sitrep(user_lib = TRUE, network = FALSE)) + +cat("== fresh-session functional checks ==\n") +script <- tempfile(fileext = ".R") +writeLines( + c( + "stopifnot(!interactive())", + "library(gdalraster)", + "ver <- gdalraster::gdal_version()[[1]]", + "cat('GDAL:', ver, '\n')", + "stopifnot(grepl('3\\\\.13\\\\.2', ver))", + "algs <- gdalraster::gdal_global_reg_names()", + "cat('algorithms:', length(algs), '\n')", + "stopifnot(length(algs) > 0L)", + "fmts <- gdalraster::gdal_formats()$short_name", + "for (d in c('Arrow', 'Parquet', 'HDF5', 'netCDF')) {", + " stopifnot(any(grepl(d, fmts, ignore.case = TRUE)))", + " cat('driver ok:', d, '\n')", + "}", + "stopifnot(isTRUE(gdalraster::has_geos()))", + "stopifnot(nzchar(gdalraster::srs_to_wkt('EPSG:4326')))", + "fixture <- system.file('extdata', 'smoke.parquet', package = 'gdalraster.windows')", + "stopifnot(nzchar(fixture), file.exists(fixture))", + "pq <- tempfile(fileext = '.parquet')", + "file.copy(fixture, pq, overwrite = TRUE)", + "layers <- gdalraster::ogr_ds_layer_names(pq)", + "cat('parquet layers:', paste(layers, collapse = ','), '\n')", + "stopifnot(length(layers) >= 1L)", + "gpkg <- tempfile(fileext = '.gpkg')", + "gdalraster::ogr_ds_create(", + " format = 'GPKG', dsn = gpkg, layer = 'points',", + " geom_type = 'Point', fld_name = 'id', fld_type = 'OFTInteger',", + " return_obj = FALSE", + ")", + "validator <- gdalraster::gdal_alg(cmd = 'driver gpkg validate')", + "validator$setArg('dataset', gpkg)", + "validator$setArg('full-check', TRUE)", + "stopifnot(isTRUE(validator$run()))", + "cat('gpkg validate: ok\n')", + "cat('FUNCTIONAL_OK\n')" + ), + script +) +status <- system2( + file.path(R.home("bin"), "Rscript.exe"), + args = c("--vanilla", script) +) +stopifnot(identical(as.integer(status), 0L)) + +cat("== TLS-noisy first parquet open ==\n") +tls <- tempfile(fileext = ".R") +writeLines( + c( + "stopifnot(!interactive())", + "for (pkg in c('httpuv', 'later', 'gifski', 'nanoparquet')) {", + " if (!requireNamespace(pkg, quietly = TRUE)) {", + " utils::install.packages(pkg, repos = 'https://cloud.r-project.org')", + " }", + " loadNamespace(pkg)", + "}", + "stopifnot(all(c('httpuv', 'later', 'gifski', 'nanoparquet') %in% names(getLoadedDLLs())))", + "pq <- tempfile(fileext = '.parquet')", + "nanoparquet::write_parquet(data.frame(id = 1L, value = 'tls'), pq)", + "library(gdalraster)", + "layers <- gdalraster::ogr_ds_layer_names(pq)", + "stopifnot(length(layers) == 1L)", + "cat('TLS_NOISY_OK algorithms=', length(gdalraster::gdal_global_reg_names()), '\n', sep = '')" + ), + tls +) +tls_status <- system2( + file.path(R.home("bin"), "Rscript.exe"), + args = c("--vanilla", tls) +) +stopifnot(identical(as.integer(tls_status), 0L)) + +cat("== LOCAL_RELEASE_VERIFY_OK ==\n") diff --git a/inst/extdata/smoke.parquet b/inst/extdata/smoke.parquet new file mode 100644 index 0000000..2eeb30e Binary files /dev/null and b/inst/extdata/smoke.parquet differ diff --git a/man/activate_gdal_runtime.Rd b/man/activate_gdal_runtime.Rd deleted file mode 100644 index 3f21c25..0000000 --- a/man/activate_gdal_runtime.Rd +++ /dev/null @@ -1,37 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/gdal_runtime.R -\name{activate_gdal_runtime} -\alias{activate_gdal_runtime} -\title{Activate GDAL runtime for current R session} -\usage{ -activate_gdal_runtime( - gdal_home = default_gdal_home(), - preload = TRUE, - quiet = FALSE -) -} -\arguments{ -\item{gdal_home}{GDAL home directory.} - -\item{preload}{Whether to preload \verb{libgdal-*.dll}.} - -\item{quiet}{Suppress informational CLI output.} -} -\value{ -Invisibly returns a list with configured paths. -} -\description{ -Prepends runtime paths, sets GDAL/PROJ env vars, and preloads GDAL DLL. -} -\details{ -When the runtime bundle contains a \verb{python/} directory (pure-python -\code{osgeo_utils} package from GDAL's \code{gdal-utils} distribution), it is -prepended to \code{PYTHONPATH} so GDAL algorithms that embed Python at runtime -(e.g. \verb{gdal driver gpkg validate}) can import it. This is session-scoped -and does not modify machine or user environment variables. - -When \code{preload = TRUE} and the GDAL DLL cannot be loaded (most commonly -because a dependency DLL is missing), activation fails with an error -rather than deferring the failure to \code{library(gdalraster)}, where the -Windows loader reports only a generic "module could not be found". -} diff --git a/man/add_gdal_rprofile_hook.Rd b/man/add_gdal_rprofile_hook.Rd deleted file mode 100644 index b950015..0000000 --- a/man/add_gdal_rprofile_hook.Rd +++ /dev/null @@ -1,30 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/startup_hook.R -\name{add_gdal_rprofile_hook} -\alias{add_gdal_rprofile_hook} -\title{Add or update an .Rprofile hook for bundled GDAL} -\usage{ -add_gdal_rprofile_hook( - rprofile = "~/.Rprofile", - gdal_home = default_gdal_home(), - lib = default_gdalraster_lib(), - dry_run = FALSE -) -} -\arguments{ -\item{rprofile}{Target \code{.Rprofile} path.} - -\item{gdal_home}{GDAL home directory.} - -\item{lib}{Library path containing the custom gdalraster install.} - -\item{dry_run}{If \code{TRUE}, return the updated file contents without writing.} -} -\value{ -Invisibly returns the updated \code{.Rprofile} text. -} -\description{ -Writes a managed hook block into an \code{.Rprofile} file. The block loads the -bundled GDAL DLL before package attach and prepends the custom gdalraster -library path. -} diff --git a/man/configure_gdal_home.Rd b/man/configure_gdal_home.Rd deleted file mode 100644 index 5917567..0000000 --- a/man/configure_gdal_home.Rd +++ /dev/null @@ -1,20 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/gdal_runtime.R -\name{configure_gdal_home} -\alias{configure_gdal_home} -\title{Configure GDAL home for current session} -\usage{ -configure_gdal_home(path, mode = c("option", "env")) -} -\arguments{ -\item{path}{GDAL home directory path.} - -\item{mode}{Either \code{"option"} or \code{"env"}.} -} -\value{ -Invisibly returns the normalized GDAL home path. -} -\description{ -Sets GDAL home for this session using either an R option or environment -variable. This does not write to user profile files. -} diff --git a/man/gdal_build_gdalraster.Rd b/man/gdal_build_gdalraster.Rd new file mode 100644 index 0000000..69f5b3e --- /dev/null +++ b/man/gdal_build_gdalraster.Rd @@ -0,0 +1,52 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/gdal_build.R +\name{gdal_build_gdalraster} +\alias{gdal_build_gdalraster} +\title{Build a self-contained gdalraster package} +\usage{ +gdal_build_gdalraster( + gdal_home = default_gdal_home(), + lib = NULL, + user_lib = FALSE, + source_tarball = NULL, + repo = .gdalraster_repo, + ref = "HEAD", + upgrade = FALSE, + repos = getOption("repos"), + force = FALSE, + enable_python = TRUE +) +} +\arguments{ +\item{gdal_home}{Installed GDAL build runtime.} + +\item{lib}{Destination library. The default is an isolated package-managed +library.} + +\item{user_lib}{Install into \code{.libPaths()[1]}. This is destructive when an +existing \code{gdalraster} is installed there and requires \code{force = TRUE} in +non-interactive sessions.} + +\item{source_tarball}{Optional local \code{gdalraster} source tarball.} + +\item{repo}{Upstream source repository.} + +\item{ref}{Git reference used for the source archive.} + +\item{upgrade}{Install missing R dependencies before compiling.} + +\item{repos}{CRAN-like repositories used when \code{upgrade = TRUE}.} + +\item{force}{Replace an existing \code{gdalraster} package.} + +\item{enable_python}{Provision the managed embedded-Python \code{.pth} file after +installation when possible.} +} +\value{ +Invisibly, the destination library. +} +\description{ +Compiles \code{gdalraster} against the managed GDAL SDK, vendors the bundle's +DLL dependency closure, GDAL/PROJ data, and pure-Python utilities into the +installed package, then records build provenance. +} diff --git a/man/gdal_enable_python.Rd b/man/gdal_enable_python.Rd new file mode 100644 index 0000000..28a0ae0 --- /dev/null +++ b/man/gdal_enable_python.Rd @@ -0,0 +1,32 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/gdal_python.R +\name{gdal_enable_python} +\alias{gdal_enable_python} +\title{Enable GDAL embedded-Python utilities} +\usage{ +gdal_enable_python( + lib = default_gdalraster_lib(), + python = NULL, + site_packages = NULL, + quiet = FALSE +) +} +\arguments{ +\item{lib}{Library containing the self-contained \code{gdalraster} package.} + +\item{python}{Optional path to the CPython executable GDAL embeds.} + +\item{site_packages}{Optional explicit \code{site-packages} directory.} + +\item{quiet}{Suppress status messages.} +} +\value{ +Invisibly, the \code{.pth} path, or \code{NULL} when no system CPython can be +located. +} +\description{ +Writes a managed \code{.pth} file into the system CPython \code{site-packages} +directory. The file points to the pure-Python \code{osgeo_utils} vendored inside +the installed \code{gdalraster} package. This does not modify \code{PYTHONPATH} and +does not affect isolated virtual environments. +} diff --git a/man/gdal_home.Rd b/man/gdal_home.Rd index 6633793..703733f 100644 --- a/man/gdal_home.Rd +++ b/man/gdal_home.Rd @@ -2,21 +2,15 @@ % Please edit documentation in R/gdal_runtime.R \name{gdal_home} \alias{gdal_home} -\title{Resolve active GDAL home path} +\title{Resolve the managed GDAL runtime directory} \usage{ gdal_home() } \value{ -A single string path. +A single path. } \description{ -Returns the currently configured GDAL runtime home used by this package. -} -\details{ -Resolution order: -\enumerate{ -\item \code{options(gdalraster.windows.gdal_home = "...")} -\item \code{GDALRASTER_WINDOWS_GDAL_HOME} environment variable -\item package-managed user data directory (\code{tools::R_user_dir()}) -} +Resolution order is the \code{gdalraster.windows.gdal_home} option, the +\code{GDALRASTER_WINDOWS_GDAL_HOME} environment variable, then the package-managed +user data directory. } diff --git a/man/gdal_install_runtime.Rd b/man/gdal_install_runtime.Rd new file mode 100644 index 0000000..75fbae8 --- /dev/null +++ b/man/gdal_install_runtime.Rd @@ -0,0 +1,45 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/gdal_runtime.R +\name{gdal_install_runtime} +\alias{gdal_install_runtime} +\title{Install a self-contained GDAL build runtime} +\usage{ +gdal_install_runtime( + repo = .bundle_repo, + tag = "latest", + asset_pattern = .bundle_asset_pattern, + gdal_home = default_gdal_home(), + force = FALSE, + local_zip = NULL, + fallback_zip = NULL +) +} +\arguments{ +\item{repo}{GitHub repository that publishes bundle releases.} + +\item{tag}{Bundle release tag or \code{"latest"}.} + +\item{asset_pattern}{Regular expression selecting a bundle zip asset.} + +\item{gdal_home}{Destination runtime directory.} + +\item{force}{Reinstall an existing runtime.} + +\item{local_zip}{Optional local bundle zip. This takes precedence over a +release download.} + +\item{fallback_zip}{Optional local zip used if release resolution or download +fails.} +} +\value{ +Invisibly, the installed runtime directory. +} +\description{ +Installs a release bundle used to compile \code{\link[=gdal_build_gdalraster]{gdal_build_gdalraster()}}. The +installed runtime is a build-time SDK; packages produced by +\code{\link[=gdal_build_gdalraster]{gdal_build_gdalraster()}} vendor everything needed at run time. +} +\details{ +The installer is idempotent. When the requested bundle tag is already +recorded in \code{MANIFEST.dcf}, installation is skipped unless \code{force = TRUE}. +} diff --git a/man/gdal_rprofile_snippet.Rd b/man/gdal_rprofile_snippet.Rd deleted file mode 100644 index 42c2e9a..0000000 --- a/man/gdal_rprofile_snippet.Rd +++ /dev/null @@ -1,24 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/startup_hook.R -\name{gdal_rprofile_snippet} -\alias{gdal_rprofile_snippet} -\title{Build an .Rprofile hook snippet for bundled GDAL} -\usage{ -gdal_rprofile_snippet( - gdal_home = default_gdal_home(), - lib = default_gdalraster_lib() -) -} -\arguments{ -\item{gdal_home}{GDAL home directory.} - -\item{lib}{Library path containing the custom gdalraster install.} -} -\value{ -A single string containing R code. -} -\description{ -Returns R code that loads the bundled GDAL DLL before attaching -\code{gdalraster}, and prepends the custom \code{lib} path so \code{library(gdalraster)} -resolves to the source build installed by \code{\link[=install_gdalraster]{install_gdalraster()}}. -} diff --git a/man/gdal_setup.Rd b/man/gdal_setup.Rd new file mode 100644 index 0000000..c9dde00 --- /dev/null +++ b/man/gdal_setup.Rd @@ -0,0 +1,48 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/gdal_setup.R +\name{gdal_setup} +\alias{gdal_setup} +\title{Set up a self-contained gdalraster installation} +\usage{ +gdal_setup( + lib = NULL, + user_lib = FALSE, + update = FALSE, + force = FALSE, + tag = "latest", + local_zip = NULL, + fallback_zip = NULL, + source_tarball = NULL, + upgrade = FALSE, + verify = TRUE +) +} +\arguments{ +\item{lib}{Destination library for \code{gdalraster}.} + +\item{user_lib}{Use \code{.libPaths()[1]} instead of the isolated managed library.} + +\item{update}{Upgrade the runtime to the requested/latest bundle and rebuild.} + +\item{force}{Reinstall and rebuild even when provenance is current.} + +\item{tag}{Runtime bundle release tag or \code{"latest"}.} + +\item{local_zip}{Optional local runtime bundle.} + +\item{fallback_zip}{Optional local fallback runtime bundle.} + +\item{source_tarball}{Optional local \code{gdalraster} source tarball.} + +\item{upgrade}{Install \code{gdalraster} R dependencies before compiling.} + +\item{verify}{Run \code{\link[=gdal_verify]{gdal_verify()}} after setup.} +} +\value{ +Invisibly, a list describing performed actions. +} +\description{ +Installs the GDAL build runtime when needed, builds and vendors +\code{gdalraster}, provisions embedded Python when available, and verifies the +result in fresh processes. +} diff --git a/man/gdal_sitrep.Rd b/man/gdal_sitrep.Rd new file mode 100644 index 0000000..719a450 --- /dev/null +++ b/man/gdal_sitrep.Rd @@ -0,0 +1,29 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/gdal_sitrep.R +\name{gdal_sitrep} +\alias{gdal_sitrep} +\title{Report GDAL and gdalraster installation state} +\usage{ +gdal_sitrep( + lib = NULL, + user_lib = FALSE, + network = rlang::is_interactive(), + quiet = FALSE +) +} +\arguments{ +\item{lib}{Library expected to contain the managed \code{gdalraster} build.} + +\item{user_lib}{Inspect \code{.libPaths()[1]} instead of the isolated library.} + +\item{network}{Query GitHub for the latest bundle release.} + +\item{quiet}{Return state without printing it.} +} +\value{ +Invisibly, a named list describing installation state. +} +\description{ +Reports bundle and build provenance, staleness, embedded-Python +provisioning, and common collision risks without changing the session. +} diff --git a/man/gdal_uninstall.Rd b/man/gdal_uninstall.Rd new file mode 100644 index 0000000..be1d42b --- /dev/null +++ b/man/gdal_uninstall.Rd @@ -0,0 +1,34 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/gdal_setup.R +\name{gdal_uninstall} +\alias{gdal_uninstall} +\title{Uninstall managed GDAL resources} +\usage{ +gdal_uninstall( + lib = NULL, + user_lib = FALSE, + runtime = TRUE, + package = TRUE, + python = TRUE, + force = FALSE +) +} +\arguments{ +\item{lib}{Library containing the managed \code{gdalraster} package.} + +\item{user_lib}{Use \code{.libPaths()[1]}.} + +\item{runtime}{Remove the GDAL build runtime.} + +\item{package}{Remove the managed \code{gdalraster} package.} + +\item{python}{Remove managed embedded-Python \code{.pth} files.} + +\item{force}{Confirm removal in non-interactive sessions.} +} +\value{ +Invisibly, the removed paths. +} +\description{ +Uninstall managed GDAL resources +} diff --git a/man/gdal_update.Rd b/man/gdal_update.Rd new file mode 100644 index 0000000..e37e56d --- /dev/null +++ b/man/gdal_update.Rd @@ -0,0 +1,40 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/gdal_setup.R +\name{gdal_update} +\alias{gdal_update} +\title{Update the GDAL runtime and rebuild gdalraster} +\usage{ +gdal_update( + lib = NULL, + user_lib = FALSE, + tag = "latest", + local_zip = NULL, + fallback_zip = NULL, + source_tarball = NULL, + upgrade = FALSE, + verify = TRUE +) +} +\arguments{ +\item{lib}{Destination library for \code{gdalraster}.} + +\item{user_lib}{Use \code{.libPaths()[1]} instead of the isolated managed library.} + +\item{tag}{Runtime bundle release tag or \code{"latest"}.} + +\item{local_zip}{Optional local runtime bundle.} + +\item{fallback_zip}{Optional local fallback runtime bundle.} + +\item{source_tarball}{Optional local \code{gdalraster} source tarball.} + +\item{upgrade}{Install \code{gdalraster} R dependencies before compiling.} + +\item{verify}{Run \code{\link[=gdal_verify]{gdal_verify()}} after setup.} +} +\value{ +The result of \code{\link[=gdal_setup]{gdal_setup()}}, invisibly. +} +\description{ +Update the GDAL runtime and rebuild gdalraster +} diff --git a/man/gdal_verify.Rd b/man/gdal_verify.Rd new file mode 100644 index 0000000..0f8fe69 --- /dev/null +++ b/man/gdal_verify.Rd @@ -0,0 +1,27 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/gdal_verify.R +\name{gdal_verify} +\alias{gdal_verify} +\title{Verify the self-contained gdalraster installation} +\usage{ +gdal_verify(lib = NULL, user_lib = FALSE, python = TRUE, quiet = FALSE) +} +\arguments{ +\item{lib}{Library containing the managed \code{gdalraster} package.} + +\item{user_lib}{Use \code{.libPaths()[1]}.} + +\item{python}{Run the embedded-Python validation when its managed \code{.pth} +file is ready.} + +\item{quiet}{Suppress verification output.} +} +\value{ +\code{TRUE} on success and \code{FALSE} on failure. +} +\description{ +Runs verification in fresh \code{Rscript --vanilla} processes. Checks the GDAL +Algorithm API, GEOS and CRS support, Arrow/Parquet/HDF5/netCDF driver +registration, a first Parquet dataset open, and the GeoPackage Python +validator when embedded Python has been provisioned. +} diff --git a/man/gdalraster.windows-package.Rd b/man/gdalraster.windows-package.Rd index e6bd22d..cdcb406 100644 --- a/man/gdalraster.windows-package.Rd +++ b/man/gdalraster.windows-package.Rd @@ -4,11 +4,11 @@ \name{gdalraster.windows-package} \alias{gdalraster.windows} \alias{gdalraster.windows-package} -\title{gdalraster.windows: Windows GDAL Runtime and gdalraster Bootstrap Tools} +\title{gdalraster.windows: Self-Contained gdalraster Builds for Windows} \description{ \if{html}{\figure{logo.png}{options: style='float: right' alt='logo' width='120'}} -Installs and activates a self-contained GDAL runtime on Windows and provides helpers to install gdalraster from source against that GDAL instead of the default Rtools GDAL. +Installs a self-contained GDAL build runtime on Windows and builds a vendored gdalraster package against it. The resulting package carries its native dependency closure and runtime data, so it loads in fresh R sessions without activation hooks or environment changes. } \seealso{ Useful links: diff --git a/man/install_gdal_runtime.Rd b/man/install_gdal_runtime.Rd deleted file mode 100644 index 3fdabee..0000000 --- a/man/install_gdal_runtime.Rd +++ /dev/null @@ -1,97 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/gdal_runtime.R -\name{install_gdal_runtime} -\alias{install_gdal_runtime} -\title{Install precompiled GDAL runtime} -\usage{ -install_gdal_runtime( - repo = .bundle_repo, - tag = "latest", - asset_pattern = .bundle_asset_pattern, - gdal_home = default_gdal_home(), - overwrite = FALSE, - local_zip = NULL, - fallback_zip = NULL -) -} -\arguments{ -\item{repo}{GitHub repo slug publishing the runtime bundle releases. -Defaults to \code{"jimbrig/gdalraster.windows"}.} - -\item{tag}{Release tag or \code{"latest"}. With \code{"latest"}, the newest release -that publishes a runtime bundle asset (matching \code{asset_pattern}) is -selected; releases without a bundle asset — such as R package releases -(\verb{v*}) — are skipped, so GitHub's "latest release" pointer does not need -to be a GDAL bundle release.} - -\item{asset_pattern}{Regex used to select the release asset. Defaults to -the runtime bundle zip naming convention -(\verb{gdal-(bundle|ucrt64)-.*\\.zip$}).} - -\item{gdal_home}{Destination GDAL home directory.} - -\item{overwrite}{Whether to replace existing \code{gdal_home}.} - -\item{local_zip}{Optional local GDAL runtime zip to install directly.} - -\item{fallback_zip}{Optional fallback zip path used when release download -fails. When \code{NULL} (default), a vendored zip at -\code{inst/extdata/gdal-ucrt64-fallback.zip} is used if present; none ships -with the package, so by default no fallback is attempted.} -} -\value{ -Invisibly returns installed GDAL home path. -} -\description{ -Installs the GDAL runtime into \code{gdal_home} from one of: -} -\details{ -\itemize{ -\item \code{local_zip} (highest precedence), -\item GitHub release asset lookup/download, -\item \code{fallback_zip} when release lookup/download fails. -} - -The selected zip must contain a GDAL root with \verb{bin/libgdal-*.dll}. -} -\section{Offline / air-gapped installation}{ - -On machines without network access, download the release asset manually -from \url{https://github.com/jimbrig/gdalraster.windows/releases}, transfer it -to the target machine, and install directly: - -\if{html}{\out{
}}\preformatted{gdalraster.windows::install_gdal_runtime( - local_zip = "C:/Downloads/gdal-ucrt64-v3.13.1-windows-x64.zip" -) -}\if{html}{\out{
}} - -Note that no fallback zip is shipped with the package (a full runtime -bundle is too large to vendor), so the fallback path only applies when you -provide a \code{fallback_zip} yourself. -} - -\section{Overwriting an installed runtime}{ - -With \code{overwrite = TRUE}, the existing \code{gdal_home} is deleted before the new -runtime is copied in. Runtime DLLs that were preloaded into the current -session (the package auto-bootstrap does this at load time when a runtime -is present) are unloaded first, but the session usually cannot fully -release its own locks anyway: runtime activation prepends \code{bin} to \code{PATH}, -so DLLs loaded later in the session (the release download itself loads the -curl package, which maps the runtime's \code{zlib1.dll}) resolve dependencies -from the runtime directory outside R's control. Mapped DLLs cannot be -deleted but can be renamed, so such leftovers are moved into a stale -sibling directory -(\verb{.stale--}) and the install proceeds; stale -directories are deleted opportunistically by later installs once their -locks are gone. When this happens, restart R before building or loading -\code{gdalraster} so the new runtime — not the still-mapped old DLLs — is used. - -Overwriting is refused outright while \code{gdalraster} is loaded (its DLL pins -the whole runtime in the process); reinstalling then requires a fresh R -session. If files are locked by \emph{other} processes (another R session, a -File Explorer preview pane), neither deletion nor the move-aside is -possible and the install aborts cleanly instead of leaving a -partially-replaced runtime. -} - diff --git a/man/install_gdalraster.Rd b/man/install_gdalraster.Rd deleted file mode 100644 index d793d12..0000000 --- a/man/install_gdalraster.Rd +++ /dev/null @@ -1,76 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/gdal_runtime.R -\name{install_gdalraster} -\alias{install_gdalraster} -\title{Install gdalraster from source against bundled GDAL} -\usage{ -install_gdalraster( - gdal_home = default_gdal_home(), - lib = default_gdalraster_lib(), - source_tarball = NULL, - repo = .gdalraster_repo, - ref = "HEAD", - upgrade = FALSE, - repos = getOption("repos") -) -} -\arguments{ -\item{gdal_home}{GDAL home directory used for compile/link flags.} - -\item{lib}{Destination library path for installing gdalraster. Defaults to -an isolated package-managed library; pass \code{.libPaths()[1]} to install -into your default user library.} - -\item{source_tarball}{Optional local path to \code{gdalraster_*.tar.gz}.} - -\item{repo}{Source GitHub repo slug for gdalraster. Defaults to -\code{"firelab/gdalraster"}.} - -\item{ref}{Git ref (branch, tag, commit) used when downloading from GitHub.} - -\item{upgrade}{When \code{TRUE}, missing R package dependencies of gdalraster are -installed from \code{repos} before the source build. Has no effect on the -compile/link flags used to build gdalraster itself.} - -\item{repos}{CRAN-like repositories used to satisfy R package dependencies -when \code{upgrade = TRUE}. Ignored when \code{upgrade = FALSE}.} -} -\value{ -Invisibly returns installed library path. -} -\description{ -Downloads or uses a local gdalraster source tarball and installs it from -source into a dedicated library path (default) so existing user libraries -are not overwritten. To install into your regular user library instead -(so plain \code{library(gdalraster)} resolves the source build without this -package's load helpers), pass it explicitly, e.g. -\code{install_gdalraster(lib = .libPaths()[1])}. -} -\section{Prerequisites}{ - -This is a source compilation, so -\href{https://cran.r-project.org/bin/windows/Rtools/}{Rtools} matching your R -version must be installed (the one thing the prebuilt runtime bundle cannot -eliminate). The function checks for a toolchain up front and aborts with -guidance when none is found. The GDAL runtime bundle itself must already be -installed via \code{\link[=install_gdal_runtime]{install_gdal_runtime()}}. -} - -\section{Upgrading}{ - -After installing a new runtime bundle version -(\code{install_gdal_runtime(overwrite = TRUE)}), rerun this function — the -previous gdalraster build is bound to the previous bundle's GDAL and must -be recompiled against the new one. -} - -\section{Bundled data files}{ - -Upstream gdalraster's \code{Makevars.win} copies GDAL and PROJ data directories -into the package from the Rtools static libraries, which generally lag the -bundle's GDAL. After the source install succeeds, this function replaces -the installed package's \verb{gdal/} and \verb{proj/} data directories with the -runtime bundle's \code{share/gdal} and \code{share/proj} so the data files match the -GDAL version the package was compiled against. -} - diff --git a/man/load_gdal_dll.Rd b/man/load_gdal_dll.Rd deleted file mode 100644 index 80a51d9..0000000 --- a/man/load_gdal_dll.Rd +++ /dev/null @@ -1,21 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/gdal_runtime.R -\name{load_gdal_dll} -\alias{load_gdal_dll} -\title{Load GDAL DLL from runtime bundle} -\usage{ -load_gdal_dll(gdal_home = default_gdal_home(), quiet = FALSE) -} -\arguments{ -\item{gdal_home}{GDAL home directory.} - -\item{quiet}{Suppress informational CLI output.} -} -\value{ -Invisibly returns activation metadata. -} -\description{ -Convenience wrapper over \code{\link[=activate_gdal_runtime]{activate_gdal_runtime()}} that ensures the GDAL -runtime is activated and the main GDAL DLL is preloaded in the current -session. -} diff --git a/man/load_gdalraster.Rd b/man/load_gdalraster.Rd deleted file mode 100644 index ffd58be..0000000 --- a/man/load_gdalraster.Rd +++ /dev/null @@ -1,26 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/gdal_runtime.R -\name{load_gdalraster} -\alias{load_gdalraster} -\title{Load gdalraster using bundled GDAL runtime} -\usage{ -load_gdalraster( - lib = default_gdalraster_lib(), - gdal_home = default_gdal_home(), - quiet = FALSE -) -} -\arguments{ -\item{lib}{Library path containing the gdalraster source install.} - -\item{gdal_home}{GDAL home directory.} - -\item{quiet}{Suppress informational CLI output.} -} -\value{ -Invisibly returns TRUE if gdalraster was attached. -} -\description{ -Activates bundled GDAL runtime, prepends \code{lib} to \code{.libPaths()}, and attaches -gdalraster for use in the current R session. -} diff --git a/man/verify_gdalraster_runtime.Rd b/man/verify_gdalraster_runtime.Rd deleted file mode 100644 index 15cfcbf..0000000 --- a/man/verify_gdalraster_runtime.Rd +++ /dev/null @@ -1,29 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/gdal_runtime.R -\name{verify_gdalraster_runtime} -\alias{verify_gdalraster_runtime} -\title{Verify gdalraster algorithm API availability} -\usage{ -verify_gdalraster_runtime( - lib.loc = NULL, - activate_runtime = TRUE, - gdal_home = default_gdal_home(), - quiet = FALSE -) -} -\arguments{ -\item{lib.loc}{Optional library location used for loading \code{gdalraster}.} - -\item{activate_runtime}{Whether to run \code{\link[=activate_gdal_runtime]{activate_gdal_runtime()}} first.} - -\item{gdal_home}{GDAL home used when \code{activate_runtime = TRUE}.} - -\item{quiet}{If \code{TRUE}, suppress sitrep CLI output.} -} -\value{ -\code{TRUE} when algorithm API is available, otherwise \code{FALSE} -(including when runtime activation itself fails). -} -\description{ -Attempts to load \code{gdalraster} and checks the global algorithm registry. -} diff --git a/tests/testthat/_snaps/gdal-runtime.md b/tests/testthat/_snaps/gdal-runtime.md deleted file mode 100644 index 754ba8e..0000000 --- a/tests/testthat/_snaps/gdal-runtime.md +++ /dev/null @@ -1,9 +0,0 @@ -# load_gdalraster fails clearly when isolated lib missing package - - Code - gdalraster.windows::load_gdalraster(lib = lib, gdal_home = gdal_home, quiet = TRUE) - Condition - Error: - ! No gdalraster install found in `lib`. - i Run `gdalraster.windows::install_gdalraster()` first. - diff --git a/tests/testthat/helper-fixtures.R b/tests/testthat/helper-fixtures.R new file mode 100644 index 0000000..0ad07ea --- /dev/null +++ b/tests/testthat/helper-fixtures.R @@ -0,0 +1,45 @@ +create_bundle_fixture <- function(root, tag = "gdal-v9.9.1") { + dirs <- c( + file.path(root, "bin"), + file.path(root, "include"), + file.path(root, "lib"), + file.path(root, "share", "gdal"), + file.path(root, "share", "proj"), + file.path(root, "python", "osgeo_utils", "samples") + ) + invisible(lapply(dirs, dir.create, recursive = TRUE, showWarnings = FALSE)) + writeLines("dll", file.path(root, "bin", "libgdal-39.dll")) + writeLines("dependency", file.path(root, "bin", "zlib1.dll")) + writeLines("header", file.path(root, "include", "gdal.h")) + writeLines("import", file.path(root, "lib", "libgdal.dll.a")) + writeLines("data", file.path(root, "share", "gdal", "header.dxf")) + writeLines("proj", file.path(root, "share", "proj", "proj.db")) + writeLines("", file.path(root, "python", "osgeo_utils", "__init__.py")) + writeLines("", file.path(root, "python", "osgeo_utils", "samples", "validate_gpkg.py")) + gdalraster.windows:::write_manifest( + gdalraster.windows:::bundle_manifest( + tag = tag, + gdal_version = sub("^gdal-v", "", tag), + asset_name = "fixture.zip" + ), + file.path(root, "MANIFEST.dcf") + ) + root +} + +create_bundle_zip <- function(path, tag = "gdal-v9.9.1") { + root <- withr::local_tempdir(.local_envir = parent.frame()) + bundle <- create_bundle_fixture(file.path(root, "bundle"), tag = tag) + old <- setwd(dirname(bundle)) + withr::defer(setwd(old), envir = parent.frame()) + utils::zip(path, files = basename(bundle)) + path +} + +release_fixture <- function(tag, assets = list(), draft = FALSE, prerelease = FALSE) { + list(tag_name = tag, draft = draft, prerelease = prerelease, assets = assets) +} + +asset_fixture <- function(id, name, url) { + list(id = id, name = name, browser_download_url = url) +} diff --git a/tests/testthat/test-e2e-clean-room.R b/tests/testthat/test-e2e-clean-room.R index 42d5fdd..db408fa 100644 --- a/tests/testthat/test-e2e-clean-room.R +++ b/tests/testthat/test-e2e-clean-room.R @@ -33,19 +33,26 @@ testthat::test_that("opt-in full e2e succeeds in clean room", { root <- withr::local_tempdir() env <- clean_room_env(root) - code <- paste( + setup_code <- paste( ".libPaths(c(Sys.getenv('R_LIBS_USER'), .libPaths()))", "stopifnot(requireNamespace('gdalraster.windows', quietly = TRUE))", - "gdalraster.windows::install_gdal_runtime(gdal_home = Sys.getenv('GDALRASTER_WINDOWS_GDAL_HOME'), overwrite = TRUE)", - "gdalraster.windows::install_gdalraster(gdal_home = Sys.getenv('GDALRASTER_WINDOWS_GDAL_HOME'), lib = Sys.getenv('R_LIBS_USER'), upgrade = TRUE)", - "gdalraster.windows::load_gdalraster(lib = Sys.getenv('R_LIBS_USER'), gdal_home = Sys.getenv('GDALRASTER_WINDOWS_GDAL_HOME'), quiet = TRUE)", + "gdalraster.windows::gdal_setup(lib = Sys.getenv('R_LIBS_USER'), upgrade = TRUE)", + sep = "; " + ) + setup <- run_clean_rscript(code = setup_code, env = env) + setup_txt <- paste(c(setup$stdout, setup$stderr), collapse = "\n") + testthat::expect_equal(setup$status, 0, info = setup_txt) + + verify_code <- paste( + "library(gdalraster)", "algs <- gdalraster::gdal_global_reg_names()", "cat('algorithm_count=', length(algs), '\\n', sep = '')", "stopifnot(length(algs) > 0L)", + "fmts <- gdalraster::gdal_formats()$short_name", + "stopifnot(all(c('Arrow', 'Parquet', 'HDF5', 'netCDF') %in% fmts))", sep = "; " ) - - res <- run_clean_rscript(code = code, env = env) + res <- run_clean_rscript(code = verify_code, env = env) txt <- paste(c(res$stdout, res$stderr), collapse = "\n") testthat::expect_equal(res$status, 0, info = txt) diff --git a/tests/testthat/test-gdal-runtime.R b/tests/testthat/test-gdal-runtime.R deleted file mode 100644 index 2a42ced..0000000 --- a/tests/testthat/test-gdal-runtime.R +++ /dev/null @@ -1,588 +0,0 @@ -create_runtime_zip_fixture <- function(path) { - root <- withr::local_tempdir() - bundle <- file.path(root, "bundle") - - 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 -} - -# builds a synthetic github release list entry; versions are deliberately -# fake (v9.x) so the fixtures cannot be mistaken for real release tags -release_fixture <- function(tag, assets = list(), draft = FALSE, prerelease = FALSE) { - list(tag_name = tag, draft = draft, prerelease = prerelease, assets = assets) -} - -asset_fixture <- function(id, name, url) { - list(id = id, name = name, browser_download_url = url) -} - -testthat::test_that("select_release_asset skips releases without a matching bundle asset", { - releases <- list( - # package release: no bundle asset, must be skipped - release_fixture("v9.0.0"), - # draft bundle release: must be skipped even though the asset matches - release_fixture( - "gdal-v9.9.2", - draft = TRUE, - assets = list( - asset_fixture(30L, "gdal-ucrt64-v9.9.2-windows-x64.zip", "https://example.com/draft.zip") - ) - ), - # newest published bundle release: wins, non-matching assets ignored - release_fixture( - "gdal-v9.9.1", - assets = list( - asset_fixture(10L, "checksums.txt", "https://example.com/checksums.txt"), - asset_fixture(11L, "gdal-ucrt64-v9.9.1-windows-x64.zip", "https://example.com/bundle.zip") - ) - ), - # older published bundle release: valid but not first - release_fixture( - "gdal-v9.9.0", - assets = list( - asset_fixture(20L, "gdal-ucrt64-v9.9.0-windows-x64.zip", "https://example.com/old.zip") - ) - ) - ) - - asset <- gdalraster.windows:::select_release_asset( - releases, - asset_pattern = gdalraster.windows:::.bundle_asset_pattern - ) - - testthat::expect_equal(asset$tag, "gdal-v9.9.1") - testthat::expect_equal(asset$name, "gdal-ucrt64-v9.9.1-windows-x64.zip") - testthat::expect_equal(asset$url, "https://example.com/bundle.zip") -}) - -testthat::test_that("select_release_asset errors when no release carries a bundle asset", { - releases <- list(release_fixture("v9.0.0")) - - testthat::expect_error( - gdalraster.windows:::select_release_asset( - releases, - asset_pattern = gdalraster.windows:::.bundle_asset_pattern - ), - "No release with an asset matching" - ) -}) - -testthat::test_that("select_release_asset tolerates assets with a missing name field", { - releases <- list( - release_fixture( - "gdal-v9.9.1", - assets = list( - list(id = 1L, browser_download_url = "https://example.com/nameless.zip"), - asset_fixture(2L, "gdal-ucrt64-v9.9.1-windows-x64.zip", "https://example.com/bundle.zip") - ) - ) - ) - - asset <- gdalraster.windows:::select_release_asset( - releases, - asset_pattern = gdalraster.windows:::.bundle_asset_pattern - ) - - testthat::expect_equal(asset$name, "gdal-ucrt64-v9.9.1-windows-x64.zip") -}) - -testthat::test_that("github_pat falls back from gitcreds to GITHUB_PAT to GITHUB_TOKEN", { - testthat::local_mocked_bindings( - gitcreds_pat = function() "", - .env = asNamespace("gdalraster.windows") - ) - - withr::local_envvar(GITHUB_PAT = "pat-value", GITHUB_TOKEN = "token-value") - testthat::expect_equal(gdalraster.windows:::github_pat(), "pat-value") - - withr::local_envvar(GITHUB_PAT = NA) - testthat::expect_equal(gdalraster.windows:::github_pat(), "token-value") - - withr::local_envvar(GITHUB_TOKEN = NA) - testthat::expect_equal(gdalraster.windows:::github_pat(), "") -}) - -testthat::test_that("github_pat prefers the git credential store when populated", { - testthat::local_mocked_bindings( - gitcreds_pat = function() "gitcreds-value", - .env = asNamespace("gdalraster.windows") - ) - - withr::local_envvar(GITHUB_PAT = "pat-value") - testthat::expect_equal(gdalraster.windows:::github_pat(), "gitcreds-value") -}) - -testthat::test_that("dll discovery supports dynamic GDAL soname", { - bin_dir <- withr::local_tempdir() - file.create(file.path(bin_dir, "libgdal-39.dll")) - file.create(file.path(bin_dir, "libgdal-40.dll")) - - gdal_home <- withr::local_tempdir() - dir.create(file.path(gdal_home, "bin"), recursive = TRUE, showWarnings = FALSE) - file.copy(file.path(bin_dir, "libgdal-39.dll"), file.path(gdal_home, "bin", "libgdal-39.dll")) - file.copy(file.path(bin_dir, "libgdal-40.dll"), file.path(gdal_home, "bin", "libgdal-40.dll")) - - dlls <- gdalraster.windows:::gdal_dll_candidates(gdal_home) - testthat::expect_true(length(dlls) >= 2L) - testthat::expect_true(grepl("^libgdal-[0-9]+\\.dll$", basename(gdalraster.windows:::gdal_dll_path(gdal_home)))) -}) - -testthat::test_that("detect_gdal_root finds extracted runtime root", { - root <- withr::local_tempdir() - dir.create(file.path(root, "gdal-bundle", "bin"), recursive = TRUE, showWarnings = FALSE) - file.create(file.path(root, "gdal-bundle", "bin", "libgdal-39.dll")) - - detected <- gdalraster.windows:::detect_gdal_root(root) - testthat::expect_equal( - normalizePath(detected, winslash = "/", mustWork = TRUE), - normalizePath(file.path(root, "gdal-bundle"), winslash = "/", mustWork = TRUE) - ) -}) - -testthat::test_that("install_gdal_runtime installs from local zip", { - testthat::skip_if_not(.Platform$OS.type == "windows") - - zip_path <- withr::local_tempfile(fileext = ".zip") - create_runtime_zip_fixture(zip_path) - - gdal_home <- withr::local_tempdir() - gdalraster.windows::install_gdal_runtime( - gdal_home = gdal_home, - overwrite = TRUE, - local_zip = zip_path - ) - - testthat::expect_true( - file.exists(file.path(gdal_home, "bin", "libgdal-39.dll")) - ) - testthat::expect_true( - dir.exists(file.path(gdal_home, "share", "gdal")) - ) - 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 fails fast on existing gdal_home before any download", { - testthat::skip_if_not(.Platform$OS.type == "windows") - - testthat::local_mocked_bindings( - resolve_release_asset = function(...) { - cli::cli_abort("download must not be attempted for this test") - }, - .env = asNamespace("gdalraster.windows") - ) - - gdal_home <- withr::local_tempdir() - testthat::expect_error( - gdalraster.windows::install_gdal_runtime( - gdal_home = gdal_home, - overwrite = FALSE - ), - "already exists" - ) -}) - -testthat::test_that("install_gdal_runtime with overwrite replaces an existing runtime", { - testthat::skip_if_not(.Platform$OS.type == "windows") - - zip_path <- withr::local_tempfile(fileext = ".zip") - create_runtime_zip_fixture(zip_path) - - gdal_home <- withr::local_tempdir() - dir.create(file.path(gdal_home, "bin"), recursive = TRUE, showWarnings = FALSE) - file.create(file.path(gdal_home, "bin", "stale-marker.dll")) - - gdalraster.windows::install_gdal_runtime( - gdal_home = gdal_home, - overwrite = TRUE, - local_zip = zip_path - ) - - testthat::expect_false( - file.exists(file.path(gdal_home, "bin", "stale-marker.dll")) - ) - testthat::expect_true( - file.exists(file.path(gdal_home, "bin", "libgdal-39.dll")) - ) -}) - -testthat::test_that("activate_gdal_runtime errors loudly when DLL preload fails", { - testthat::skip_if_not(.Platform$OS.type == "windows") - - # fixture dll is an empty file, so dyn.load must fail - gdal_home <- create_gdal_home_fixture(python = FALSE) - - testthat::expect_error( - gdalraster.windows::activate_gdal_runtime( - gdal_home = gdal_home, - preload = TRUE, - quiet = TRUE - ), - "Failed to preload the GDAL runtime DLL" - ) -}) - -testthat::test_that("loaded_runtime_dlls is empty for a never-loaded runtime", { - testthat::skip_if_not(.Platform$OS.type == "windows") - - gdal_home <- create_gdal_home_fixture(python = FALSE) - testthat::expect_length( - gdalraster.windows:::loaded_runtime_dlls(gdal_home), - 0L - ) -}) - -testthat::test_that("verify_gdalraster_runtime returns FALSE when activation fails", { - testthat::skip_if_not(.Platform$OS.type == "windows") - - gdal_home <- create_gdal_home_fixture(python = FALSE) - ok <- gdalraster.windows::verify_gdalraster_runtime( - activate_runtime = TRUE, - gdal_home = gdal_home, - quiet = TRUE - ) - testthat::expect_false(ok) -}) - -testthat::test_that("install_gdal_runtime uses fallback zip when release lookup fails", { - testthat::skip_if_not(.Platform$OS.type == "windows") - - zip_path <- withr::local_tempfile(fileext = ".zip") - create_runtime_zip_fixture(zip_path) - - testthat::local_mocked_bindings( - resolve_release_asset = function(...) { - cli::cli_abort("forced release lookup failure for test") - }, - .env = asNamespace("gdalraster.windows") - ) - - gdal_home <- withr::local_tempdir() - gdalraster.windows::install_gdal_runtime( - repo = "jimbrig/gdalraster.windows", - tag = "latest", - gdal_home = gdal_home, - overwrite = TRUE, - fallback_zip = zip_path - ) - - testthat::expect_true( - file.exists(file.path(gdal_home, "bin", "libgdal-39.dll")) - ) -}) - -testthat::test_that("install_gdal_runtime errors when release fails and no fallback is available", { - testthat::skip_if_not(.Platform$OS.type == "windows") - - testthat::local_mocked_bindings( - resolve_release_asset = function(...) { - cli::cli_abort("forced release lookup failure for test") - }, - .env = asNamespace("gdalraster.windows") - ) - - gdal_home <- withr::local_tempdir() - testthat::expect_error( - gdalraster.windows::install_gdal_runtime( - repo = "jimbrig/gdalraster.windows", - tag = "latest", - gdal_home = gdal_home, - overwrite = TRUE, - fallback_zip = NULL - ), - "Failed to download GDAL runtime from GitHub release" - ) -}) - -testthat::test_that("load_gdalraster fails clearly when isolated lib missing package", { - testthat::skip_if_not(.Platform$OS.type == "windows") - - lib <- withr::local_tempdir() - gdal_home <- withr::local_tempdir() - dir.create(file.path(gdal_home, "bin"), recursive = TRUE, showWarnings = FALSE) - file.create(file.path(gdal_home, "bin", "libgdal-39.dll")) - - testthat::expect_snapshot(error = TRUE, { - gdalraster.windows::load_gdalraster(lib = lib, gdal_home = gdal_home, quiet = TRUE) - }) -}) - -testthat::test_that("verify_gdalraster_runtime returns FALSE when gdalraster is unavailable", { - testthat::skip_if_not(.Platform$OS.type == "windows") - - testthat::local_mocked_bindings( - has_gdalraster_namespace = function() FALSE, - .env = asNamespace("gdalraster.windows") - ) - - ok <- gdalraster.windows::verify_gdalraster_runtime( - activate_runtime = FALSE, - quiet = TRUE - ) - testthat::expect_false(ok) -}) - -testthat::test_that("stale_runtime_dir is a uniquely-named sibling of gdal_home", { - gdal_home <- file.path(withr::local_tempdir(), "gdal") - - stale <- gdalraster.windows:::stale_runtime_dir(gdal_home) - - testthat::expect_equal(dirname(stale), dirname(gdal_home)) - testthat::expect_true(startsWith(basename(stale), "gdal.stale-")) - testthat::expect_false(identical(stale, gdal_home)) -}) - -testthat::test_that("move_tree_aside moves all files and removes the source tree", { - root <- withr::local_tempdir() - from <- file.path(root, "gdal") - to <- file.path(root, "gdal.stale-test") - - dir.create(file.path(from, "bin"), recursive = TRUE, showWarnings = FALSE) - dir.create(file.path(from, "share", "proj"), recursive = TRUE, showWarnings = FALSE) - writeLines("dll", file.path(from, "bin", "libgdal-39.dll")) - writeLines("db", file.path(from, "share", "proj", "proj.db")) - - ok <- gdalraster.windows:::move_tree_aside(from, to) - - testthat::expect_true(ok) - testthat::expect_false(dir.exists(from)) - testthat::expect_true(file.exists(file.path(to, "bin", "libgdal-39.dll"))) - testthat::expect_true(file.exists(file.path(to, "share", "proj", "proj.db"))) -}) - -testthat::test_that("cleanup_stale_runtimes deletes stale siblings and ignores others", { - root <- withr::local_tempdir() - gdal_home <- file.path(root, "gdal") - stale <- file.path(root, "gdal.stale-123-20260101") - unrelated <- file.path(root, "library") - - dir.create(gdal_home, recursive = TRUE, showWarnings = FALSE) - dir.create(stale, recursive = TRUE, showWarnings = FALSE) - file.create(file.path(stale, "zlib1.dll")) - dir.create(unrelated, recursive = TRUE, showWarnings = FALSE) - - gdalraster.windows:::cleanup_stale_runtimes(gdal_home) - - testthat::expect_false(dir.exists(stale)) - testthat::expect_true(dir.exists(gdal_home)) - testthat::expect_true(dir.exists(unrelated)) -}) - -testthat::test_that("remove_gdal_home fully deletes an unlocked runtime", { - root <- withr::local_tempdir() - gdal_home <- file.path(root, "gdal") - dir.create(file.path(gdal_home, "bin"), recursive = TRUE, showWarnings = FALSE) - file.create(file.path(gdal_home, "bin", "libgdal-39.dll")) - - moved <- gdalraster.windows:::remove_gdal_home(gdal_home) - - testthat::expect_false(moved) - testthat::expect_false(dir.exists(gdal_home)) - # no stale sibling should be left behind for a clean delete - testthat::expect_length(list.files(root, pattern = "stale"), 0L) -}) - -testthat::test_that("remove_gdal_home aborts when files are locked without delete sharing", { - testthat::skip_if_not(.Platform$OS.type == "windows") - - root <- withr::local_tempdir() - gdal_home <- file.path(root, "gdal") - dir.create(file.path(gdal_home, "bin"), recursive = TRUE, showWarnings = FALSE) - locked <- file.path(gdal_home, "bin", "libgdal-39.dll") - writeLines("dll", locked) - - # an open connection holds the file without FILE_SHARE_DELETE, which blocks - # both deletion and the rename-based move-aside (the external-locker case) - con <- file(locked, open = "rb") - withr::defer(close(con)) - - testthat::expect_error( - gdalraster.windows:::remove_gdal_home(gdal_home), - "Could not fully delete or move aside" - ) -}) - -testthat::test_that("install_gdalraster calls install.packages with repos = NULL", { - testthat::skip_if_not(.Platform$OS.type == "windows") - - # Intercept install.packages() and capture the repos argument so we can - # assert it is NULL (required for local-file installation; when repos is - # non-NULL R looks up the tarball path as a package name and never installs - # from the file, producing the "not available for this version of R" warning). - captured_repos <- list() - - gdal_home <- create_gdal_home_fixture() - lib <- withr::local_tempdir() - tarball <- withr::local_tempfile(fileext = ".tar.gz") - file.create(tarball) - - testthat::local_mocked_bindings( - activate_gdal_runtime = function(...) invisible(list()), - .env = asNamespace("gdalraster.windows") - ) - - testthat::local_mocked_bindings( - install.packages = function(pkgs, repos, ...) { - # c(list(NULL)) appends a NULL element; `[[<-` with NULL would drop it - captured_repos <<- c(captured_repos, list(repos)) - # Simulate a successful install by creating the package directory. - dir.create(file.path(list(...)$lib, "gdalraster"), recursive = TRUE, showWarnings = FALSE) - invisible(NULL) - }, - .package = "utils" - ) - - gdalraster.windows::install_gdalraster( - gdal_home = gdal_home, - lib = lib, - source_tarball = tarball, - upgrade = FALSE - ) - - # The local-tarball install.packages() call must use repos = NULL. - testthat::expect_true( - any(vapply(captured_repos, is.null, logical(1L))), - info = "install.packages() must be called with repos = NULL for local tarball installation" - ) -}) - -testthat::test_that("sync_gdalraster_share_data replaces packaged data with bundle share data", { - lib <- withr::local_tempdir() - pkg_gdal <- file.path(lib, "gdalraster", "gdal") - pkg_proj <- file.path(lib, "gdalraster", "proj") - dir.create(pkg_gdal, recursive = TRUE, showWarnings = FALSE) - dir.create(pkg_proj, recursive = TRUE, showWarnings = FALSE) - # rtools-era files that must not survive the sync - writeLines("rtools", file.path(pkg_gdal, "stale_datum.csv")) - writeLines("rtools", file.path(pkg_proj, "proj.db")) - - gdal_home <- withr::local_tempdir() - share_gdal <- file.path(gdal_home, "share", "gdal") - share_proj <- file.path(gdal_home, "share", "proj") - dir.create(file.path(share_gdal, "nested"), recursive = TRUE, showWarnings = FALSE) - dir.create(share_proj, recursive = TRUE, showWarnings = FALSE) - writeLines("bundle", file.path(share_gdal, "header.dxf")) - writeLines("bundle", file.path(share_gdal, "nested", "extra.csv")) - writeLines("bundle", file.path(share_proj, "proj.db")) - - synced <- gdalraster.windows:::sync_gdalraster_share_data( - lib = lib, - gdal_home = gdal_home - ) - - testthat::expect_setequal(synced, c("gdal", "proj")) - testthat::expect_false(file.exists(file.path(pkg_gdal, "stale_datum.csv"))) - testthat::expect_equal(readLines(file.path(pkg_gdal, "header.dxf")), "bundle") - testthat::expect_equal(readLines(file.path(pkg_gdal, "nested", "extra.csv")), "bundle") - testthat::expect_equal(readLines(file.path(pkg_proj, "proj.db")), "bundle") -}) - -testthat::test_that("sync_gdalraster_share_data keeps packaged data when bundle dirs are missing", { - lib <- withr::local_tempdir() - pkg_gdal <- file.path(lib, "gdalraster", "gdal") - dir.create(pkg_gdal, recursive = TRUE, showWarnings = FALSE) - writeLines("rtools", file.path(pkg_gdal, "gdal_datum.csv")) - - gdal_home <- withr::local_tempdir() - - synced <- gdalraster.windows:::sync_gdalraster_share_data( - lib = lib, - gdal_home = gdal_home - ) - - testthat::expect_length(synced, 0L) - testthat::expect_equal(readLines(file.path(pkg_gdal, "gdal_datum.csv")), "rtools") -}) diff --git a/tests/testthat/test-manifest-runtime.R b/tests/testthat/test-manifest-runtime.R new file mode 100644 index 0000000..28e91ef --- /dev/null +++ b/tests/testthat/test-manifest-runtime.R @@ -0,0 +1,161 @@ +testthat::test_that("manifest round trip preserves provenance fields", { + path <- withr::local_tempfile(fileext = ".dcf") + fields <- list( + `Bundle-Tag` = "gdal-v9.9.1", + `GDAL-Version` = "9.9.1", + `Asset-Name` = "fixture.zip" + ) + + gdalraster.windows:::write_manifest(fields, path) + result <- gdalraster.windows:::read_manifest(path) + + testthat::expect_identical(result[["Bundle-Tag"]], "gdal-v9.9.1") + testthat::expect_identical(result[["GDAL-Version"]], "9.9.1") + testthat::expect_null(gdalraster.windows:::read_manifest(withr::local_tempfile())) +}) + +testthat::test_that("build provenance classifies current and stale builds", { + bundle <- list(`Bundle-Tag` = "gdal-v9.9.1") + current <- list(`Bundle-Tag` = "gdal-v9.9.1") + stale <- list(`Bundle-Tag` = "gdal-v9.9.0") + + testthat::expect_true(gdalraster.windows:::build_is_current(bundle, current)) + testthat::expect_false(gdalraster.windows:::build_is_current(bundle, stale)) + testthat::expect_false(gdalraster.windows:::build_is_current(bundle, NULL)) +}) + +testthat::test_that("local bundle install writes and preserves its manifest", { + testthat::skip_if_not(.Platform$OS.type == "windows") + zip <- withr::local_tempfile(fileext = ".zip") + create_bundle_zip(zip) + home <- file.path(withr::local_tempdir(), "gdal") + + gdalraster.windows::gdal_install_runtime( + gdal_home = home, + local_zip = zip, + force = TRUE + ) + + manifest <- gdalraster.windows:::installed_bundle_manifest(home) + testthat::expect_identical(manifest[["Bundle-Tag"]], "gdal-v9.9.1") + testthat::expect_true(file.exists(file.path(home, "bin", "libgdal-39.dll"))) + testthat::expect_true(dir.exists(file.path(home, "python", "osgeo_utils"))) +}) + +testthat::test_that("runtime install skips a matching release without download", { + testthat::skip_if_not(.Platform$OS.type == "windows") + home <- create_bundle_fixture(file.path(withr::local_tempdir(), "gdal")) + + testthat::local_mocked_bindings( + resolve_release_asset = function(...) { + list( + name = "fixture.zip", + tag = "gdal-v9.9.1", + url = "https://example.invalid/fixture.zip" + ) + }, + download_release_asset = function(...) { + testthat::fail("matching installs must not download") + }, + .env = asNamespace("gdalraster.windows") + ) + + testthat::expect_message( + gdalraster.windows::gdal_install_runtime(gdal_home = home), + "already installed" + ) +}) + +testthat::test_that("runtime install reports an available update without replacing", { + testthat::skip_if_not(.Platform$OS.type == "windows") + home <- create_bundle_fixture( + file.path(withr::local_tempdir(), "gdal"), + tag = "gdal-v9.9.0" + ) + + testthat::local_mocked_bindings( + resolve_release_asset = function(...) { + list( + name = "fixture.zip", + tag = "gdal-v9.9.1", + url = "https://example.invalid/fixture.zip" + ) + }, + .env = asNamespace("gdalraster.windows") + ) + + testthat::expect_message( + gdalraster.windows::gdal_install_runtime(gdal_home = home), + "gdal_update" + ) + testthat::expect_identical( + gdalraster.windows:::manifest_value( + gdalraster.windows:::installed_bundle_manifest(home), + "Bundle-Tag" + ), + "gdal-v9.9.0" + ) +}) + +testthat::test_that("runtime install uses a local fallback after release failure", { + testthat::skip_if_not(.Platform$OS.type == "windows") + zip <- withr::local_tempfile(fileext = ".zip") + create_bundle_zip(zip) + home <- file.path(withr::local_tempdir(), "gdal") + + testthat::local_mocked_bindings( + resolve_release_asset = function(...) cli::cli_abort("forced failure"), + .env = asNamespace("gdalraster.windows") + ) + + gdalraster.windows::gdal_install_runtime( + gdal_home = home, + fallback_zip = zip, + force = TRUE + ) + testthat::expect_true(file.exists(file.path(home, "bin", "libgdal-39.dll"))) +}) + +testthat::test_that("release selection ignores package and draft releases", { + releases <- list( + release_fixture("v9.0.0"), + release_fixture( + "gdal-v9.9.2", + draft = TRUE, + assets = list(asset_fixture(1L, "gdal-ucrt64-v9.9.2.zip", "draft")) + ), + release_fixture( + "gdal-v9.9.1", + assets = list(asset_fixture(2L, "gdal-ucrt64-v9.9.1.zip", "winner")) + ) + ) + + result <- gdalraster.windows:::select_release_asset( + releases, + gdalraster.windows:::.bundle_asset_pattern + ) + testthat::expect_identical(result$tag, "gdal-v9.9.1") + testthat::expect_identical(result$url, "winner") +}) + +testthat::test_that("stale runtime helpers preserve unrelated directories", { + root <- withr::local_tempdir() + home <- file.path(root, "gdal") + stale <- file.path(root, "gdal.stale-test") + unrelated <- file.path(root, "library") + dir.create(file.path(home, "bin"), recursive = TRUE) + dir.create(stale) + dir.create(unrelated) + writeLines("dll", file.path(home, "bin", "libgdal-39.dll")) + + moved <- gdalraster.windows:::move_tree_aside( + home, + file.path(root, "gdal.stale-moved") + ) + testthat::expect_true(moved) + testthat::expect_false(dir.exists(home)) + + gdalraster.windows:::cleanup_stale_runtimes(home) + testthat::expect_false(dir.exists(stale)) + testthat::expect_true(dir.exists(unrelated)) +}) diff --git a/tests/testthat/test-sitrep-api.R b/tests/testthat/test-sitrep-api.R new file mode 100644 index 0000000..9ca5e57 --- /dev/null +++ b/tests/testthat/test-sitrep-api.R @@ -0,0 +1,100 @@ +testthat::test_that("sitrep classifies a current vendored installation", { + home <- create_bundle_fixture(file.path(withr::local_tempdir(), "gdal")) + lib <- withr::local_tempdir() + package_dir <- file.path(lib, "gdalraster") + dir.create(package_dir) + gdalraster.windows:::write_manifest( + list(`Bundle-Tag` = "gdal-v9.9.1"), + gdalraster.windows:::build_manifest_path(package_dir) + ) + withr::local_options(gdalraster.windows.gdal_home = home) + + testthat::local_mocked_bindings( + managed_python_pth_files = function() character(), + path_gdal_dlls = function() character(), + loaded_gdal_dlls = function() character(), + .env = asNamespace("gdalraster.windows") + ) + + state <- gdalraster.windows::gdal_sitrep( + lib = lib, + network = FALSE, + quiet = TRUE + ) + testthat::expect_true(state$runtime_installed) + testthat::expect_true(state$gdalraster_installed) + testthat::expect_true(state$build_current) + testthat::expect_identical(state$bundle_tag, "gdal-v9.9.1") +}) + +testthat::test_that("sitrep classifies a stale build", { + home <- create_bundle_fixture( + file.path(withr::local_tempdir(), "gdal"), + tag = "gdal-v9.9.2" + ) + lib <- withr::local_tempdir() + package_dir <- file.path(lib, "gdalraster") + dir.create(package_dir) + gdalraster.windows:::write_manifest( + list(`Bundle-Tag` = "gdal-v9.9.1"), + gdalraster.windows:::build_manifest_path(package_dir) + ) + withr::local_options(gdalraster.windows.gdal_home = home) + + testthat::local_mocked_bindings( + managed_python_pth_files = function() character(), + path_gdal_dlls = function() character(), + loaded_gdal_dlls = function() character(), + .env = asNamespace("gdalraster.windows") + ) + + state <- gdalraster.windows::gdal_sitrep( + lib = lib, + network = FALSE, + quiet = TRUE + ) + testthat::expect_false(state$build_current) + testthat::expect_identical(state$bundle_tag, "gdal-v9.9.2") + testthat::expect_identical(state$build_tag, "gdal-v9.9.1") +}) + +testthat::test_that("legacy profile detection recognizes old hook forms", { + profile <- withr::local_tempfile(fileext = ".Rprofile") + writeLines("# >>> gdalraster.windows hook >>>", profile) + testthat::expect_true( + gdalraster.windows:::legacy_hook_detected(profile) + ) + + writeLines("options(width = 100)", profile) + testthat::expect_false( + gdalraster.windows:::legacy_hook_detected(profile) + ) +}) + +testthat::test_that("removed activation API is no longer exported", { + removed <- c( + "activate_gdal_runtime", + "add_gdal_rprofile_hook", + "configure_gdal_home", + "gdal_rprofile_snippet", + "install_gdal_runtime", + "install_gdalraster", + "load_gdal_dll", + "load_gdalraster", + "verify_gdalraster_runtime" + ) + testthat::expect_length( + intersect(removed, getNamespaceExports("gdalraster.windows")), + 0L + ) +}) + +testthat::test_that("verification returns false when package is absent", { + testthat::skip_if_not(.Platform$OS.type == "windows") + testthat::expect_false( + gdalraster.windows::gdal_verify( + lib = withr::local_tempdir(), + quiet = TRUE + ) + ) +}) diff --git a/tests/testthat/test-startup-hook.R b/tests/testthat/test-startup-hook.R deleted file mode 100644 index 0ee3c3b..0000000 --- a/tests/testthat/test-startup-hook.R +++ /dev/null @@ -1,42 +0,0 @@ -testthat::test_that("gdal_rprofile_snippet includes loader and library path", { - testthat::skip_if_not(.Platform$OS.type == "windows") - - gdal_home <- "C:/gdal-ucrt64" - lib <- "C:/custom-lib" - txt <- gdalraster.windows::gdal_rprofile_snippet( - gdal_home = gdal_home, - lib = lib - ) - - testthat::expect_match(txt, "load_gdal_dll", fixed = TRUE) - testthat::expect_match(txt, gdal_home, fixed = TRUE) - testthat::expect_match(txt, lib, fixed = TRUE) -}) - -testthat::test_that("add_gdal_rprofile_hook appends and updates managed block", { - testthat::skip_if_not(.Platform$OS.type == "windows") - - profile <- withr::local_tempfile(fileext = ".Rprofile") - writeLines("options(width = 120)", con = profile, useBytes = TRUE) - - gdalraster.windows::add_gdal_rprofile_hook( - rprofile = profile, - gdal_home = "C:/gdal-a", - lib = "C:/lib-a" - ) - first <- readLines(profile, warn = FALSE) - testthat::expect_true(any(grepl("gdalraster.windows hook", first, fixed = TRUE))) - testthat::expect_true(any(grepl("C:/gdal-a", first, fixed = TRUE))) - - gdalraster.windows::add_gdal_rprofile_hook( - rprofile = profile, - gdal_home = "C:/gdal-b", - lib = "C:/lib-b" - ) - second <- readLines(profile, warn = FALSE) - - testthat::expect_equal(sum(grepl("^# >>> gdalraster.windows hook >>>$", second)), 1L) - testthat::expect_equal(sum(grepl("^# <<< gdalraster.windows hook <<<$", second)), 1L) - testthat::expect_true(any(grepl("C:/gdal-b", second, fixed = TRUE))) - testthat::expect_false(any(grepl("C:/gdal-a", second, fixed = TRUE))) -}) diff --git a/tests/testthat/test-startup-status.R b/tests/testthat/test-startup-status.R deleted file mode 100644 index eb0e344..0000000 --- a/tests/testthat/test-startup-status.R +++ /dev/null @@ -1,52 +0,0 @@ -testthat::test_that("pkg_startup_msg shows setup-needed guidance", { - testthat::skip_if_not(.Platform$OS.type == "windows") - - withr::local_options(gdalraster.windows.gdal_home = withr::local_tempdir()) - empty_lib <- withr::local_tempdir() - testthat::local_mocked_bindings( - default_gdalraster_lib = function() empty_lib, - .env = asNamespace("gdalraster.windows") - ) - txt <- paste(gdalraster.windows:::pkg_startup_msg(), collapse = "\n") - - testthat::expect_match(txt, "setup needed", fixed = TRUE) - testthat::expect_match(txt, "install_gdal_runtime", fixed = TRUE) - testthat::expect_match(txt, "install_gdalraster", fixed = TRUE) -}) - -testthat::test_that("pkg_startup_msg shows ready-style details", { - testthat::skip_if_not(.Platform$OS.type == "windows") - - gdal_home <- withr::local_tempdir() - dir.create(file.path(gdal_home, "bin"), recursive = TRUE, showWarnings = FALSE) - file.create(file.path(gdal_home, "bin", "libgdal-39.dll")) - - lib <- withr::local_tempdir() - dir.create(file.path(lib, "gdalraster"), recursive = TRUE, showWarnings = FALSE) - - withr::local_options(gdalraster.windows.gdal_home = gdal_home) - testthat::local_mocked_bindings( - default_gdalraster_lib = function() lib, - .env = asNamespace("gdalraster.windows") - ) - testthat::local_mocked_bindings( - runtime_sitrep = function() { - list( - gdal_home = gdal_home, - gdal_bin = file.path(gdal_home, "bin"), - gdal_dll = file.path(gdal_home, "bin", "libgdal-39.dll"), - custom_lib = lib, - gdal_home_exists = TRUE, - gdal_dll_exists = TRUE, - custom_lib_exists = TRUE, - custom_gdalraster_exists = TRUE, - gdalraster_loaded = TRUE - ) - }, - .env = asNamespace("gdalraster.windows") - ) - - txt <- paste(gdalraster.windows:::pkg_startup_msg(), collapse = "\n") - testthat::expect_match(txt, "runtime:", fixed = TRUE) - testthat::expect_match(txt, "gdalraster lib:", fixed = TRUE) -}) diff --git a/tests/testthat/test-vendoring-python.R b/tests/testthat/test-vendoring-python.R new file mode 100644 index 0000000..fd1ca4d --- /dev/null +++ b/tests/testthat/test-vendoring-python.R @@ -0,0 +1,95 @@ +testthat::test_that("vendoring copies DLLs, data, and Python without deleting package DLL", { + home <- create_bundle_fixture(file.path(withr::local_tempdir(), "gdal")) + package_dir <- file.path(withr::local_tempdir(), "gdalraster") + dir.create(file.path(package_dir, "libs", "x64"), recursive = TRUE) + writeLines("package", file.path(package_dir, "libs", "x64", "gdalraster.dll")) + dir.create(file.path(package_dir, "gdal")) + writeLines("stale", file.path(package_dir, "gdal", "stale.csv")) + + gdalraster.windows:::vendor_gdalraster(package_dir, home) + + testthat::expect_true( + file.exists(file.path(package_dir, "libs", "x64", "gdalraster.dll")) + ) + testthat::expect_true( + file.exists(file.path(package_dir, "libs", "x64", "libgdal-39.dll")) + ) + testthat::expect_false(file.exists(file.path(package_dir, "gdal", "stale.csv"))) + testthat::expect_true(file.exists(file.path(package_dir, "proj", "proj.db"))) + testthat::expect_true( + file.exists(file.path(package_dir, "python", "osgeo_utils", "__init__.py")) + ) +}) + +testthat::test_that("package replacement is staged and removes its backup", { + root <- withr::local_tempdir() + staged <- file.path(root, "stage", "gdalraster") + target <- file.path(root, "library", "gdalraster") + dir.create(staged, recursive = TRUE) + dir.create(target, recursive = TRUE) + writeLines("new", file.path(staged, "marker")) + writeLines("old", file.path(target, "marker")) + + gdalraster.windows:::replace_package_tree(staged, target) + + testthat::expect_identical(readLines(file.path(target, "marker")), "new") + testthat::expect_false(dir.exists(staged)) + testthat::expect_length( + list.files(dirname(target), pattern = "\\.previous-"), + 0L + ) +}) + +testthat::test_that("managed Python path provisioning is idempotent", { + testthat::skip_if_not(.Platform$OS.type == "windows") + lib <- withr::local_tempdir() + package_python <- file.path(lib, "gdalraster", "python", "osgeo_utils") + dir.create(package_python, recursive = TRUE) + site <- withr::local_tempdir() + + first <- gdalraster.windows::gdal_enable_python( + lib = lib, + site_packages = site, + quiet = TRUE + ) + second <- gdalraster.windows::gdal_enable_python( + lib = lib, + site_packages = site, + quiet = TRUE + ) + + testthat::expect_identical(first, second) + lines <- readLines(first) + testthat::expect_identical( + lines[[1L]], + gdalraster.windows:::.python_pth_marker + ) + testthat::expect_true(dir.exists(lines[[2L]])) + testthat::expect_length(list.files(site, pattern = "\\.pth$"), 1L) +}) + +testthat::test_that("pth target parsing rejects unmanaged files", { + path <- withr::local_tempfile(fileext = ".pth") + writeLines("C:/something", path) + testthat::expect_true(is.na(gdalraster.windows:::pth_target(path))) + + writeLines( + c(gdalraster.windows:::.python_pth_marker, "C:/managed"), + path + ) + testthat::expect_identical( + gdalraster.windows:::pth_target(path), + "C:/managed" + ) +}) + +testthat::test_that("runtime contract requires all vendoring inputs", { + home <- create_bundle_fixture(file.path(withr::local_tempdir(), "gdal")) + testthat::expect_true(gdalraster.windows:::validate_runtime_contract(home)) + + unlink(file.path(home, "python"), recursive = TRUE) + testthat::expect_error( + gdalraster.windows:::validate_runtime_contract(home), + "incomplete" + ) +}) diff --git a/tools/build_arrow.sh b/tools/build_arrow.sh new file mode 100644 index 0000000..5ca1766 --- /dev/null +++ b/tools/build_arrow.sh @@ -0,0 +1,175 @@ +#!/usr/bin/env bash +# ============================================================================= +# build_arrow.sh — Build static Apache Arrow for the GDAL Windows bundle +# +# Arrow is built with the MSYS2 UCRT64/MinGW toolchain used for GDAL and +# installed to a dedicated prefix. GDAL then folds these static libraries into +# libgdal-*.dll. Shared Arrow/Parquet/Thrift DLLs are intentionally excluded: +# the previous shared libarrow.dll crashed during lazy MinGW emulated-TLS +# initialization when loaded into TLS-heavy R processes. +# +# Environment variables (set by the GitHub Actions workflow): +# ARROW_VER : Apache Arrow release version, e.g. "25.0.0" +# ARROW_INSTALL_DIR : cmake install prefix consumed by build_gdal.sh +# ============================================================================= +set -euo pipefail + +: "${ARROW_VER:?ARROW_VER must be set}" +: "${ARROW_INSTALL_DIR:?ARROW_INSTALL_DIR must be set}" + +ARROW_INSTALL_DIR="$(cygpath -u "${ARROW_INSTALL_DIR}")" + +echo "============================================" +echo " Building static Apache Arrow ${ARROW_VER}" +echo " Install prefix: ${ARROW_INSTALL_DIR}" +echo "============================================" + +SRC_DIR="/tmp/arrow-src" +ARROW_TAG="apache-arrow-${ARROW_VER}" + +if [[ -d "${SRC_DIR}/.git" ]]; then + echo ">>> Reusing existing clone at ${SRC_DIR}" + git -C "${SRC_DIR}" fetch --depth=1 origin \ + "refs/tags/${ARROW_TAG}:refs/tags/${ARROW_TAG}" 2>/dev/null || true + git -C "${SRC_DIR}" checkout "${ARROW_TAG}" +else + echo ">>> Cloning Apache Arrow ${ARROW_VER} (shallow)" + git clone \ + --depth=1 \ + --branch="${ARROW_TAG}" \ + https://github.com/apache/arrow.git \ + "${SRC_DIR}" +fi + +rm -rf "${SRC_DIR}/cpp/build" "${ARROW_INSTALL_DIR}" + +# Arrow's bundled dependency mode produces libarrow_bundled_dependencies.a for +# Thrift/snappy/brotli/etc. zlib stays a MSYS2 static archive (avoids Arrow's +# MinGW bundled-zlib naming bug). lz4/zstd use the same MSYS2 *shared* import +# libraries GDAL already links — mixing Arrow-static + GDAL-shared copies of +# those codecs fails the final libgdal link with multiple-definition errors. +# The system allocator avoids the mimalloc/jemalloc TLS state implicated by +# the original first-Parquet-open crash. +if [[ ! -f /ucrt64/lib/libz.a ]]; then + echo "FATAL: required static zlib archive missing: /ucrt64/lib/libz.a" + exit 1 +fi +for codec_lib in /ucrt64/lib/liblz4.dll.a /ucrt64/lib/libzstd.dll.a; do + if [[ ! -f "${codec_lib}" ]]; then + echo "FATAL: required shared codec import library missing: ${codec_lib}" + exit 1 + fi +done + +echo "" +echo ">>> cmake configure" +cmake -S "${SRC_DIR}/cpp" -B "${SRC_DIR}/cpp/build" -G Ninja \ + -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_INSTALL_PREFIX="${ARROW_INSTALL_DIR}" \ + -DCMAKE_C_FLAGS_RELEASE="-O2 -DNDEBUG" \ + -DCMAKE_CXX_FLAGS_RELEASE="-O2 -DNDEBUG" \ + -DBUILD_SHARED_LIBS=OFF \ + \ + -DARROW_BUILD_STATIC=ON \ + -DARROW_BUILD_SHARED=OFF \ + -DARROW_DEPENDENCY_SOURCE=BUNDLED \ + -DARROW_DEPENDENCY_USE_SHARED=OFF \ + -DARROW_THRIFT_USE_SHARED=OFF \ + -DZLIB_SOURCE=SYSTEM \ + -DZLIB_USE_STATIC_LIBS=ON \ + -DZLIB_LIBRARY=/ucrt64/lib/libz.a \ + -DZLIB_INCLUDE_DIR=/ucrt64/include \ + -Dlz4_SOURCE=SYSTEM \ + -DLZ4_USE_STATIC_LIBS=OFF \ + -DLZ4_LIBRARY=/ucrt64/lib/liblz4.dll.a \ + -DLZ4_INCLUDE_DIR=/ucrt64/include \ + -Dzstd_SOURCE=SYSTEM \ + -Dzstd_USE_STATIC_LIBS=OFF \ + -Dzstd_LIBRARY=/ucrt64/lib/libzstd.dll.a \ + -Dzstd_INCLUDE_DIR=/ucrt64/include \ + \ + -DARROW_PARQUET=ON \ + -DARROW_DATASET=ON \ + -DARROW_ACERO=ON \ + -DARROW_COMPUTE=ON \ + -DARROW_FILESYSTEM=ON \ + \ + -DARROW_MIMALLOC=OFF \ + -DARROW_JEMALLOC=OFF \ + -DARROW_WITH_BROTLI=ON \ + -DARROW_WITH_BZ2=ON \ + -DARROW_WITH_LZ4=ON \ + -DARROW_WITH_SNAPPY=ON \ + -DARROW_WITH_ZLIB=ON \ + -DARROW_WITH_ZSTD=ON \ + \ + -DARROW_BUILD_BENCHMARKS=OFF \ + -DARROW_BUILD_EXAMPLES=OFF \ + -DARROW_BUILD_INTEGRATION=OFF \ + -DARROW_BUILD_TESTS=OFF \ + -DARROW_BUILD_UTILITIES=OFF \ + -DARROW_CSV=OFF \ + -DARROW_FLIGHT=OFF \ + -DARROW_GANDIVA=OFF \ + -DARROW_HDFS=OFF \ + -DARROW_JSON=OFF \ + -DARROW_S3=OFF \ + -DPARQUET_BUILD_EXECUTABLES=OFF \ + -DPARQUET_REQUIRE_ENCRYPTION=OFF + +NCPUS=$(nproc) +echo "" +echo ">>> cmake build (${NCPUS} cores)" +cmake --build "${SRC_DIR}/cpp/build" -j"${NCPUS}" + +echo "" +echo ">>> cmake install -> ${ARROW_INSTALL_DIR}" +cmake --install "${SRC_DIR}/cpp/build" + +required_targets=( + "Arrow/ArrowConfig.cmake" + "ArrowDataset/ArrowDatasetConfig.cmake" + "ArrowCompute/ArrowComputeConfig.cmake" + "Parquet/ParquetConfig.cmake" +) +for config in "${required_targets[@]}"; do + if [[ ! -f "${ARROW_INSTALL_DIR}/lib/cmake/${config}" ]]; then + echo "FATAL: required static Arrow CMake target missing: ${config}" + exit 1 + fi +done + +if ! compgen -G "${ARROW_INSTALL_DIR}/lib/libarrow*.a" >/dev/null; then + echo "FATAL: no static Arrow libraries were installed" + exit 1 +fi +if ! compgen -G "${ARROW_INSTALL_DIR}/lib/libparquet*.a" >/dev/null; then + echo "FATAL: no static Parquet libraries were installed" + exit 1 +fi +if [[ ! -f "${ARROW_INSTALL_DIR}/lib/libarrow_bundled_dependencies.a" ]]; then + echo "FATAL: bundled static Arrow dependencies were not installed" + exit 1 +fi +if compgen -G "${ARROW_INSTALL_DIR}/bin/*.dll" >/dev/null; then + echo "FATAL: static Arrow prefix unexpectedly contains DLLs:" + printf ' %s\n' "${ARROW_INSTALL_DIR}"/bin/*.dll + exit 1 +fi + +# ArrowTargets must not propagate absolute paths to liblz4.a / libzstd.a into +# the GDAL link; those collide with GDAL's liblz4.dll.a / libzstd.dll.a. +echo "" +echo ">>> Checking Arrow CMake targets do not pin static lz4/zstd archives" +if grep -R --include='*.cmake' -E '/ucrt64/lib/lib(lz4|zstd)\.a' \ + "${ARROW_INSTALL_DIR}/lib/cmake" >/tmp/arrow-static-codec-refs.txt 2>/dev/null; then + echo "FATAL: Arrow CMake package still references static lz4/zstd archives:" + cat /tmp/arrow-static-codec-refs.txt + exit 1 +fi + +echo "" +echo ">>> Static Arrow build complete." +echo " Libraries:" +printf ' %s\n' "${ARROW_INSTALL_DIR}"/lib/libarrow*.a +printf ' %s\n' "${ARROW_INSTALL_DIR}"/lib/libparquet*.a diff --git a/tools/build_gdal.sh b/tools/build_gdal.sh index eab2c92..e663fbc 100644 --- a/tools/build_gdal.sh +++ b/tools/build_gdal.sh @@ -6,6 +6,7 @@ # GDAL_VER : git tag to check out, e.g. "v3.13.0" # BUNDLE_DIR : absolute path where the final bundle should land # INSTALL_DIR : cmake install prefix (intermediate, collected by collect_dlls.sh) +# ARROW_INSTALL_DIR : static Arrow prefix produced by build_arrow.sh # # Key build decisions: # - Static GCC/stdc++/winpthread runtime — the DLLs carry their own C++ @@ -16,6 +17,9 @@ # DLLs used from R (GDAL's Windows exports use __stdcall). # - GDAL_USE_MUPARSER=ON — enables the Algorithmic Processing API # (gdal_global_reg_names() returns non-empty on Windows). +# - ARROW_USE_STATIC_LIBRARIES=ON — folds Arrow, Parquet, Dataset, Compute, +# and bundled third-party dependencies into libgdal. This removes the +# shared libarrow.dll MinGW emulated-TLS failure from the import graph. # - BUILD_TESTING=OFF, BUILD_APPS=OFF — reduces build time by ~30%. # - GDAL_HIDE_INTERNAL_SYMBOLS=ON — cleaner export table. # - GDAL_USE_MSSQL_ODBC/NCLI=OFF — GitHub runner images ship the proprietary @@ -47,13 +51,24 @@ # ============================================================================= set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + # ── Validate env ────────────────────────────────────────────────────────────── : "${GDAL_VER:?GDAL_VER must be set}" : "${INSTALL_DIR:?INSTALL_DIR must be set}" +: "${ARROW_INSTALL_DIR:?ARROW_INSTALL_DIR must be set}" + +ARROW_INSTALL_DIR="$(cygpath -u "${ARROW_INSTALL_DIR}")" + +if [[ ! -f "${ARROW_INSTALL_DIR}/lib/cmake/Arrow/ArrowConfig.cmake" ]]; then + echo "FATAL: static Arrow prefix is incomplete: ${ARROW_INSTALL_DIR}" + exit 1 +fi echo "============================================" echo " Building GDAL ${GDAL_VER}" echo " Install prefix: ${INSTALL_DIR}" +echo " Static Arrow prefix: ${ARROW_INSTALL_DIR}" echo "============================================" # ── Clone ───────────────────────────────────────────────────────────────────── @@ -74,6 +89,20 @@ fi cd "${SRC_DIR}" +# GDAL 3.13.2's exported-link flattener marks targets only after recursively +# visiting their dependencies. Arrow 25's static abseil graph contains cycles, +# so configuration otherwise exceeds CMake's recursion limit. Apply the focused +# cycle guard while preserving the existing dependency ordering. +GDAL_CYCLE_PATCH="${SCRIPT_DIR}/patches/gdal-static-target-cycles.patch" +if git apply --check "${GDAL_CYCLE_PATCH}"; then + git apply "${GDAL_CYCLE_PATCH}" +elif git apply --reverse --check "${GDAL_CYCLE_PATCH}"; then + echo ">>> Static-target cycle guard already applied" +else + echo "FATAL: GDAL static-target cycle guard does not apply to ${GDAL_VER}" + exit 1 +fi + # Clean any previous build tree rm -rf build @@ -82,7 +111,14 @@ rm -rf build # -Wl,-Bstatic,--whole-archive \ # -lwinpthread : embed pthreads-win32 statically # -Wl,-Bdynamic,--no-whole-archive : revert to dynamic for everything after -STATIC_RT="-static-libgcc -static-libstdc++ -Wl,-Bstatic,--whole-archive -lwinpthread -Wl,-Bdynamic,--no-whole-archive" +# --allow-multiple-definition : GDAL's FindLZ4/FindZSTD pull both the +# shared import lib and an Alt static archive; Arrow also contributes the +# shared codecs. Identical LZ4_*/ZSTD_* symbols then collide at final link. +# Scoped to the libgdal link only (not R PKG_LIBS — see #3). +# ws2_32 must appear *after* static Arrow/Thrift archives in the final link +# line (Thrift references __imp_htonl/ntohl). CMAKE_CXX_STANDARD_LIBRARIES is +# appended late by the MinGW/Ninja generators; linker FLAGS alone are too early. +STATIC_RT="-static-libgcc -static-libstdc++ -Wl,-Bstatic,--whole-archive -lwinpthread -Wl,-Bdynamic,--no-whole-archive -Wl,--allow-multiple-definition" # ── Configure ───────────────────────────────────────────────────────────────── echo "" @@ -90,11 +126,18 @@ echo ">>> cmake configure" cmake -B build -G Ninja \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_INSTALL_PREFIX="${INSTALL_DIR}" \ - -DCMAKE_PREFIX_PATH=/ucrt64 \ + "-DCMAKE_PREFIX_PATH=${ARROW_INSTALL_DIR};/ucrt64" \ + -DArrow_DIR="${ARROW_INSTALL_DIR}/lib/cmake/Arrow" \ + -DArrowCompute_DIR="${ARROW_INSTALL_DIR}/lib/cmake/ArrowCompute" \ + -DArrowDataset_DIR="${ARROW_INSTALL_DIR}/lib/cmake/ArrowDataset" \ + -DParquet_DIR="${ARROW_INSTALL_DIR}/lib/cmake/Parquet" \ \ -DGDAL_USE_MUPARSER=ON \ -DGDAL_USE_ARROW=ON \ -DGDAL_USE_PARQUET=ON \ + -DGDAL_USE_ARROWDATASET=ON \ + -DGDAL_USE_ARROWCOMPUTE=ON \ + -DARROW_USE_STATIC_LIBRARIES=ON \ -DGDAL_USE_GEOS=ON \ -DGDAL_USE_SPATIALITE=ON \ -DGDAL_USE_HDF5=ON \ @@ -114,7 +157,18 @@ cmake -B build -G Ninja \ -DOGR_BUILD_OPTIONAL_DRIVERS=ON \ \ "-DCMAKE_SHARED_LINKER_FLAGS=-Wl,--kill-at ${STATIC_RT}" \ - "-DCMAKE_MODULE_LINKER_FLAGS=-Wl,--kill-at ${STATIC_RT}" + "-DCMAKE_MODULE_LINKER_FLAGS=-Wl,--kill-at ${STATIC_RT}" \ + "-DCMAKE_CXX_STANDARD_LIBRARIES=-lws2_32 -lkernel32 -luser32 -lgdi32 -lwinspool -lshell32 -lole32 -loleaut32 -luuid -lcomdlg32 -ladvapi32" + +# Ensure ws2_32 follows static Arrow/Thrift objects on the final link line. +# CMAKE_CXX_STANDARD_LIBRARIES usually does this; also append to the Ninja +# response file when present so a generator quirk cannot leave Thrift unresolved. +if [[ -f build/CMakeFiles/GDAL.rsp ]]; then + if ! grep -q -- '-lws2_32' build/CMakeFiles/GDAL.rsp; then + echo '-lws2_32' >> build/CMakeFiles/GDAL.rsp + echo ">>> Appended -lws2_32 to GDAL.rsp" + fi +fi # ── Build ───────────────────────────────────────────────────────────────────── NCPUS=$(nproc) diff --git a/tools/collect_dlls.sh b/tools/collect_dlls.sh index a9ecf3f..d349b79 100644 --- a/tools/collect_dlls.sh +++ b/tools/collect_dlls.sh @@ -97,10 +97,12 @@ fi # Guard: the PDF driver must stay disabled (GDAL_ENABLE_DRIVER_PDF=OFF in # build_gdal.sh). The MSYS2 libpodofo.dll fails DllMain with # ERROR_DLL_INIT_FAILED (1114) in any process, which makes a libgdal that -# imports it unloadable. Poppler's NSS/NSPR chain is banned alongside it so a -# config regression re-enabling the driver via either backend fails the build -# here instead of shipping a broken bundle. -banned_dep_regex='^(libpodofo[^ ]*\.dll|libpoppler[^ ]*\.dll|nss3\.dll|nssutil3\.dll|smime3\.dll|libnspr4\.dll|nspr4\.dll|libplc4\.dll|libplds4\.dll)$' +# imports it unloadable. Poppler's NSS/NSPR chain is banned alongside it. +# +# Arrow, Parquet, and Thrift must be statically folded into libgdal. Shared +# versions reintroduce the MinGW emulated-TLS crash this bundle build fixes. +# Any config regression to either dependency subtree fails here. +banned_dep_regex='^(libpodofo[^ ]*\.dll|libpoppler[^ ]*\.dll|nss3\.dll|nssutil3\.dll|smime3\.dll|libnspr4\.dll|nspr4\.dll|libplc4\.dll|libplds4\.dll|libarrow[^ ]*\.dll|libparquet[^ ]*\.dll|libthrift[^ ]*\.dll)$' banned_found="$( ntldd -R "${GDAL_DLL}" \ | awk '{ if ($2 != "=>") next; print tolower($1) }' \ @@ -112,7 +114,7 @@ if [[ -n "${banned_found}" ]]; then echo "FATAL: libgdal links banned dependency DLLs (broken/unnecessary at runtime):" printf ' %s\n' ${banned_found} echo "" - echo "Re-check the PDF driver flags in tools/build_gdal.sh and rebuild." + echo "Re-check the PDF and static Arrow flags in tools/build_gdal.sh and rebuild." exit 1 fi @@ -244,6 +246,45 @@ else echo "✓ PASS — Bundle is fully self-contained (no external non-Windows deps)" fi +# The import-graph check above is authoritative, but also reject stray banned +# DLL files copied into the bundle so the published contract is unambiguous. +banned_bundle_files=() +while IFS= read -r dll_path; do + [[ -z "${dll_path}" ]] && continue + dll_name="$(basename "${dll_path}" | tr '[:upper:]' '[:lower:]')" + if [[ "${dll_name}" =~ ${banned_dep_regex} ]]; then + banned_bundle_files+=("${dll_path}") + fi +done < <(printf '%s\n' "${BUNDLE_DIR}"/bin/*.dll) + +if (( ${#banned_bundle_files[@]} > 0 )); then + echo "" + echo "FATAL: bundle contains banned dependency DLLs:" + printf ' %s\n' "${banned_bundle_files[@]}" + exit 1 +fi +echo "✓ PASS — No shared Arrow, Parquet, Thrift, or PDF dependency DLLs" + +# ── Provenance manifest for gdalraster.windows installs ─────────────────────── +# Written into the published zip so gdal_install_runtime(local_zip=...) and +# release downloads share the same Bundle-Tag / GDAL-Version contract. +release_tag="${RELEASE_TAG:-}" +gdal_ver="${GDAL_VER:-}" +if [[ -z "${release_tag}" && -n "${gdal_ver}" ]]; then + release_tag="gdal-v${gdal_ver#v}" +fi +if [[ -n "${release_tag}" ]]; then + gdal_ver_field="${gdal_ver:-${release_tag#gdal-}}" + echo "" + echo ">>> Writing MANIFEST.dcf (${release_tag})" + cat > "${BUNDLE_DIR}/MANIFEST.dcf" < 0L) + +formats <- gdalraster::gdal_formats()$short_name +stopifnot(any(grepl("Parquet", formats, ignore.case = TRUE))) +stopifnot(any(grepl("Arrow", formats, ignore.case = TRUE))) + +layers <- gdalraster::ogr_ds_layer_names(parquet_path) +stopifnot(length(layers) == 1L) + +cli::cli_alert_success( + "first Parquet open passed after loading httpuv, later, gifski, and nanoparquet ({length(algorithms)} algorithms)" +) diff --git a/vignettes/architecture.qmd b/vignettes/architecture.qmd index 41a0400..1ba3520 100644 --- a/vignettes/architecture.qmd +++ b/vignettes/architecture.qmd @@ -4,148 +4,92 @@ vignette: > %\VignetteIndexEntry{Architecture} %\VignetteEngine{quarto::html} %\VignetteEncoding{UTF-8} -knitr: - opts_chunk: - collapse: true - comment: '#>' --- -```{r} -#| include: false -#| eval: false -library(gdalraster.windows) -``` - -This article explains the systems-level design behind `gdalraster.windows`: why the package exists, how the [GDAL](https://gdal.org/) runtime bundle is built, and why runtime activation works the way it does. - -## The root problem - -GDAL's [Algorithm API](https://gdal.org/en/stable/api/gdalalg_cpp.html) registers algorithms through static C++ constructors, file-scope objects whose constructors insert entries into a global registry when `libgdal` is loaded. Under some Windows toolchain states (notably Rtools/[MXE](https://mxe.cc/) builds where dependencies are static archives), the linker's dead-code elimination discarded those self-registration translation units, leaving the registry empty (see [firelab/gdalraster#826](https://github.com/firelab/gdalraster/issues/826)). - -The visible symptom: - -```{r} -#| eval: false -gdalraster::gdal_global_reg_names() -#> character(0) -``` +## Why this package exists -The upstream fix landed in GDAL 3.12.2 ([OSGeo/gdal#13592](https://github.com/OSGeo/gdal/pull/13592)), and [`muparser`](https://beltoforion.de/en/muparser/) (required by parts of the Algorithm API) was added to the Rtools GDAL build in [release 6768](https://cran.r-project.org/bin/windows/Rtools/rtools45/news.html) (see [firelab/gdalraster#858](https://github.com/firelab/gdalraster/issues/858)). Until a fixed GDAL ships in the default toolchain, and for anyone needing a pinned, feature-rich GDAL, this package provides a known good runtime: a custom GDAL build plus the activation logic to load it reliably. +[`gdalraster`](https://firelab.github.io/gdalraster/) binds to GDAL's C++ API. +On Windows, `gdalraster.dll` and `libgdal-*.dll` therefore must be built in a +compatible MinGW/UCRT ABI environment. The default Rtools GDAL has also +historically lacked the Algorithm API registration and driver profile this +project needs. -## Toolchain stack +The repository builds a modern shared GDAL in MSYS2 UCRT64, publishes a +verified runtime bundle, and compiles `gdalraster` from source against that +bundle. -| Term | What it is | -|------|------------| -| [MinGW-w64](https://www.mingw-w64.org/) | GCC-based toolchain producing native Win32 `.exe`/`.dll` (no POSIX emulation layer) | -| [MSYS2](https://www.msys2.org/) | Distribution + `pacman` package manager shipping several MinGW-w64 toolchain variants; the *build environment*, not the runtime target | -| [UCRT](https://learn.microsoft.com/en-us/cpp/porting/upgrade-your-code-to-the-universal-crt) | Microsoft's Universal C Runtime (default since VS2015); mixing binaries linked against different C runtimes is unsafe (incompatible heap allocators, `FILE*`, etc.) | -| [UCRT64](https://www.msys2.org/docs/environments/) | The MSYS2 environment targeting UCRT — the variant compatible with Rtools | -| [Rtools45](https://cran.r-project.org/bin/windows/Rtools/rtools45/rtools.html) | CRAN's Windows toolchain for R 4.5 and later; UCRT64/MinGW-based, so C++ ABI-compatible with MSYS2 UCRT64 builds of the same GCC line | - -The invariant this package maintains: GDAL and `gdalraster` are both compiled with compatible MinGW/UCRT toolchains. - -## Why `gdalraster` must be rebuilt from source - -C++ has no standardized ABI across compilers. Name mangling, vtable layout, exception unwinding, and object layout all differ between MSVC and MinGW/GCC, and can drift between incompatible GCC configurations. [`gdalraster`](https://firelab.github.io/gdalraster/) binds to GDAL's C++ API through [Rcpp](https://www.rcpp.org/) (not a C `extern "C"` shim), so `gdalraster.dll` and `libgdal-*.dll` must come from the same ABI world. - -That is why `install_gdalraster()` builds from source against the bundle's headers and import library rather than reusing the CRAN binary (which is linked — statically — against Rtools' own GDAL): - -```{r} -#| eval: false -gdalraster.windows::install_gdalraster() -``` +## Install-time vendoring -Internally this uses [`withr::with_makevars()`](https://withr.r-lib.org/reference/with_makevars.html), which writes a scoped Makevars file and points the `R_MAKEVARS_USER` environment variable at it for the duration of the install — compile/link flags never leak into your persistent configuration. - -## Key build flags - -From [`tools/build_gdal.sh`](https://github.com/jimbrig/gdalraster.windows/blob/main/tools/build_gdal.sh): - -| Flag | Purpose | -|------|---------| -| `-DGDAL_USE_MUPARSER=ON` | Algorithm API support (expression evaluation) | -| `-DGDAL_USE_ARROW/PARQUET/HDF5/NETCDF/GEOS/SPATIALITE=ON` | Extended driver profile beyond the lean Rtools build | -| `-DGDAL_ENABLE_DRIVER_PDF=OFF` (+ poppler/podofo/pdfium `OFF`) | The MSYS2 `libpodofo.dll` fails its DLL initialization routine (Windows error 1114) in any process; a `libgdal` that imports it cannot be loaded at all, so the PDF driver is excluded from the bundle | -| `-DGDAL_HIDE_INTERNAL_SYMBOLS=ON` | Restricts the export table to the public API (PE/COFF DLLs cap export ordinals at 65,535 and GDAL's full symbol set exceeds it — see [OSGeo/gdal#4706](https://github.com/OSGeo/gdal/issues/4706)) | -| `-Wl,--kill-at` | Strips `@N` stdcall decoration from exports so symbol names match what loaders expect | -| `-static-libgcc -static-libstdc++` + whole-archive `winpthread` | Embeds the GCC runtime into the DLLs — end users need neither Rtools nor MSYS2 at runtime | - -## Dependency closure: `collect_dlls.sh` - -Producing `libgdal-*.dll` is half the job; it imports dozens of transitive DLLs ([GEOS](https://libgeos.org/), [PROJ](https://proj.org/), [Arrow](https://arrow.apache.org/)'s deep tree, [HDF5](https://www.hdfgroup.org/solutions/hdf5/), ...). [`tools/collect_dlls.sh`](https://github.com/jimbrig/gdalraster.windows/blob/main/tools/collect_dlls.sh) walks the full PE import tree with [`ntldd -R`](https://github.com/LRN/ntldd), copies every dependency that resolves to the UCRT64 prefix into the bundle's `bin/`, and **fails** if any non-Windows-system dependency remains unresolved. The bundle is therefore a verified-closed set: the only external imports are Windows system DLLs. - -Final bundle layout: +Version 0.4.0 moves all runtime selection to install time: ```text -/ -├── bin/ libgdal-*.dll + closed transitive DLL set -├── include/ headers (compile-time, for install_gdalraster()) -├── lib/ libgdal.dll.a import library (compile-time) -├── share/ gdal/ + proj/ runtime data -└── python/ osgeo_utils (pure-python, for embedded-python algorithms) +bundle SDK -> source build -> staged gdalraster package + | + +-- libs/x64: native dependency closure + +-- gdal + proj: matching data + +-- python: osgeo_utils + +-- build provenance ``` -No executables ship in the bundle (`BUILD_APPS=OFF`): consumers are R -processes loading the DLL, not command-line users. +The staged package replaces the destination only after compilation and +vendoring succeed. This prevents a failed build or locked destination from +leaving a partially updated package. -## Runtime activation: why loading needs help +## Fresh-session loading -Windows resolves a DLL's import table at load time using a fixed search order (executable directory, System32, then `PATH`). When `library(gdalraster)` loads `gdalraster.dll`, Windows immediately needs `libgdal-*.dll` — if the bundle's `bin/` is not discoverable at that exact moment, loading fails with `LoadLibrary failure`. +R's Windows loader calls `library.dynam()` with the installed package's +`libs/x64` directory. That directory becomes the search location for the +entire load-time dependency graph, so the vendored `libgdal` and dependency +DLLs resolve next to `gdalraster.dll`. -`activate_gdal_runtime()` handles this, session-scoped: +GDAL and PROJ data are package-internal, matching the GDAL version used at +compile time. No startup hook, DLL preload, `PATH` mutation, or GDAL/PROJ +environment export is part of the package architecture. -- prepends `/bin` to `PATH` -- sets `GDAL_DATA`, `PROJ_LIB`, `PROJ_DATA` (GDAL and PROJ require their runtime data trees for CRS operations) -- prepends `/python` to `PYTHONPATH` (next section) -- preloads the GDAL DLL via `dyn.load(..., local = FALSE, now = TRUE)` — mapping it into the process's loaded-module list *before* `gdalraster.dll` asks for it; `local = FALSE` loads into the global symbol namespace so subsequent DLLs resolve against it +## Multi-GDAL machines -## The embedded Python layer +Another GDAL on `PATH` does not override the vendored DLL while +`gdalraster.dll` is loading. The remaining process-level exception is an +identically named GDAL DLL already loaded before `gdalraster`; Windows module +resolution can reuse an existing loaded module by name. `gdal_sitrep()` reports +both competing `PATH` locations and loaded GDAL modules. -Some GDAL algorithms (e.g. [`gdal driver gpkg validate`](https://gdal.org/en/stable/programs/gdal_driver_gpkg_validate.html)) are thin C++ entry points around Python implementations. At first use, `libgdal` locates a `python.exe` on `PATH`, dynamically loads the matching `libpython` DLL (no static CPython link), calls `Py_Initialize()`, and imports `osgeo_utils.samples.validate_gpkg`. +Command-line GDAL installations from pixi, conda, OSGeo4W, or MSYS2 remain +independent. Their executables can coexist with the vendored R package. -[`osgeo_utils`](https://github.com/OSGeo/gdal/tree/master/swig/python/gdal-utils) (GDAL's `gdal-utils` distribution) is pure Python — no compiled extension modules, hence no CPython version/ABI coupling. The bundle ships it under `/python`, version-locked to the built GDAL tag, and activation exposes it via `PYTHONPATH`. The compiled `osgeo` SWIG bindings are deliberately **not** bundled: they would pin the bundle to a single CPython ABI, and the Python-implemented validators degrade gracefully without them. +## Bundle responsibilities -```{r} -#| eval: false -alg <- gdalraster::gdal_alg(cmd = "driver gpkg validate") -alg$setArg("dataset", "file.gpkg") -alg$setArg("full-check", TRUE) -alg$run() -alg$output() -``` - -## Compile-time vs runtime paths - -These are independent concerns, and conflating them is the most common source of confusion: +The build workflow and scripts are authoritative for the distributable GDAL +SDK: -- **Compile-time** (during `install_gdalraster()`): `PKG_CPPFLAGS` points at `/include`, `PKG_LIBS` at `/lib` — scoped via `withr`. -- **Runtime** (every session): the Windows loader resolves DLLs through `PATH`/preload state — handled by `activate_gdal_runtime()`. +- `.github/workflows/build.yml`; +- `tools/build_gdal.sh`; and +- `tools/collect_dlls.sh`. -A successful link does not imply a loadable session, and vice versa. +They build GDAL, collect the non-Windows dependency closure, validate bundle +layout and loadability, and publish release assets. The package does not +reimplement those tasks. -## Reproducing the bundle +The Arrow/Parquet TLS correction belongs to this bundle layer. The package +contains no session-order or Parquet initialization workaround. Package CI +instead verifies a first Parquet open in a fresh process so bundle regressions +are observable. -The bundle is built entirely from the repository — no local machine state. For a new GDAL release: +## Package responsibilities -```bash -git tag gdal-v3.14.0 && git push origin gdal-v3.14.0 -``` - -or dispatch the [build workflow](https://github.com/jimbrig/gdalraster.windows/actions/workflows/build.yml) with `gdal_version=v3.14.0`. The version string drives the GDAL source checkout, cache key, asset name (`gdal-ucrt64-v3.14.0-windows-x64.zip`), and release tag. CI cache keys hash the build scripts, so any build-logic change forces a fresh compile. Published bundles are available on the [releases page](https://github.com/jimbrig/gdalraster.windows/releases). +The R package: -Local (non-CI) reproduction from an MSYS2 UCRT64 shell: +1. installs and stamps the SDK; +2. compiles `gdalraster` with scoped Makevars and environment state; +3. vendors DLLs, data, and Python utilities; +4. provisions the managed Python `.pth`; and +5. verifies the result in fresh processes. -```bash -export GDAL_VER=v3.14.0 -export INSTALL_DIR=/c/gdal-install -export BUNDLE_DIR=/c/gdal-bundle -bash tools/build_gdal.sh -bash tools/collect_dlls.sh -``` +The end-to-end workflow consumes these exported functions exactly as users do. -## Upstream references +## Provenance boundary -- [firelab/gdalraster#826](https://github.com/firelab/gdalraster/issues/826) — algorithm-registry failure mode -- [firelab/gdalraster#982](https://github.com/firelab/gdalraster/issues/982) — working Windows workflow this package productized -- [OSGeo/gdal#13592](https://github.com/OSGeo/gdal/pull/13592) — upstream registration fix (GDAL 3.12.2) -- [Rtools45 news](https://cran.r-project.org/bin/windows/Rtools/rtools45/news.html) +`MANIFEST.dcf` identifies the installed SDK. +`gdalraster.windows-build.dcf` identifies the SDK used for a package build. +Comparing their bundle tags turns an ABI-sensitive update into an explicit +state transition: a new SDK always requires a new `gdalraster` build. diff --git a/vignettes/getting-started.qmd b/vignettes/getting-started.qmd index 16d8560..2f26f38 100644 --- a/vignettes/getting-started.qmd +++ b/vignettes/getting-started.qmd @@ -4,134 +4,115 @@ vignette: > %\VignetteIndexEntry{Getting Started} %\VignetteEngine{quarto::html} %\VignetteEncoding{UTF-8} -knitr: - opts_chunk: - collapse: true - comment: '#>' --- -```{r} -#| label: setup -#| eval: false -library(gdalraster.windows) -``` - -## What this package does +## What the package installs -`gdalraster.windows` provides a reliable Windows workflow for using [`gdalraster`](https://firelab.github.io/gdalraster/) against a modern, self-contained [GDAL](https://gdal.org/) runtime built in CI — including features the default [Rtools](https://cran.r-project.org/bin/windows/Rtools/) GDAL lacks (notably the [GDAL Algorithm API](https://gdal.org/en/stable/api/gdalalg_cpp.html) with [`muparser`](https://beltoforion.de/en/muparser/), plus [Arrow](https://arrow.apache.org/)/[Parquet](https://parquet.apache.org/), [HDF5](https://www.hdfgroup.org/solutions/hdf5/), [NetCDF](https://www.unidata.ucar.edu/software/netcdf/), and [SpatiaLite](https://www.gaia-gis.it/fossil/libspatialite/index) drivers). +`gdalraster.windows` downloads a verified GDAL build runtime, compiles +[`gdalraster`](https://firelab.github.io/gdalraster/) against it, and vendors +the complete native dependency closure into the installed `gdalraster` +package. The result carries: -It does three things: +- GDAL and dependency DLLs under `libs/x64`; +- matching GDAL and PROJ data under `gdal/` and `proj/`; +- pure-Python `osgeo_utils` under `python/`; and +- a provenance manifest recording the bundle used for the build. -1. **Installs a GDAL runtime bundle** — a prebuilt, verified-closed set of DLLs, runtime data, and pure-python utilities published as a [GitHub release asset](https://github.com/jimbrig/gdalraster.windows/releases). -2. **Builds `gdalraster` from source** against that bundle, into an isolated library so nothing you already have installed is touched. -3. **Activates the runtime per session** so the Windows loader, GDAL, and PROJ all resolve against the bundle. - -Everything is non-destructive by default: the runtime lives under a package-managed user data directory, and the source-built `gdalraster` goes into its own library path rather than replacing a CRAN install. +No `.Rprofile` hook, `PATH` edit, DLL preload, or GDAL/PROJ environment +variable is needed in later sessions. ## Prerequisites -Two things must be on the machine before setup: - -- **R on Windows** — everything in this package is Windows-specific. -- **[Rtools](https://cran.r-project.org/bin/windows/Rtools/) matching your R version** — `install_gdalraster()` compiles gdalraster from source against the bundled GDAL headers. The prebuilt runtime bundle removes every other toolchain requirement (no MSYS2, no manual GDAL build), but the compile step itself needs Rtools. The function checks for a toolchain up front and aborts with guidance when none is found. - -No other GDAL, Python, or spatial system dependencies are required: the runtime bundle is self-contained. +- Windows and R. +- The matching [Rtools](https://cran.r-project.org/bin/windows/Rtools/) + release. Compilation is the only step the prebuilt GDAL bundle cannot + remove. -## Quick start +## One-time setup -One-time setup (using [pak](https://pak.r-lib.org/)): +Install the package, then build into your regular user library when you want +plain `library(gdalraster)` in every later session: ```{r} #| eval: false pak::pak("jimbrig/gdalraster.windows") - -# download and install the GDAL runtime bundle (latest release asset) -gdalraster.windows::install_gdal_runtime() - -# build gdalraster from source against that runtime -gdalraster.windows::install_gdalraster() +gdalraster.windows::gdal_setup(user_lib = TRUE) ``` -Then load and verify: +`gdal_setup()` prints one plan, installs or skips the runtime idempotently, +builds and vendors `gdalraster`, provisions embedded Python when a system +CPython is available, and verifies the result in fresh processes. + +The package's non-destructive default is an isolated managed library: ```{r} #| eval: false -gdalraster.windows::load_gdalraster() - -gdalraster::gdal_global_reg_names() -#> [1] "raster" "vector" "convert" "info" ... (non-empty) +result <- gdalraster.windows::gdal_setup() +result$lib ``` -A non-empty algorithm registry is the key success signal — on a broken toolchain/runtime combination it comes back as `character(0)`. +Use `user_lib = TRUE` explicitly to replace a package in `.libPaths()[1]`. +Interactive sessions ask before replacement; non-interactive replacement +requires explicit arguments. ## Everyday use -After setup, attaching the package is enough. Its load hook automatically activates the installed runtime and prepends the isolated `gdalraster` library to `.libPaths()`: +After a user-library setup, `gdalraster.windows` does not need to be attached: ```{r} #| eval: false -library(gdalraster.windows) library(gdalraster) - gdalraster::gdal_global_reg_names() ``` -If you prefer explicit control over the load order: +For an isolated install, provide its library location: ```{r} #| eval: false -gdalraster.windows::load_gdal_dll() - -library(gdalraster) -gdalraster::gdal_global_reg_names() -``` - -To make sessions bootstrap without attaching this package at all, install a managed `.Rprofile` hook (optional, and clearly delimited in the file): - -```{r} -#| eval: false -gdalraster.windows::add_gdal_rprofile_hook() +library( + gdalraster, + lib.loc = file.path( + tools::R_user_dir("gdalraster.windows", "data"), + "library" + ) +) ``` -## Verifying the setup - -`verify_gdalraster_runtime()` runs the full chain — activate runtime, load `gdalraster`, check the algorithm registry — and reports what it finds: +## Status and verification ```{r} #| eval: false -gdalraster.windows::verify_gdalraster_runtime() -#> v gdalraster is ready ("3.13.1") +gdalraster.windows::gdal_sitrep(user_lib = TRUE) +gdalraster.windows::gdal_verify(user_lib = TRUE) ``` -## Offline / air-gapped machines +`gdal_verify()` uses fresh `Rscript --vanilla` processes. It checks the +Algorithm API, GEOS and CRS support, Arrow, Parquet, HDF5, and netCDF driver +registration, a first Parquet open, and the GeoPackage Python validator when +Python provisioning is ready. -`install_gdal_runtime()` downloads from GitHub Releases by default. Without network access, download the release asset from on a connected machine, transfer it, and install directly: +## Updating ```{r} #| eval: false -gdalraster.windows::install_gdal_runtime( - local_zip = "C:/Downloads/gdal-ucrt64-v3.13.1-windows-x64.zip" -) +gdalraster.windows::gdal_update(user_lib = TRUE) ``` -## Where things are installed +The runtime and built package manifests let this operation distinguish a +current build from one that must be rebuilt. -| Component | Default location | Override | -|-----------|------------------|----------| -| GDAL runtime | `tools::R_user_dir("gdalraster.windows", "data")` | `configure_gdal_home()`, `options(gdalraster.windows.gdal_home = ...)`, or the `GDALRASTER_WINDOWS_GDAL_HOME` environment variable | -| Source-built `gdalraster` | isolated `library/` folder under the same user data directory | `install_gdalraster(lib = ...)` | +## Offline setup -To install the source build into your regular user library instead — so plain `library(gdalraster)` resolves it without this package's helpers — pass the library explicitly: +Download a bundle release asset on a connected machine, transfer it, then use: ```{r} #| eval: false -gdalraster.windows::install_gdalraster(lib = .libPaths()[1]) +gdalraster.windows::gdal_setup( + user_lib = TRUE, + local_zip = "C:/Downloads/gdal-bundle-v3.13.2-windows-x64.zip" +) ``` -This replaces any existing `gdalraster` (e.g. the CRAN binary) in that library, and the bundled runtime must still be activated before the package loads in each session. - -## Next steps - -- The [Runtime Guide](runtime-guide.html) covers session activation, configuration options, the startup hook, and embedded-python algorithms in depth. -- [Architecture](architecture.html) explains why this package exists and how the runtime bundle is built. -- [Troubleshooting](troubleshooting.html) walks through the common failure modes and their fixes. +See the [Runtime Guide](runtime-guide.html) for layout and provenance details, +[Architecture](architecture.html) for the loading model, and +[Troubleshooting](troubleshooting.html) for diagnosis. diff --git a/vignettes/runtime-guide.qmd b/vignettes/runtime-guide.qmd index f286bcd..ddc5be4 100644 --- a/vignettes/runtime-guide.qmd +++ b/vignettes/runtime-guide.qmd @@ -4,165 +4,120 @@ vignette: > %\VignetteIndexEntry{Runtime Guide} %\VignetteEngine{quarto::html} %\VignetteEncoding{UTF-8} -knitr: - opts_chunk: - collapse: true - comment: '#>' --- -```{r} -#| label: setup -#| eval: false -library(gdalraster.windows) -``` - -This guide covers how the [GDAL](https://gdal.org/) runtime is located, activated, and used from day to day: session activation, configuration, source builds of [`gdalraster`](https://firelab.github.io/gdalraster/), startup hooks, and embedded-python algorithms. For the build internals behind the runtime bundle, see the [Architecture](architecture.html) article. - -## How the runtime home is resolved - -Every helper in this package resolves the runtime location (`gdal_home`) through the same precedence chain: - -1. `options(gdalraster.windows.gdal_home = "...")` -2. the `GDALRASTER_WINDOWS_GDAL_HOME` environment variable -3. the package-managed user data directory (`tools::R_user_dir("gdalraster.windows", "data")`) - -```{r} -#| eval: false -# where the active runtime lives -gdalraster.windows::gdal_home() - -# point the session at a different runtime (option or env var, not persisted) -gdalraster.windows::configure_gdal_home("D:/gdal/custom-runtime", mode = "option") +## Runtime and installed-package roles + +The managed GDAL runtime is a build-time SDK. It provides headers, import +libraries, DLLs, data, and Python utilities to +`gdal_build_gdalraster()`. Runtime use is served entirely by files vendored +inside the resulting `gdalraster` package. + +```text +managed gdal_home/ + bin/*.dll + include/ + lib/ + share/gdal/ + share/proj/ + python/osgeo_utils/ + MANIFEST.dcf + +installed gdalraster/ + libs/x64/gdalraster.dll + libs/x64/libgdal-*.dll + libs/x64/ + gdal/ + proj/ + python/osgeo_utils/ + gdalraster.windows-build.dcf ``` -`configure_gdal_home()` is session-scoped by design — it never writes to profile files or machine state. +`library.dynam()` loads `gdalraster.dll` with the package's `libs/x64` +directory as its DLL path. Windows resolves the dependent `libgdal` and its +dependency closure from that same directory, including when another GDAL is +earlier on `PATH`. -## Session activation +## Runtime location -Windows resolves a DLL's imports at load time, so the bundle's `bin/` directory must be discoverable *before* `gdalraster.dll` loads. `activate_gdal_runtime()` prepares the session: - -- prepends `/bin` to `PATH` -- sets `GDAL_DATA`, `PROJ_LIB`, and `PROJ_DATA` to the bundle's `share/` data trees (GDAL and [PROJ](https://proj.org/) need their runtime data for CRS operations) -- prepends `/python` to `PYTHONPATH` for embedded-python algorithms -- preloads `libgdal-*.dll` into the process (when `preload = TRUE`, the default), so the DLL is already mapped when `gdalraster` asks for it - -All of this is session-scoped: no machine or user environment variables are modified. When preloading fails — most commonly because a dependency DLL is missing — activation fails immediately with an informative error instead of deferring to `library(gdalraster)`, where the Windows loader would only report a generic "module could not be found". - -```{r} -#| eval: false -gdalraster.windows::activate_gdal_runtime() -#> v gdal runtime activated from C:/Users/you/AppData/Roaming/R/data/R/gdalraster.windows/... -``` - -`load_gdal_dll()` is a convenience wrapper that activates with `preload = TRUE`: - -```{r} -#| eval: false -gdalraster.windows::load_gdal_dll() -``` +`gdal_home()` resolves: -## Automatic activation on load +1. `options(gdalraster.windows.gdal_home = "...")`; +2. `GDALRASTER_WINDOWS_GDAL_HOME`; then +3. the package-managed user data directory. -Attaching the package triggers a bootstrap that activates an installed runtime and prepends the isolated `gdalraster` library to `.libPaths()`, so in an already-set-up session this is all you need: +The option and environment variable are useful for tests, CI, and offline +SDKs. They do not affect later loading of a vendored `gdalraster`. -```{r} -#| eval: false -library(gdalraster.windows) -library(gdalraster) -``` +## Plumbing API -Two options control this behavior: +Use the lower-level functions when setup must be split: ```{r} #| eval: false -# disable the load-time bootstrap entirely -options(gdalraster.windows.auto_bootstrap = FALSE) - -# additionally auto-attach gdalraster from the isolated library at load time -options(gdalraster.windows.auto_load_gdalraster = TRUE) +gdalraster.windows::gdal_install_runtime() +gdalraster.windows::gdal_build_gdalraster() +gdalraster.windows::gdal_enable_python() +gdalraster.windows::gdal_verify() ``` -## Building gdalraster against the runtime +`gdal_install_runtime()` is idempotent. A matching `Bundle-Tag` in +`MANIFEST.dcf` is skipped. A newer release is reported without destructive +replacement; `gdal_update()` or `force = TRUE` performs replacement. -`install_gdalraster()` downloads (or accepts) a `gdalraster` source tarball from [firelab/gdalraster](https://github.com/firelab/gdalraster) and builds it against the bundle's headers and import library: +`gdal_build_gdalraster()` stages a complete package before replacing an +existing installation. If the destination is locked, the old package remains +unchanged. -```{r} -#| eval: false -# default: latest source from firelab/gdalraster, into the isolated library -gdalraster.windows::install_gdalraster() +## Provenance and staleness -# pin a specific ref, or build from a local tarball -gdalraster.windows::install_gdalraster(ref = "v2.1.0") -gdalraster.windows::install_gdalraster(source_tarball = "C:/tmp/gdalraster_2.1.0.tar.gz") +The runtime manifest records: -# pre-install gdalraster's R dependencies from CRAN before the source build -gdalraster.windows::install_gdalraster(upgrade = TRUE) -``` +- bundle tag and GDAL version; +- release asset name; +- installation time; and +- installer package version. -Compile and link flags (`GDAL_HOME`, `PKG_CPPFLAGS`, `PKG_LIBS`) are applied through a scoped Makevars file via [`withr::with_makevars()`](https://withr.r-lib.org/reference/with_makevars.html), and the runtime's `bin/` and data directories are exposed through scoped environment variables for the duration of the install. Nothing leaks into your persistent configuration. +The build manifest records the bundle tag and GDAL version plus R, platform, +compiler, build time, and builder package version. `gdal_sitrep()` compares the +two tags. A mismatch means `gdalraster` must be rebuilt. -The default destination is an isolated library (`/library`), so an existing CRAN `gdalraster` is left untouched. Loading from that isolated library is what `load_gdalraster()` does: +## Embedded Python -```{r} -#| eval: false -# activates the runtime, prepends the isolated library, attaches gdalraster -gdalraster.windows::load_gdalraster() -``` +Some algorithms, including `gdal driver gpkg validate`, embed CPython and +import `osgeo_utils`. `gdal_enable_python()` writes a managed file named +`gdalraster-windows-osgeo-utils.pth` into system CPython's `site-packages`. +The file points at the vendored `gdalraster/python` directory. -To make the source build your regular `gdalraster` instead, install it into your user library — accepting that it replaces whatever `gdalraster` is there: +This design does not set `PYTHONPATH`, does not modify user or machine +environment variables, and does not affect isolated virtual environments. +When no system CPython is available, core `gdalraster` remains usable and the +Python-specific check is reported as unavailable. -```{r} -#| eval: false -gdalraster.windows::install_gdalraster(lib = .libPaths()[1]) -``` - -## Startup hooks - -For sessions that should bootstrap without attaching this package, a managed `.Rprofile` hook loads the bundled GDAL DLL and prepends the isolated library at startup: +## Updates ```{r} #| eval: false -# preview the generated code without writing anything -cat(gdalraster.windows::gdal_rprofile_snippet()) - -# write (or update) the managed block in ~/.Rprofile -gdalraster.windows::add_gdal_rprofile_hook() - -# preview the resulting file contents without writing -gdalraster.windows::add_gdal_rprofile_hook(dry_run = TRUE) +gdalraster.windows::gdal_update() ``` -The hook is wrapped in `# >>> gdalraster.windows hook >>>` / `# <<< gdalraster.windows hook <<<` markers, guards itself with `requireNamespace()` and an OS check, and is updated in place on subsequent calls rather than appended repeatedly. - -## Embedded-python algorithms - -Some GDAL algorithms (e.g. [`gdal driver gpkg validate`](https://gdal.org/en/stable/programs/gdal_driver_gpkg_validate.html)) are thin C++ entry points around Python implementations: `libgdal` embeds a CPython interpreter at first use and imports the pure-python [`osgeo_utils`](https://github.com/OSGeo/gdal/tree/master/swig/python/gdal-utils) package. The runtime bundle ships `osgeo_utils` under `/python`, version-locked to the built GDAL, and activation exposes it via `PYTHONPATH`: +For a user-library installation: ```{r} #| eval: false -library(gdalraster.windows) -library(gdalraster) - -alg <- gdalraster::gdal_alg(cmd = "driver gpkg validate") -alg$setArg("dataset", "path/to/file.gpkg") -alg$setArg("full-check", TRUE) -alg$run() -alg$output() -#> [1] "Checking gpkg_spatial_ref_sys\n...\nValidation succeeded" +gdalraster.windows::gdal_update(user_lib = TRUE) ``` -A `python.exe` must be discoverable on `PATH` for GDAL to embed an interpreter at all — Rtools' UCRT64 python works, as does any system python. The compiled `osgeo` SWIG bindings are deliberately not bundled (they would pin the bundle to a single CPython ABI); the python-implemented validators degrade gracefully without them. - -## Upgrading the runtime +An update replaces the SDK, rebuilds from source, re-vendors every runtime +component, re-points the managed `.pth`, and verifies in a fresh process. -After a new [GDAL runtime release](https://github.com/jimbrig/gdalraster.windows/releases), reinstall the bundle and rebuild `gdalraster` against it — the previous `gdalraster.dll` is bound to the previous GDAL's ABI and import names: +## Uninstall ```{r} #| eval: false -# in a fresh session, before gdalraster is loaded -gdalraster.windows::install_gdal_runtime(overwrite = TRUE) -gdalraster.windows::install_gdalraster() -gdalraster.windows::verify_gdalraster_runtime() +gdalraster.windows::gdal_uninstall(force = TRUE) ``` -Overwriting is refused while `gdalraster` is loaded, because its DLL pins the runtime files in the current process; restart R first. When the session has merely preloaded the runtime (the auto-bootstrap does this at package load), the overwrite still works: old DLLs the session cannot release are moved into a stale sibling directory that later installs clean up, and the installer then advises an R restart before rebuilding or loading `gdalraster`. See the [Troubleshooting](troubleshooting.html) article if the install aborts with a lock error. +Set `user_lib = TRUE` only when the managed build was placed in the regular +user library. The uninstall removes the selected package, SDK, and managed +Python path file. diff --git a/vignettes/troubleshooting.qmd b/vignettes/troubleshooting.qmd index d147cc2..2b73cb6 100644 --- a/vignettes/troubleshooting.qmd +++ b/vignettes/troubleshooting.qmd @@ -4,145 +4,127 @@ vignette: > %\VignetteIndexEntry{Troubleshooting} %\VignetteEngine{quarto::html} %\VignetteEncoding{UTF-8} -knitr: - opts_chunk: - collapse: true - comment: '#>' --- +## Start with the sitrep + ```{r} -#| label: setup #| eval: false -library(gdalraster.windows) +gdalraster.windows::gdal_sitrep(user_lib = TRUE) +gdalraster.windows::gdal_verify(user_lib = TRUE) ``` -## Baseline triage +Omit `user_lib = TRUE` for the default isolated installation. The sitrep +reports runtime and build manifests, staleness, Python readiness, competing +GDAL DLLs, already loaded modules, legacy profile hooks, and foreign +`gdalraster` packages. + +## `library(gdalraster)` cannot find the package -Run these in order; most problems surface at one of these steps. +The non-destructive default installs into a package-managed isolated library. +Either load from that location or rebuild into the regular user library: ```{r} #| eval: false -# 1) where is the active runtime, and is the DLL there? -gdalraster.windows::gdal_home() -list.files( - file.path(gdalraster.windows::gdal_home(), "bin"), - pattern = "^libgdal-.*\\.dll$" -) - -# 2) activate runtime (PATH, data vars, PYTHONPATH, DLL preload) -gdalraster.windows::activate_gdal_runtime() - -# 3) end-to-end verification -gdalraster.windows::verify_gdalraster_runtime() +gdalraster.windows::gdal_setup(user_lib = TRUE) +library(gdalraster) ``` -If all three pass, the runtime contract is intact and the problem is elsewhere. - -## `gdal_global_reg_names()` returns `character(0)` +## `LoadLibrary` reports a missing module -Most likely the wrong GDAL DLL was resolved first, or activation never ran in this session. +A self-contained build must contain `gdalraster.dll`, `libgdal-*.dll`, and the +full dependency closure in the same `libs/x64` directory: -- Run `gdalraster.windows::activate_gdal_runtime()` in a **fresh** R session, then load `gdalraster`. -- Inspect `Sys.getenv("PATH")` for competing GDAL installations (Rtools, conda/pixi, OSGeo4W) appearing before the bundle's `bin/`. -- Confirm `gdalraster` was built by `install_gdalraster()` against the bundle, not installed as the CRAN binary (which statically links Rtools' GDAL). +```{r} +#| eval: false +package_dir <- find.package("gdalraster") +list.files(file.path(package_dir, "libs", "x64"), pattern = "\\.dll$") +``` -## `LoadLibrary failure` when loading gdalraster +Run `gdal_update()` to rebuild and re-vendor from a complete bundle. Do not add +Rtools or another GDAL to `PATH` as a repair; that defeats package isolation. -The Windows loader could not resolve `libgdal-*.dll` or one of its transitive dependencies. `activate_gdal_runtime()` fails loudly when the preload of `libgdal-*.dll` itself fails, so a `LoadLibrary failure` surfacing only at `library(gdalraster)` usually means the runtime was never activated in this session. +## Empty Algorithm API or missing drivers -- Activate the runtime before `library(gdalraster)` — or use `gdalraster.windows::load_gdalraster()`, which does both. -- Isolate profile effects with a clean subprocess: +`gdal_verify()` requires: -```powershell -Rscript -e "gdalraster.windows::activate_gdal_runtime(); library(gdalraster); print(length(gdalraster::gdal_global_reg_names()))" -``` +- a non-empty `gdal_global_reg_names()` result; +- Arrow, Parquet, HDF5, and netCDF drivers; +- GEOS and EPSG:4326 resolution; and +- a successful first Parquet open in a fresh process. -- Inspect the dependency tree from an [MSYS2](https://www.msys2.org/)/[Rtools](https://cran.r-project.org/bin/windows/Rtools/) shell with [ntldd](https://github.com/LRN/ntldd): `ntldd -R /bin/libgdal-*.dll` — any entry that resolves outside the bundle and outside Windows system paths indicates a missing bundled DLL. Or list direct imports with `objdump -x /bin/libgdal-*.dll | findstr "DLL Name"`. +If it fails, compare the runtime and build tags in `gdal_sitrep()`. A mismatch +requires `gdal_update()`. A matching build with missing drivers indicates a +bundle regression and should be reported with the verification output. -A DLL can be "missing" even when CI verified the bundle: GitHub runner images ship products that install DLLs into `System32` (e.g. the Microsoft ODBC Driver for SQL Server, `msodbcsql17.dll`), so a dependency on them resolves in CI but not on end-user machines. The build disables such linkage (`GDAL_USE_MSSQL_ODBC=OFF`) and bundle verification rejects known non-OS `System32` DLLs, but any import in the `objdump` output that is neither in the bundle's `bin/` nor a Windows system DLL is the culprit. +## Another GDAL is installed -## `LoadLibrary failure: A dynamic link library (DLL) initialization routine failed` +GDAL executables from pixi, conda, OSGeo4W, Rtools, or MSYS2 may remain on the +machine. The package's `libs/x64` directory controls dependency resolution +while `gdalraster.dll` loads. -This is a different failure class from "module could not be found" (Windows error 1114 vs 126). Every dependency was *found* and mapped into the process, but one of them failed its own initialization (`DllMain` / C++ static constructors), which makes the whole `libgdal-*.dll` load fail. Two properties make it confusing: +An identically named `libgdal` already loaded in the process is different: +Windows can reuse it by module name. Restart R, load `gdalraster` first, and +inspect `gdal_sitrep()` for the loaded module path. -- **Dependency-closure checks cannot detect it.** The bundle can be verified complete (`ntldd` reports every import resolved) and still fail this way — the broken DLL is present, it just cannot initialize. This is why bundle builds are also *load-tested* in CI (every DLL is passed through `LoadLibrary` in a plain process before an asset is published). -- **The same DLL bytes can load in one process and fail in another**, because its initializer's behavior depends on which copies of *its* dependencies the loader resolved (first-loaded-wins by base name). +## Legacy `.Rprofile` hooks -To isolate the culprit, sweep-load the bundle's DLLs individually in a fresh session — the failing one is rarely `libgdal` itself: +Version 0.4.0 removes activation and profile-hook APIs. Delete blocks marked: -```{r} -#| eval: false -bin <- file.path(gdalraster.windows::gdal_home(), "bin") -withr::local_envvar(PATH = paste(bin, Sys.getenv("PATH"), sep = ";")) -for (dll in list.files(bin, pattern = "\\.dll$", full.names = TRUE)) { - ok <- tryCatch( - { dyn.load(dll, local = FALSE, now = TRUE); TRUE }, - error = function(e) FALSE - ) - if (!ok) cat("FAILS TO INITIALIZE:", basename(dll), "\n") -} +```text +# >>> gdalraster.windows hook >>> +... +# <<< gdalraster.windows hook <<< ``` -Historical instance: bundles published before July 2026 shipped `libpodofo.dll` (a PDF-driver backend), whose static initializers run OpenSSL setup during `DllMain` and fail against the MSYS2-built `libcrypto-3-x64.dll` — in any process, R or not. Current bundles exclude the PDF driver entirely (`GDAL_ENABLE_DRIVER_PDF=OFF`) and CI refuses to publish a bundle containing any DLL that fails to load. If you see this error with a current bundle, reinstall the runtime first (`install_gdal_runtime(overwrite = TRUE)`), then run the sweep above and report the failing DLL in an issue. +Also remove personal code that calls `load_gdal_dll()`, +`activate_gdal_runtime()`, or edits GDAL-related environment variables. +Rebuild once with `gdal_setup()` after cleanup. -## `install_gdal_runtime(overwrite = TRUE)` cannot delete the old runtime +## Locked runtime directory -Deleting `gdal_home` fails when its DLLs are mapped into a running process — including the current session: the auto-bootstrap preloads the runtime at package load and prepends its `bin` to `PATH`, so DLLs loaded later in the session resolve dependencies from the runtime directory by module name (the release download itself loads the curl package, which maps the runtime's `zlib1.dll`). Those mappings live outside R's DLL registry, so unloading `libgdal` cannot release them. The installer handles this case itself: mapped DLLs cannot be deleted but can be renamed, so leftovers this session still maps are moved into a stale sibling directory (`.stale--`) and the install proceeds; later installs delete stale directories once their locks are gone. When the installer reports this, restart R before building or loading `gdalraster` so the new runtime is used. +Windows cannot delete mapped DLLs. `gdal_install_runtime(force = TRUE)` first +tries normal deletion, then moves remaining files into a sibling directory +named `.stale--`. Later installs remove stale +directories after locks disappear. -The installer refuses to run at all while `gdalraster` is loaded (its DLL pins the runtime — restart R first). If the install still aborts with a lock error, another process holds locks without delete sharing: other R sessions using the runtime, or File Explorer windows/preview panes open on the runtime directory. Close them ([PowerToys File Locksmith](https://learn.microsoft.com/en-us/windows/powertoys/file-locksmith) or Resource Monitor identify the locker) and rerun. +If move-aside also fails, another process holds the file without delete +sharing. Close other R sessions and File Explorer previews. PowerToys File +Locksmith or Resource Monitor can identify the holder. -## `ModuleNotFoundError: No module named 'osgeo_utils'` +## Locked `gdalraster` package -Raised by embedded-python algorithms such as [`gdal driver gpkg validate`](https://gdal.org/en/stable/programs/gdal_driver_gpkg_validate.html). See the [Runtime Guide](runtime-guide.html) for how the embedded-python layer works. +The builder stages the complete replacement before touching the installed +package. If the destination DLL is locked, replacement aborts and leaves the +old package unchanged. Restart R, ensure `gdalraster` is not loaded in another +session, then rerun the build. -- Check the bundle has the python layer: +## Embedded Python is unavailable -```{r} -#| eval: false -dir.exists(file.path(gdalraster.windows::gdal_home(), "python", "osgeo_utils")) -``` +`gdal_sitrep()` reports whether the managed +`gdalraster-windows-osgeo-utils.pth` points at the current vendored +`gdalraster/python` directory. -- If missing, the installed runtime predates python support — reinstall: +For a regular user-library build use: ```{r} #| eval: false -gdalraster.windows::install_gdal_runtime(overwrite = TRUE) +gdalraster.windows::gdal_enable_python(lib = .libPaths()[1]) ``` -- Re-activate and confirm `Sys.getenv("PYTHONPATH")` contains `/python`. -- A `python.exe` must be discoverable on `PATH` for GDAL to embed an interpreter at all (the GDAL debug stream shows which python/libpython it loads). - -Note: `validate_gpkg` treats the compiled `osgeo` bindings as optional; the bundle intentionally omits them, which skips only tiled gridded coverage content checks. - -## CRS / projection errors despite GDAL loading - -`GDAL_DATA` / `PROJ_DATA` are not pointing at the bundle's `share/` tree. `activate_gdal_runtime()` sets all three (`GDAL_DATA`, `PROJ_LIB`, `PROJ_DATA`); check whether something later in your startup overwrites them. +When no system CPython is available, core GDAL functionality remains ready, +but Python-backed algorithms such as `driver gpkg validate` cannot run. -## Download failures during `install_gdal_runtime()` +## Offline and proxy-restricted installation -On machines without network access (or behind strict proxies), install from a manually transferred release asset: +Transfer a published bundle zip and pass it directly: ```{r} #| eval: false -gdalraster.windows::install_gdal_runtime( - local_zip = "C:/Downloads/gdal-ucrt64-v3.13.1-windows-x64.zip" +gdalraster.windows::gdal_setup( + local_zip = "C:/Downloads/gdal-bundle-v3.13.2-windows-x64.zip" ) ``` -Assets are published at . - -## `install_gdalraster()` reports "source install did not produce an installed package" - -If `install_gdalraster()` fails with this error and R also printed a warning like `package '…tar.gz' is not available for this version of R`, the underlying cause was that `install.packages()` received `repos` set to a CRAN mirror together with a local file path. In that combination R looks the path up as a *package name* in the repository rather than installing from the file, so the install silently does nothing. - -This was fixed in `gdalraster.windows` ≥ 0.2.1 by always calling `install.packages()` with `repos = NULL` for local-file installation. If you encounter this with an older version, upgrade the package: - -```{r} -#| eval: false -pak::pak("jimbrig/gdalraster.windows") -``` - -## After a GDAL version upgrade - -- Reinstall the runtime (`install_gdal_runtime(overwrite = TRUE)`), then rebuild `gdalraster` against it (`install_gdalraster()`) — the previous `gdalraster.dll` is bound to the previous GDAL's ABI/import names. -- Never assume the GDAL SONAME is stable across versions; everything in this package discovers `libgdal-*.dll` by glob, and your own scripts should too. +The installer preserves an embedded manifest when present and otherwise +stamps provenance from the requested release information.