% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/gdal_cli.R
\name{gdal_cli}
\alias{gdal_cli}
\alias{gdal_commands}
\alias{gdal_usage}
\alias{gdal_run}
\alias{gdal_run_piped}
\alias{gdal_alg}
\alias{gdal_global_reg_names}
\title{Functions for using GDAL CLI algorithms}
\usage{
gdal_commands(contains = NULL, recurse = TRUE, cout = TRUE)

gdal_usage(cmd = NULL)

gdal_run(
  cmd,
  args,
  close = FALSE,
  quiet = FALSE,
  setVectorArgsFromObject = TRUE
)

gdal_run_piped(
  input,
  cmd,
  output = NULL,
  output_format = NULL,
  other_args = NULL,
  output_index = 1,
  outputLayerNameForOpen = NULL
)

gdal_alg(cmd = NULL, args = NULL, parse = TRUE)

gdal_global_reg_names()
}
\arguments{
\item{contains}{Optional character string for filtering output to certain
commands, e.g., \code{gdal_commands("vector")}.}

\item{recurse}{Logical value, \code{TRUE} to include all subcommands recursively
(the default). Set to \code{FALSE} to include only the top-level \code{gdal} commands
(i.e., \code{raster}, \code{vector}, etc.)}

\item{cout}{Logical value, \code{TRUE} to print a list of commands along with
their descriptions and help URLS to the console (the default).}

\item{cmd}{A character string or character vector containing the path to the
algorithm, e.g., \code{"raster reproject"} or \code{c("raster", "reproject")}.
Defaults to \code{"gdal"}, the main entry point to CLI commands.}

\item{args}{Either a character vector or a named list containing input
arguments of the algorithm (see section \verb{Algorithm Argument Syntax} below).}

\item{close}{Logical value, \code{FALSE} by default. Set to \code{TRUE} to finalize
the algorithm immediately after it is run, which completes any pending
actions such as closing output datasets. This is useful if you do not need to
access the output as objects, e.g., when only generating file output for
later use. See \code{GDALAlg$close()}.}

\item{quiet}{Logical value, \code{FALSE} by default. Set to \code{TRUE} to suppress
progress reporting along with various messages and warnings. Sets the value
of \code{GDALAlg$quiet}.}

\item{setVectorArgsFromObject}{Logical value, \code{TRUE} to set algorithm
arguments automatically when the \code{"input"} argument or the \code{"like"} argument
is an object of class \code{GDALVector} (the default). Can be set to \code{FALSE} to
disable automatically setting algorithm arguments from \code{GDALVector} input
(see Note).}

\item{input}{Value passed as input to the GDAL algorithm specified in \code{cmd}
(i.e., the \code{"input"}, \code{"dataset"} or \code{"source"} argument for the command).
Typically this is a dataset name (e.g., file or database connection string),
or an object of class \code{GDALRaster} or \code{GDALVector}.}

\item{output}{Value passed for the \code{"output"} (or \code{"destination"}) argument
of \code{cmd}. Typically this is a filename for commands that generate a raster
or vector dataset or other file output. May be \code{NULL} or empty string (\code{""})
if \code{output_format} is \code{"MEM"} (in-memory dataset).}

\item{output_format}{Optional character string specifying the output format,
e.g., a format driver short name when output is a raster or vector dataset.
Will be passed to the algorithm's optional \code{"output-format"} argument.}

\item{other_args}{Either a character vector or a named list containing other
input arguments of the algorithm (i.e., other than those already specified
via \code{input}, \code{output} and \code{output_format} above, see also the section
\verb{Algorithm Argument Syntax} below).}

\item{output_index}{Optional numeric value or character string giving the
list index or output argument name for an algorithm with more than one
output. Defaults to \code{1}.}

\item{outputLayerNameForOpen}{Optional character string specifying a layer
name to open when obtaining algorithm output as an object of class
\code{GDALVector} (see the class method \link[=GDALAlg]{GDALAlg$output()}). Defaults to
empty string (\code{""}) in which case the first layer by index is opened.
Ignored if output is not a vector dataset.}

\item{parse}{Logical value, \code{TRUE} to attempt parsing \code{args} if they are
given in \code{gdal_alg()} (the default). Set to \code{FALSE} to instantiate the
algorithm without parsing arguments. The \code{$parseCommandLineArgs()}
method on the returned object can be called to parse arguments and obtain
the result of that, with potentially useful error messages.}
}
\description{
This set of functions can be used to access and run \code{gdal} command line
interface (CLI) algorithms.

\strong{Requires GDAL >= 3.11.3}

\strong{Experimental} (see the section \verb{Development Status} below)
}
\details{
These functions provide an interface to GDAL CLI algorithms by way of the
C++ exposed class \code{\link{GDALAlg}}. See the class documentation for
additional information (\code{?GDALAlg}).

\code{gdal_commands()} prints a list of commands and their descriptions to the
console, and returns (invisibly) a data frame with columns \code{command},
\code{description}, \code{URL}. The \code{contains} argument can be used to filter the
output, e.g., \code{gdal_commands("vector")} to return only commands for working
with vector inputs.

\code{gdal_usage()} prints a help message to the console for a given command, or
for the root \code{gdal} entry point if called with no argument. No return value,
called for that side effect only.

\code{gdal_run()} executes a GDAL CLI algorithm and returns it as an object of
class \code{\link{GDALAlg}}. A list containing algorithm output(s) can be
accessed by calling the \code{$outputs()} method (plural) on the returned
object, or, more conveniently in most cases, by calling \code{$output()}
(singular) to return the the single output value when there is only one.
After assigning the output, or otherwise completing work with the \code{GDALAlg}
object, its \code{$release()} method can be called to close datasets and
free resources.

\code{gdal_run_piped()} is a variation of \code{gdal_run()}. It is suitable for use
with the R native pipe operator (\verb{|>}), but may be useful stand-alone when
it is desirable to obtain the output of the algorithm directly, and access
to the \code{GDALAlg} object itself is not needed. The first argument to this
function is passed to the \code{"input"} (or \code{"dataset"} or \code{"source"}) argument
of the algorithm (i.e., as input to the GDAL command specified in \code{cmd}). The
function returns (invisibly) the output of the CLI algorithm if it has one.
If the algorithm has multiple outputs, the first by index is returned by
default but this can be controlled by the \code{output_index} argument (numeric
index or character name of the desired output). Logical \code{TRUE} is returned
invisibly if the algorithm has no output and no error was reported by the
\code{run()} method of the algorithm object. Logical \code{FALSE} is returned invisibly
but a message printed if an error occurs. The algorithm object used
internally is always finalized before return.

\code{gdal_alg()} instantiates and returns an object of class \code{\link{GDALAlg}}
without running it. Passing argument values to the requested CLI algorithm is
optional. This function may be useful (with or without argument values) for
obtaining algorithm properties with the returned object's \code{$info()}
method, obtaining properties of algorithm arguments
(\code{$argInfo(arg_name)}), or obtaining algorithm usage as a
JSON-formatted string (\code{$usageAsJSON()}).
This function is simply an alternative to calling the \code{new()} constructor
for class \code{GDALAlg}. Executing the returned algorithm is optional by calling
the object's \code{$run()} method (assuming argument values were given).

\code{gdal_global_reg_names()} returns a character vector containing the names of
the algorithms in the GDAL global algorithm registry. These are the
top-level nodes (\code{raster}, \code{vector}, etc.) known to GDAL. Potentially code
external to GDAL could register a new command available for CLI use in a
GDAL plugin. This function may be useful in certain troubleshooting
scenarios. It will return a vector of length zero if no names are returned
from the global registry.
}
\note{
Commands do not require the leading \code{"gdal"} root node. They may begin
with a top-level command (e.g., \code{"raster"}, \code{"vector"}, etc.).

When using argument names as the element names of a list, the underscore
character can be substituted for the dash characters that are used in some
names. This avoids having to surround names in backticks when they are used
to access list elements in the form \code{args$arg_name} (the form
\code{args[["arg-name"]]} also works).

When \code{setVectorArgsFromObject} is \code{TRUE} (the default) and the \code{"input"} or
\code{"like"} argument for an algorithm is given as a \code{GDALVector} object,
corresponding algorithm arguments will be set automatically based on
properties of the object (when the argument is available to the algorithm):
\itemize{
\item \code{"input-format"}: set to the \code{GDALVector} object's driver short name
\item \code{"input-layer"}: set to the \code{GDALVector} layer name if it is not a SQL
layer
\item \code{"sql"}: set to the SQL statement if the \code{GDALVector} layer is defined by
one
\item \code{"dialect"}: set to the SQL dialect if one is specified for a SQL layer
\item \code{"like-layer"}: set to the \code{GDALVector} layer name if it is not a SQL
layer
\item \code{"like-sql"}: set to the SQL statement if the \code{GDALVector} layer is
defined by one
}

Argument values specified explicitly will override the automatic setting (as
long as they result in a parsable set of arguments). If
\code{setVectorArgsFromObject} is \code{FALSE}, then only the vector dataset is passed
to the algorithm, i.e., without automatically passing any layer
specifications.
}
\section{Algorithm Argument Syntax}{

Arguments are given in \R as a character vector or named list, but
otherwise syntax basically matches the GDAL specification for arguments as
they are given on the command line. Those specifications are listed here
along with some amendments regarding the character vector and named list
formats. Programmatic usage also allows passing and receiving datasets as
objects (i.e., \code{GDALRaster} or \code{GDALVector}), in addition to dataset names
(e.g., filename, URL, database connection string).
\itemize{
\item Commands accept one or several positional arguments, typically for dataset
names (or in \R as \code{GDALRaster} or \code{GDALVector} datasets). The order is
input(s) first, output last. Positional arguments can also be specified as
named arguments, if preferred to avoid any ambiguity.
\item Named arguments have:
\itemize{
\item at least one "long" name, preceded by two dash characters
\item optionally, auxiliary long names (i.e., aliases),
\item and optionally a one-letter short name, preceded by a single dash
character, e.g., \code{-f, --of, --format, --output-format <OUTPUT-FORMAT>}
}
\item Boolean arguments are specified by just specifying the argument name in
character vector format. In \R \code{list} format, the named element must be
assigned a value of logical \code{TRUE}.
\item Arguments that require a value are specified like:
\itemize{
\item \code{-f VALUE} for one-letter short names
\item \code{--format VALUE} or \code{--format=VALUE} for long names
\item in a named list, this might look like: \code{args$format <- VALUE}
}
\item Some arguments can be multi-valued. Some of them require all values to be
packed together and separated with comma. This is, e.g., the case of:\cr
\code{--bbox <BBOX> Clipping bounding box as xmin,ymin,xmax,ymax} \cr
e.g., \code{--bbox=2.1,49.1,2.9,49.9}
\item Others accept each value to be preceded by a new mention of the argument
name, e.g., \code{c("--co", "COMPRESS=LZW", "--co", "TILED=YES")}. For that
one, if the value of the argument does not contain commas, the packed form
is also accepted: \code{--co COMPRESS=LZW,TILED=YES}. Note that repeated
mentions of an argument are possible in the character vector format for
argument input, whereas arguments given in named list format must use
argument long names as the list element names, and the packed format for the
values (which can be a character vector or numeric vector of values).
\item Named arguments can be placed before or after positional arguments.
}
}

\section{Development Status}{

The GDAL Command Line Interface Modernization was first introduced in the
\href{https://github.com/OSGeo/gdal/releases/tag/v3.11.0}{GDAL 3.11.0 release}
(2025-05-09). The GDAL project provides warning that the new CLI "is
provisionally provided as an alternative interface to GDAL and OGR command
line utilities. The project reserves the right to modify, rename,
reorganize, and change the behavior until it is officially frozen via PSC
vote in a future major GDAL release. The utility needs time to mature,
benefit from incremental feedback, and explore enhancements without carrying
the burden of full backward compatibility. Your usage of it should have no
expectation of compatibility until that time."
(\url{https://gdal.org/en/latest/programs/#gdal-application})

Initial bindings to enable programmatic use of the CLI algorithms from \R
were added in \pkg{gdalraster} 2.2.0, and will evolve over future releases.
\emph{The bindings are considered experimental until the upstream API is declared
stable}. Breaking changes in minor version releases are possible until then.
Please use with those cautions in mind. Bug reports may be filed at:
\url{https://github.com/firelab/gdalraster/issues}.
}

\examples{
\dontshow{if (length(gdal_global_reg_names()) > 0) withAutoprint(\{ # examplesIf}
## top-level commands
gdal_commands(recurse = FALSE)

## convert storml_elev.tif to GeoPackage raster
gdal_commands("convert")

gdal_usage("raster convert")

f_tif <- system.file("extdata/storml_elev.tif", package="gdalraster")
f_gpkg <- file.path(tempdir(), "storml_elev.gpkg")
args <- c("--overwrite", f_tif, f_gpkg)

# finalize the algorithm immediately after it is run if only generating
# file output for later use:
# gdal_run("raster convert", args, close = TRUE)

# or, assign to a variable and access algorithm output as a dataset object
(alg <- gdal_run("raster convert", args))

(ds <- alg$output())

alg$release()

plot_raster(ds, legend = TRUE)

ds$close()
unlink(f_gpkg)

## use the R native pipe operator

if (requireNamespace("ltc")) {
  # make a of plot of 'terrain ruggedness index' (TRI) for Storm Lake AOI
  system.file("extdata/storml_elev.tif", package="gdalraster") |>
    gdal_run_piped("raster tri", "", "MEM") |>
    plot_raster(legend = TRUE,
                minmax_pct_cut = c(0, 99),
                col_map_fn = rev(ltc::ltc("heatmap3")),
                main = "Storm Lake AOI: terrain ruggedness index")
}

## get help for vector commands
gdal_usage("vector")

## clip a vector layer by a bounding box
gdal_usage("vector clip")

f <- system.file("extdata/ynp_fires_1984_2022.gpkg", package="gdalraster")
f_clip <- file.path(tempdir(), "ynp_fires_clip.gpkg")

# some multi-valued arguments require all values packed and comma separated
# e.g., --bbox <BBOX>
bb <- c(469686, 11442, 544070, 85508)
bb <- paste(bb, collapse = ",")

args <- c("--bbox", bb, "--overwrite", f, f_clip)
(alg <- gdal_run("vector clip", args))

(lyr <- alg$output())

lyr$bbox()

lyr$getFeatureCount()

lyr$close()
alg$release()
unlink(f_clip)

## rasterize a vector layer and return output as a GDALRaster object
gdal_usage("vector rasterize")

f_out = file.path(tempdir(), "ynp_fire_year.tif")

# arguments in list format
args <- list(input = f,
             sql = "SELECT * FROM mtbs_perims ORDER BY ig_year",
             attribute_name = "ig_year",
             output = f_out,
             overwrite = TRUE,
             creation_option = c("TILED=YES", "COMPRESS=DEFLATE"),
             resolution = c(90, 90),
             output_data_type = "Int16",
             init = -32767,
             nodata = -32767)

(alg <- gdal_run("vector rasterize", args))

(ds <- alg$output())

alg$release()

if (requireNamespace("scales")) {
  pal <- scales::viridis_pal(end = 0.8, direction = -1)(6)
  ramp <- scales::colour_ramp(pal)
  plot_raster(ds, legend = TRUE, col_map_fn = ramp, na_col = "#d9d9d9",
              main = "YNP Fires 1984-2022 - Most Recent Burn Year")
}

ds$close()
deleteDataset(f_out)

## GDAL CLI pipeline syntax
# "raster pipeline" example 2 from:
# https://gdal.org/en/latest/programs/gdal_raster_pipeline.html
# serialize the command to reproject a GTiff file into GDALG format, and
# then later read the GDALG file
# GDAL Streamed Algorithm format:
# https://gdal.org/en/stable/drivers/raster/gdalg.html

gdal_usage("raster pipeline")

f_tif <- system.file("extdata/storml_elev.tif", package="gdalraster")
f_out <- file.path(tempdir(), "storml_elev_epsg_32100.gdalg.json")

args <- c("read", "--input", f_tif, "!",
          "reproject", "--dst-crs=EPSG:32100", "!",
          "write", "--output", f_out, "--overwrite")

alg <- gdal_run("raster pipeline", args)
alg$release()

# content of the .gdalg.json file
readLines(f_out, warn = FALSE) |> writeLines()

(ds <- new(GDALRaster, f_out))

plot_raster(ds, legend = TRUE)

ds$close()
unlink(f_out)
\dontshow{\}) # examplesIf}
}
\seealso{
\code{\link[=GDALAlg]{GDALAlg-class}}

\code{gdal} Command Line Interface (CLI) \cr
\url{https://gdal.org/en/stable/programs/index.html}

Using \code{gdal} CLI algorithms from R\cr
\url{https://firelab.github.io/gdalraster/articles/use-gdal-cli-from-r.html}
}
