| 1 |
#' Read YAML data |
| 2 |
#' |
| 3 |
#' If the \pkg{yaml} package is installed, use [yaml::yaml.load()] to read the |
| 4 |
#' data. If not, use the simple parser [taml_load()] instead. |
| 5 |
#' @param x A character vector of YAML data. |
| 6 |
#' @param ...,handlers Arguments to be passed to [yaml::yaml.load()]. |
| 7 |
#' @param envir The environment in which R expressions in YAML are evaluated. To |
| 8 |
#' disable the evaluation, use `envir = FALSE`. |
| 9 |
#' @param use_yaml Whether to use the \pkg{yaml} package. |
| 10 |
#' @return An R object (typically a list). |
| 11 |
#' @note R expressions in YAML will be returned as [expression]s when they are |
| 12 |
#' not evaluated. This is different with [yaml::yaml.load()], which returns |
| 13 |
#' character strings for expressions. |
| 14 |
#' @export |
| 15 |
#' @examples |
| 16 |
#' yaml_load('a: 1') |
| 17 |
#' yaml_load('a: 1', use_yaml = FALSE) |
| 18 |
yaml_load = function( |
| 19 |
x, ..., handlers = NULL, envir = parent.frame(), use_yaml = loadable('yaml') |
| 20 |
) { |
| 21 |
if (!use_yaml) taml_load(x) else handle_error( |
| 22 |
yaml::yaml.load(x, eval.expr = FALSE, handlers = yaml_handlers(handlers, envir), ...), |
| 23 |
function(loc) { |
| 24 |
s = geterrmessage() |
| 25 |
r = 'line (\\d+), column (\\d+)' |
| 26 |
m = regmatches(s, regexec(r, s))[[1]] |
| 27 |
if (length(m) < 3) return() |
| 28 |
m = as.integer(m[-1]) # c(row, col) |
| 29 |
if (loc != '') loc = paste(' at lines', loc) |
| 30 |
c( |
| 31 |
sprintf('Failed to parse YAML%s:', loc), '', |
| 32 |
append(x, paste0(strrep(' ', m[2]), '^~~~~~'), m[1]), '' |
| 33 |
) |
| 34 |
} |
| 35 |
) |
| 36 |
} |
| 37 |
|
| 38 |
#' A simple YAML reader and writer |
| 39 |
#' |
| 40 |
#' TAML is a tiny subset of YAML. See |
| 41 |
#' <https://pkg.yihui.org/litedown/book/#sec:yaml-syntax> for its |
| 42 |
#' specifications. |
| 43 |
#' @param x For `taml_load()`, a character vector of the YAML content. For |
| 44 |
#' `taml_save()`, a list to be converted to YAML. |
| 45 |
#' @param path A file path to read from or write to. |
| 46 |
#' @inheritParams yaml_load |
| 47 |
#' @return `taml_load()` and `taml_file()` return a list; if `path = NULL`, |
| 48 |
#' `taml_save()` returns a character vector, otherwise the vector is written |
| 49 |
#' to the file specified by the `path`. |
| 50 |
#' @export |
| 51 |
#' @examples |
| 52 |
#' (res = taml_load('a: 1')) |
| 53 |
#' taml_save(res) |
| 54 |
#' |
| 55 |
#' (res = taml_load('a: 1\nb: "foo"\nc: null')) |
| 56 |
#' taml_save(res) |
| 57 |
#' |
| 58 |
#' (res = taml_load('a:\n b: false\n c: true\n d: 1.234\ne: bar')) |
| 59 |
#' taml_save(res) |
| 60 |
#' taml_save(res, indent = '\t') |
| 61 |
#' |
| 62 |
#' taml_load('a: !expr paste(1:10, collapse = ", ")') |
| 63 |
#' taml_load('a: [1, 3, 4, 2]') |
| 64 |
#' taml_load('a: [1, "abc", 4, 2]') |
| 65 |
#' taml_load('a: ["foo", "bar"]') |
| 66 |
#' taml_load('a: [true, false, true]') |
| 67 |
#' # the other form of array is not supported |
| 68 |
#' taml_load('a:\n - b\n - c') |
| 69 |
#' # and you must use the yaml package |
| 70 |
#' if (loadable('yaml')) yaml_load('a:\n - b\n - c') |
| 71 |
taml_load = function(x, envir = parent.frame()) { |
| 72 |
res = list() |
| 73 |
r = '^(\\s*)(.+?):($|\\s+.*)' |
| 74 |
x = split_lines(x) |
| 75 |
x = x[grep(r, x)] |
| 76 |
x = x[grep('^\\s*#', x, invert = TRUE)] # comments |
| 77 |
if (length(x) == 0) return(res) |
| 78 |
lvl = gsub(r, '\\1', x) # indentation level |
| 79 |
# skip array items (lines starting with `- `) and their indented children |
| 80 |
keep = rep(TRUE, length(x)) |
| 81 |
array_ind = -1 |
| 82 |
for (i in seq_along(x)) { |
| 83 |
ind = nchar(lvl[i]) |
| 84 |
if (array_ind >= 0) { |
| 85 |
if (ind > array_ind) { keep[i] = FALSE; next } |
| 86 |
array_ind = -1 |
| 87 |
} |
| 88 |
if (grepl('^\\s*- ', x[i])) { array_ind = ind; keep[i] = FALSE } |
| 89 |
} |
| 90 |
x = x[keep] |
| 91 |
if (length(x) == 0) return(res) |
| 92 |
lvl = indent_level(lvl[keep]) |
| 93 |
key = gsub(r, '\\2', x) |
| 94 |
val = gsub('^\\s*|\\s*$', '', gsub(r, '\\3', x)) |
| 95 |
keys = NULL |
| 96 |
for (i in seq_along(x)) { |
| 97 |
keys = c(head(keys, lvl[i]), key[i]) |
| 98 |
v = if (is_blank(val[i])) list() else yaml_value(val[i], envir) |
| 99 |
# special treatment of NULL (to preserve a key with a null value) |
| 100 |
if (is.null(v)) { |
| 101 |
if (length(keys) <= 1) res[keys] = list(v) else { |
| 102 |
res[[head(keys, -1)]][tail(keys, 1)] = list(v) |
| 103 |
} |
| 104 |
} else res[[keys]] = v |
| 105 |
} |
| 106 |
res |
| 107 |
} |
| 108 |
|
| 109 |
#' @rdname taml_load |
| 110 |
#' @export |
| 111 |
taml_file = function(path) taml_load(read_utf8(path)) |
| 112 |
|
| 113 |
#' @param indent A character string to indent sub-lists by one level. |
| 114 |
#' @rdname taml_load |
| 115 |
#' @export |
| 116 |
taml_save = function(x, path = NULL, indent = ' ') { |
| 117 |
res = .taml_save(x, indent) |
| 118 |
if (is.null(path)) raw_string(res, lang = '.yaml') else write_utf8(res, path) |
| 119 |
} |
| 120 |
|
| 121 |
.taml_save = function(x, indent = ' ', level = 1) { |
| 122 |
str2 = function(x) one_string(capture.output(str(x))) |
| 123 |
if (is.list(x)) { |
| 124 |
nms = names(x) |
| 125 |
if (is.null(nms)) { |
| 126 |
stop('Lists must be named:\n', str2(x)) |
| 127 |
} |
| 128 |
val = lapply(x, function(z) { |
| 129 |
if (!is.list(z)) .taml_save(z) else { |
| 130 |
.indent = strrep(indent, level) |
| 131 |
one_string(c('', paste0(.indent, .taml_save(z, indent, level + 1)))) |
| 132 |
} |
| 133 |
}) |
| 134 |
paste(nms, val, sep = ': ') |
| 135 |
} else { |
| 136 |
asis = inherits(x, 'AsIs') |
| 137 |
if (is.null(x)) return('null') |
| 138 |
if (is.logical(x)) x = tolower(x) else if (is.expression(x)) { |
| 139 |
x = unlist(lapply(x, deparse)) |
| 140 |
x = paste('!expr', paste(x, collapse = '\\n')) |
| 141 |
} else if (is.numeric(x) || is.character(x)) { |
| 142 |
if (!is.numeric(x) && length(x)) x = paste0('"', x, '"') |
| 143 |
} else { |
| 144 |
stop("Unsupported data type ('", class(x)[1], "'):\n", str2(x)) |
| 145 |
} |
| 146 |
if (length(x) == 1 && !asis) x else paste0('[', paste(x, collapse = ', '), ']') |
| 147 |
} |
| 148 |
} |
| 149 |
|
| 150 |
indent_level = function(x) { |
| 151 |
N = nchar(x) |
| 152 |
stack = -1L |
| 153 |
res = integer(length(N)) |
| 154 |
for (i in seq_along(N)) { |
| 155 |
n = N[i] |
| 156 |
while (tail(stack, 1) >= n) stack = stack[-length(stack)] |
| 157 |
res[i] = length(stack) - 1L |
| 158 |
stack = c(stack, n) |
| 159 |
} |
| 160 |
res |
| 161 |
} |
| 162 |
|
| 163 |
# only support logical, numeric, character values (both scalar and [] arrays), |
| 164 |
# and R expressions starting with !r/!expr |
| 165 |
yaml_value = function(x, envir = parent.frame()) { |
| 166 |
v = tolower(x) |
| 167 |
if (v == 'null') return() |
| 168 |
if (yaml_bool(v)) return(as.logical(x)) |
| 169 |
if (grepl(r <- '^\\s*\\[(.*)\\]\\s*$', v)) { |
| 170 |
v = gsub(r, '\\1', x) |
| 171 |
if (is_blank(v)) return() |
| 172 |
v = unname(unlist(read.csv(text = v, header = FALSE))) |
| 173 |
if (is.numeric(v)) return(v) |
| 174 |
v = gsub('^ ', '', v) # [a, b] -> ["a", " b"] -> ["a", "b"] |
| 175 |
return(if (yaml_bool(v)) as.logical(v) else yaml_unquote(v)) |
| 176 |
} |
| 177 |
if (grepl('^[0-9.e+-]', v)) { |
| 178 |
v = suppressWarnings(as.numeric(v)) |
| 179 |
if (!is.na(v)) return(if ((v2 <- as.integer(v)) == v) v2 else v) |
| 180 |
} |
| 181 |
if (grepl(r <- '^!(r|expr) (.+)$', x)) { |
| 182 |
yaml_expr(gsub(r, '\\2', x), envir) |
| 183 |
} else yaml_unquote(x) |
| 184 |
} |
| 185 |
|
| 186 |
# convert true/false/na to boolean |
| 187 |
yaml_bool = function(x) all(grepl('^(true|false|na)$', x)) |
| 188 |
# remove optional quotes for strings |
| 189 |
yaml_unquote = function(x) gsub('^["\']|["\']$', '', x) |
| 190 |
|
| 191 |
yaml_expr = function(x, envir) { |
| 192 |
x = parse_only(x) |
| 193 |
if (is.environment(envir)) x = eval(x, envir) |
| 194 |
x |
| 195 |
} |
| 196 |
|
| 197 |
# add !r and !expr handlers to support a custom eval environment, which |
| 198 |
# yaml::yaml.load() doesn't support by default (vubiostat/r-yaml#54) |
| 199 |
yaml_handlers = function(h, envir) { |
| 200 |
h = as.list(h) |
| 201 |
f = function(x) yaml_expr(x, envir) |
| 202 |
for (i in c('r', 'expr')) if (is.null(h[[i]])) h[[i]] = f |
| 203 |
h |
| 204 |
} |
| 205 |
|
| 206 |
#' Partition the YAML metadata and the body in a document |
| 207 |
#' |
| 208 |
#' Split a document into the YAML metadata (which starts with `---` in the |
| 209 |
#' beginning of the document) and the body. |
| 210 |
#' @param x A character vector of the document content. |
| 211 |
#' @param ... Arguments to be passed to `yaml_load()`. |
| 212 |
#' @param parse Whether to parse the YAML data. |
| 213 |
#' @export |
| 214 |
#' @return A list of components `yaml` (the YAML data), `lines` (starting and |
| 215 |
#' ending line numbers of YAML), and `body` (a character vector of the body |
| 216 |
#' text). If YAML metadata does not exist in the document, the components |
| 217 |
#' `yaml` and `lines` will be missing. |
| 218 |
#' @examples |
| 219 |
#' xfun::yaml_body(c('---', 'title: Hello', 'output: litedown::html_format', '---', '', 'Content.')) |
| 220 |
yaml_body = function(x, ..., parse = TRUE) { |
| 221 |
n = length(x) |
| 222 |
res = if (length(i <- locate_yaml(x)) == 0) { |
| 223 |
list(body = x) |
| 224 |
} else list( |
| 225 |
yaml = x[i[1]:i[2]], body = c(rep('', i[2]), tail(x, n - i[2])), lines = i |
| 226 |
) |
| 227 |
if ((n <- length(res$yaml)) >= 2) { |
| 228 |
res$yaml = res$yaml[-c(1, n)] |
| 229 |
if (parse) res['yaml'] = list(yaml_load(res$yaml, ...)) |
| 230 |
} |
| 231 |
res |
| 232 |
} |
| 233 |
|
| 234 |
# find lines of YAML |
| 235 |
locate_yaml = function(x) { |
| 236 |
i = grep('^---\\s*$', x) |
| 237 |
if (length(i) > 1 && all(is_blank(x[seq_len(i[1] - 1)]))) i[1:2] |
| 238 |
} |