Debian Codegraph @

R/database.R

raw
1 .startup_msg <- function(warn = FALSE) {
2 paste("udunits database from" , default_units_xml(warn))
3 }
4
5 default_units_xml <- function(warn = FALSE) {
6 paths = c(
7 Sys.getenv("UDUNITS2_XML_PATH"),
8 "/usr/local/share/udunits/udunits2.xml",
9 "/usr/share/xml/udunits/udunits2.xml",
10 "/usr/share/udunits/udunits2.xml")
11
12 fallback = system.file("share/udunits/udunits2.xml", package="units")
13
14 w = which(file.exists(paths))
15 if (length(w) > 1 && warn)
16 warning(paste("multiple udunits databases present:\n - "),
17 paste(paths[w], collapse = "\n - "), call.=FALSE)
18 p = if (length(w) == 0) fallback else paths[w[1]]
19
20 if (!file.exists(p))
21 stop("Failed to identify udunits database: units will not work properly.",
22 "\nPlease set the UDUNITS2_XML_PATH environment variable before ",
23 "attempting to read the units database")
24 p
25 }
26
27 #' Load a unit system
28 #'
29 #' Load an XML database containing a unit system compatible with UDUNITS2.
30 #'
31 #' A unit system comprises a root \code{<unit-system>} and a number of children
32 #' defining prefixes (\code{<prefix>}) or units (\code{<unit>}).
33 #' See the contents of
34 #'
35 #' \code{system.file("share/udunits", package="units")}
36 #'
37 #' for examples.
38 #'
39 #' @param path a path to a valid unit system in XML format.
40 #'
41 #' @examples
42 #' # load a new unit system
43 #' load_units_xml(system.file("share/udunits/udunits2-base.xml", package="units"))
44 #' \dontrun{
45 #' set_units(1, rad) # doesn'twork
46 #' }
47 #'
48 #' # reload the default unit system
49 #' load_units_xml()
50 #' set_units(1, rad) # works again
51 #'
52 #' @export
53 load_units_xml <- function(path = default_units_xml()) {
54 if (.Platform$OS.type == "windows")
55 path <- shortPathName(path)
56 ud_init(path)
57 }
58
59 .read_ud_db <- function(path = default_units_xml(), type) {
60 if (! requireNamespace("xml2", quietly = TRUE))
61 stop("package 'xml2' is required for this functionality", call.=FALSE)
62
63 db <- xml2::read_xml(path)
64
65 # resolve imports
66 imports <- xml2::xml_find_all(db, "import")
67 files <- sapply(imports, xml2::xml_text)
68 for (i in files) {
69 import <- xml2::read_xml(file.path(dirname(path), i))
70 for (child in xml2::xml_children(import)) {
71 source <- gsub("udunits2-|\\.xml", "", i)
72 source <- paste0("<doc><source>", source, "</source></doc>")
73 source <- xml2::xml_child(xml2::read_xml(source))
74 xml2::xml_add_child(child, source)
75 xml2::xml_add_child(db, child)
76 }
77 }
78 xml2::xml_remove(imports)
79
80 # filter by type
81 if (!missing(type)) {
82 children <- xml2::xml_children(db)
83 xml2::xml_remove(children[xml2::xml_name(children) != type])
84 }
85
86 db
87 }