Debian Codegraph @

R/io.R

raw
1 #' Read / write files encoded in UTF-8
2 #'
3 #' Read or write files, assuming they are encoded in UTF-8. `read_utf8()` is
4 #' roughly `readLines(encoding = 'UTF-8')` (a warning will be issued if non-UTF8
5 #' lines are found), and `write_utf8()` calls `writeLines(enc2utf8(text),
6 #' useBytes = TRUE)`.
7 #'
8 #' The function `append_utf8()` appends UTF-8 content to a file or connection
9 #' based on `read_utf8()` and `write_utf8()`, and optionally sort the content.
10 #' The function `append_unique()` appends unique lines to a file or connection.
11 #' @param con A connection or a file path.
12 #' @param error Whether to signal an error when non-UTF8 characters are detected
13 #' (if `FALSE`, only a warning message is issued).
14 #' @param binary Whether to read the file via a binary-mode connection. On
15 #' Windows, [readLines()] on a text-mode connection (the default) treats a
16 #' `Ctrl+Z` byte (`\x1a`) as end-of-file and silently truncates the file
17 #' (e.g., self-contained HTML embedding the PNG signature
18 #' `\x89PNG\r\n\x1a\n` in JavaScript). Set `binary = TRUE` to read the whole
19 #' file regardless of `Ctrl+Z` bytes (this has a small overhead and is only
20 #' necessary on Windows). This argument is only used when `con` is a file
21 #' path.
22 #' @param text A character vector (will be converted to UTF-8 via [enc2utf8()]).
23 #' @param ... Other arguments passed to [writeLines()] (except `useBytes`, which
24 #' is `TRUE` in `write_utf8()`).
25 #' @return `read_utf8()` returns a character vector of the file content;
26 #' `write_utf8()` returns the `con` argument (invisibly).
27 #' @export
28 read_utf8 = function(con, error = FALSE, binary = FALSE) {
29 # Reading via a binary connection avoids readLines() treating a Ctrl+Z byte
30 # (\x1a) as end-of-file on Windows (see the 'binary' argument documentation).
31 f = if (is.character(con)) con # remember the file path for the message below
32 if (is.character(con) && binary) {
33 con = file(con, 'rb', encoding = 'UTF-8'); on.exit(close(con), add = TRUE)
34 }
35 # users may have set options(encoding = 'UTF-8'), which usually won't help but
36 # will bring more trouble than good, so we reset this option temporarily
37 opts = options(encoding = 'native.enc'); on.exit(options(opts), add = TRUE)
38 x = readLines(con, encoding = 'UTF-8', warn = FALSE)
39 i = invalid_utf8(x)
40 n = length(i)
41 if (n > 0) (if (error) stop else warning)(
42 if (!is.null(f)) c('The file ', f, ' is not encoded in UTF-8. '),
43 'These lines contain invalid UTF-8 characters: ',
44 paste(c(head(i), if (n > 6) '...'), collapse = ', ')
45 )
46 x
47 }
48
49 #' @rdname read_utf8
50 #' @export
51 write_utf8 = function(text, con, ...) {
52 if (is.null(text)) text = character(0)
53 if (identical(con, '')) {
54 cat(text, sep = '\n', file = con)
55 } else {
56 # prevent re-encoding the text in the file() connection in writeLines()
57 # https://kevinushey.github.io/blog/2018/02/21/string-encoding-and-r/
58 opts = options(encoding = 'native.enc'); on.exit(options(opts), add = TRUE)
59 writeLines(enc2utf8(text), con, ..., useBytes = TRUE)
60 }
61 invisible(con)
62 }
63
64 #' @param sort Logical (`FALSE` means not to sort the content) or a
65 #' function to sort the content; `TRUE` is equivalent to
66 #' `base::sort`.
67 #' @rdname read_utf8
68 #' @export
69 append_utf8 = function(text, con, sort = TRUE) {
70 x = read_utf8(con, error = TRUE)
71 x = c(x, text)
72 if (is.logical(sort)) sort = if (sort) base::sort else identity
73 if (is.function(sort)) x = sort(x)
74 write_utf8(x, con)
75 }
76
77 #' @rdname read_utf8
78 #' @export
79 append_unique = function(text, con, sort = function(x) base::sort(unique(x))) {
80 append_utf8(text, con, sort)
81 }
82
83 # which lines are invalid UTF-8
84 invalid_utf8 = function(x) {
85 which(!is_utf8(x))
86 }
87
88 test_utf8 = function(x) {
89 is.na(x) | !is.na(iconv(x, 'UTF-8', 'UTF-8'))
90 }
91
92 # validUTF8() was added to base R 3.3.0
93 is_utf8 = function(x) {
94 if ('validUTF8' %in% ls(baseenv())) validUTF8(x) else test_utf8(x)
95 }
96
97 #' Read a text file and concatenate the lines by `'\n'`
98 #'
99 #' The source code of this function should be self-explanatory.
100 #' @param file Path to a text file (should be encoded in UTF-8).
101 #' @return A character string of text lines concatenated by `'\n'`.
102 #' @export
103 #' @examples
104 #' xfun::file_string(system.file('DESCRIPTION', package = 'xfun'))
105 file_string = function(file) {
106 x = read_utf8(file)
107 # paste converts 0-length character() into 1-length ""
108 if (length(x)) x = paste(x, collapse = '\n')
109 raw_string(x)
110 }
111
112 #' Read all records of a binary file as a raw vector by default
113 #'
114 #' This is a wrapper function of [readBin()] with default arguments
115 #' `what = "raw"` and `n = `[`file.size`]`(file)`, which means it
116 #' will read the full content of a binary file as a raw vector by default.
117 #' @param file,what,n,... Arguments to be passed to `readBin()`.
118 #' @return A vector returned from `readBin()`.
119 #' @export
120 #' @examples
121 #' f = tempfile()
122 #' cat('abc', file = f)
123 #' xfun::read_bin(f)
124 #' unlink(f)
125 read_bin = function(file, what = 'raw', n = file.info(file)$size, ...) {
126 readBin(file, what, n, ...)
127 }
128
129 #' Read all text files and concatenate their content
130 #'
131 #' Read files one by one, and optionally add text before/after the content. Then
132 #' combine all content into one character vector.
133 #' @param files A vector of file paths.
134 #' @param before,after A function that takes one file path and its content as
135 #' the input and returns values to be added before or after the content of the
136 #' file. Alternatively, they can be constant values to be added.
137 #' @return A character vector.
138 #' @export
139 #' @examples
140 #' # two files in this package
141 #' fs = system.file('scripts', c('call-fun.R', 'child-pids.sh'), package = 'xfun')
142 #' xfun::read_all(fs)
143 #'
144 #' # add file paths before file content and an empty line after content
145 #' xfun::read_all(fs, before = function(f) paste('#-----', f, '-----'), after = '')
146 #'
147 #' # add constants
148 #' xfun::read_all(fs, before = '/*', after = c('*/', ''))
149 read_all = function(files, before = function(f, x) NULL, after = function(f, x) NULL) {
150 call_fun = function(fun, x, ...) {
151 if (is.function(fun)) {
152 if (length(formals(fun)) > 1) fun(x, ...) else fun(x)
153 } else fun
154 }
155 x = unlist(lapply(files, function(f) {
156 t = read_utf8(f)
157 c(call_fun(before, f, t), t, call_fun(after, f, t))
158 }))
159 raw_string(x)
160 }
161
162 #' Read a text file, process the text with a function, and write the text back
163 #'
164 #' Read a text file with the UTF-8 encoding, apply a function to the text, and
165 #' write back to the original file if the processed text is different with the
166 #' original input.
167 #'
168 #' `sort_file()` is an application of `process_file()`, with the processing
169 #' function being [sort()], i.e., it sorts the text lines in a file and write
170 #' back the sorted text.
171 #' @param file Path to a text file.
172 #' @param fun A function to process the text.
173 #' @param x The content of the file.
174 #' @param ... Arguments to be passed to `process_file()`.
175 #' @return If `file` is provided, invisible `NULL` (the file is updated as a
176 #' side effect), otherwise the processed content (as a character vector).
177 #' @export
178 #' @examples f = tempfile()
179 #' xfun::write_utf8('Hello World', f)
180 #' xfun::process_file(f, function(x) gsub('World', 'woRld', x))
181 #' xfun::read_utf8(f) # see if it has been updated
182 #' file.remove(f)
183 process_file = function(file, fun = identity, x = read_utf8(file)) {
184 x2 = fun(x)
185 if (missing(file)) x2 else {
186 if ((length(x2) != length(x)) || !all(x2 == x)) write_utf8(x2, file)
187 }
188 }
189
190 #' @rdname process_file
191 #' @export
192 sort_file = function(..., fun = sort) {
193 process_file(fun = fun, ...)
194 }
195
196 #' Search and replace strings in files
197 #'
198 #' These functions provide the "file" version of [gsub()], i.e.,
199 #' they perform searching and replacement in files via `gsub()`.
200 #' @param file Path of a single file.
201 #' @param ... For `gsub_file()`, arguments passed to `gsub()`. For
202 #' other functions, arguments passed to `gsub_file()`. Note that the
203 #' argument `x` of `gsub()` is the content of the file.
204 #' @param rw_error Whether to signal an error if the file cannot be read or
205 #' written. If `FALSE`, the file will be ignored (with a warning).
206 #' @param files A vector of file paths.
207 #' @param dir Path to a directory (all files under this directory will be
208 #' replaced).
209 #' @param recursive Whether to find files recursively under a directory.
210 #' @param ext A vector of filename extensions (without the leading periods).
211 #' @param mimetype A regular expression to filter files based on their MIME
212 #' types, e.g., `'^text/'` for plain text files.
213 #' @note These functions perform in-place replacement, i.e., the files will be
214 #' overwritten. Make sure you backup your files in advance, or use version
215 #' control!
216 #' @export
217 #' @examples library(xfun)
218 #' f = tempfile()
219 #' writeLines(c('hello', 'world'), f)
220 #' gsub_file(f, 'world', 'woRld', fixed = TRUE)
221 #' readLines(f)
222 gsub_file = function(file, ..., rw_error = TRUE) {
223 if (!(file.access(file, 2) == 0 && file.access(file, 4) == 0)) {
224 (if (rw_error) stop else warning)('Unable to read or write to ', file)
225 if (!rw_error) return(invisible())
226 }
227 x1 = tryCatch(read_utf8(file, error = TRUE), error = function(e) if (rw_error) stop(e))
228 if (is.null(x1)) return(invisible())
229 x2 = gsub(x = x1, ...)
230 if (!identical(x1, x2)) write_utf8(x2, file)
231 }
232
233 #' @rdname gsub_file
234 #' @export
235 gsub_files = function(files, ...) {
236 for (f in files) gsub_file(f, ...)
237 }
238
239 #' @rdname gsub_file
240 #' @export
241 gsub_dir = function(..., dir = '.', recursive = TRUE, ext = NULL, mimetype = '.*') {
242 files = list.files(dir, full.names = TRUE, recursive = recursive)
243 if (length(ext)) files = files[file_ext(files) %in% ext]
244 if (mimetype != '.*') files = files[grep(mimetype, mime_type(files))]
245 gsub_files(files, ...)
246 }
247
248 #' @rdname gsub_file
249 #' @export
250 gsub_ext = function(ext, ..., dir = '.', recursive = TRUE) {
251 gsub_dir(..., dir = dir, recursive = recursive, ext = ext)
252 }
253
254 #' Perform replacement with `gsub()` on elements matched from `grep()`
255 #'
256 #' This function is a shorthand of `gsub(pattern, replacement,
257 #' grep(pattern, x, value = TRUE))`.
258 #' @param pattern,replacement,x,... Passed to [grep()] and
259 #' `gsub()`.
260 #' @return A character vector.
261 #' @export
262 #' @examples # find elements that matches 'a[b]+c' and capitalize 'b' with perl regex
263 #' xfun::grep_sub('a([b]+)c', 'a\\U\\1c', c('abc', 'abbbc', 'addc', '123'), perl = TRUE)
264 grep_sub = function(pattern, replacement, x, ...) {
265 x = grep(pattern, x, value = TRUE, ...)
266 gsub(pattern, replacement, x, ...)
267 }
268
269 #' Try various methods to download a file
270 #'
271 #' Try all possible methods in [download.file()] (e.g., `libcurl`, `curl`,
272 #' `wget`, and `wininet`) and see if any method can succeed. The reason to
273 #' enumerate all methods is that sometimes the default method does not work,
274 #' e.g., <https://stat.ethz.ch/pipermail/r-devel/2016-June/072852.html>.
275 #' @param url The URL of the file.
276 #' @param output Path to the output file. By default, it is determined by
277 #' [url_filename()].
278 #' @param ... Other arguments to be passed to [download.file()] (except
279 #' `method`).
280 #' @param .error An error message to signal when the download fails.
281 #' @note To allow downloading large files, the `timeout` option in [options()]
282 #' will be temporarily set to one hour (3600 seconds) inside this function
283 #' when this option has the default value of 60 seconds. If you want a
284 #' different `timeout` value, you may set it via `options(timeout = N)`, where
285 #' `N` is the number of seconds (not 60).
286 #' @return The `output` file path if the download succeeded, or an error if none
287 #' of the download methods worked.
288 #' @export
289 download_file = function(
290 url, output = url_filename(url), ...,
291 .error = 'No download method works (auto/wininet/wget/curl/lynx)'
292 ) {
293 if (getOption('timeout') == 60L) {
294 opts = options(timeout = 3600) # one hour
295 on.exit(options(opts), add = TRUE)
296 }
297 dir_create(dirname(output))
298 download = function(method = 'auto') suppressWarnings({
299 # curl needs to add a -L option to follow redirects
300 if (method == 'curl' && is.null(getOption('download.file.extra'))) {
301 opts2 = options(download.file.extra = c('-L', '--fail'))
302 on.exit(options(opts2), add = TRUE)
303 }
304 tryCatch(download.file(url, output, ..., method = method), error = function(e) 1L)
305 })
306 for (method in c('libcurl', 'auto', if (is_windows()) 'wininet')) {
307 if (download(method) == 0) return(output)
308 }
309 # check for libcurl/curl/wget/lynx, call download.file with appropriate method
310 for (method in c('curl', 'wget', 'lynx')) {
311 if (Sys.which(method) != '' && download(method) == 0) return(output)
312 }
313 stop(.error)
314 }
315
316 #' Test if a URL is accessible
317 #'
318 #' Try to send a `HEAD` request to a URL using
319 #' [curlGetHeaders()] or the \pkg{curl} package, and see if it
320 #' returns a successful status code.
321 #' @param x A URL as a character string.
322 #' @param use_curl Whether to use the \pkg{curl} package or the
323 #' `curlGetHeaders()` function in base R to send the request to the URL.
324 #' By default, \pkg{curl} will be used when base R does not have the
325 #' \command{libcurl} capability (which should be rare).
326 #' @param ... Arguments to be passed to `curlGetHeaders()`.
327 #' @return `TRUE` or `FALSE`.
328 #' @export
329 #' @examples xfun::url_accessible('https://yihui.org')
330 url_accessible = function(x, use_curl = !capabilities('libcurl'), ...) {
331 try_status = function(code) tryCatch(code < 400, error = function(e) FALSE)
332 if (use_curl) {
333 h = curl::new_handle()
334 curl::handle_setopt(h, customrequest = 'HEAD', nobody = TRUE)
335 try_status(curl::curl_fetch_memory(x, h)$status_code)
336 } else {
337 # use curlGetHeaders() instead
338 try_status(attr2(curlGetHeaders(x, ...), 'status'))
339 }
340 }
341
342 #' Get the final destination of a URL
343 #'
344 #' If a URL is redirected, query the new location via [curlGetHeaders()],
345 #' otherwise return the original URL.
346 #' @param x A character vector of URLs.
347 #' @param force By default, the query is cached in the current R session. To
348 #' bypass the cache, use `force = TRUE`.
349 #' @return The final destination(s). If the URL returns a status code greater
350 #' than or equal to 400, it will throw an error.
351 #' @export
352 #' @examples
353 #' u = 'https://cran.r-project.org/package=xfun'
354 #' url_destination(u) # redirected to canonical URL
355 url_destination = function(x, force = FALSE) {
356 unlist(lapply(x, .url_destination, force))
357 }
358
359 .url_destination = local({
360 db = list()
361 function(x, force = FALSE) {
362 if (!force && is.character(db[[x]])) return(db[[x]])
363 h = curlGetHeaders(x)
364 if ((s <- attr2(h, 'status')) >= 400) stop2('URL ', x, ' returned status code ', s)
365 u = grep_sub('^location:\\s+(.+?)[\r\n]*$', '\\1', h, ignore.case = TRUE)
366 db[[x]] <<- if (length(u)) tail(u, 1) else x
367 }
368 })
369
370 #' Generate a message with `cat()`
371 #'
372 #' This function is similar to [message()], and the difference is
373 #' that `msg_cat()` uses [cat()] to write out the message,
374 #' which is sent to [stdout()] instead of [stderr()]. The
375 #' message can be suppressed by [suppressMessages()].
376 #' @param ... Character strings of messages, which will be concatenated into one
377 #' string via `paste(c(...), collapse = '')`.
378 #' @note By default, a newline will not be appended to the message. If you need
379 #' a newline, you have to explicitly add it to the message (see
380 #' \sQuote{Examples}).
381 #' @return Invisible `NULL`, with the side-effect of printing the message.
382 #' @seealso This function was inspired by `rlang::inform()`.
383 #' @export
384 #' @examples
385 #' {
386 #' # a message without a newline at the end
387 #' xfun::msg_cat('Hello world!')
388 #' # add a newline at the end
389 #' xfun::msg_cat(' This message appears right after the previous one.\n')
390 #' }
391 #' suppressMessages(xfun::msg_cat('Hello world!'))
392 msg_cat = function(...) {
393 x = paste(c(...), collapse = '')
394 withRestarts({
395 signalCondition(simpleMessage(x))
396 cat(x)
397 }, muffleMessage = function() invisible(NULL))
398 }
399
400 #' Save objects to files and lazy-load them
401 #'
402 #' The function [lazy_save()] saves objects to files with incremental integer
403 #' names (e.g., the first object is saved to `1.rds`, and the second object is
404 #' saved to `2.rds`, etc.). The function [lazy_load()] lazy-load objects from
405 #' files saved via [lazy_save()], i.e., a file will not be read until the object
406 #' is used.
407 #' @param list A character vector of object names. This list will be written to
408 #' an index file with `0` as the base name (e.g., `0.rds`).
409 #' @param path The path to write files to / read files from.
410 #' @param method The file save/load method. It can be a string (e.g., `rds`,
411 #' `raw`, or `qs2`) or a list. See the `rw` argument of [cache_exec()]. By
412 #' default, it is automatically detected by checking the existence of the
413 #' index file (e.g., `0.rds`, `0.raw`, or `0.qs2`).
414 #' @param envir The environment to [get] or [assign] objects.
415 #' @return [lazy_save()] returns invisible `NULL`; [lazy_load()] returns the
416 #' object names invisibly.
417 #' @seealso [delayedAssign()]
418 #' @export
419 lazy_save = function(list = NULL, path = './', method = 'auto', envir = parent.frame()) {
420 m = io_method(method, path)
421 idx = lazy_idx(path, m$name)
422 m$save(list, idx)
423 for (i in seq_along(list)) {
424 v = get(list[[i]], envir, inherits = FALSE)
425 m$save(v, sprintf('%s%d.%s', path, i, m$name))
426 }
427 }
428
429 #' @rdname lazy_save
430 #' @export
431 lazy_load = function(path = './', method = 'auto', envir = parent.frame()) {
432 m = io_method(method, path)
433 idx = lazy_idx(path, m$name)
434 vars = m$load(idx)
435 .mapply(function(path, name) {
436 delayedAssign(name, m$load(path), assign.env = envir)
437 }, list(sprintf('%s%d.%s', path, seq_along(vars), m$name), vars), NULL)
438 invisible(vars)
439 }
440
441 # use 0.ext as the index file to store the object names
442 lazy_idx = function(path, ext) paste0(path, '0.', ext)
443
444 io_method = function(method, path) {
445 if (is.character(method)) {
446 if (method == 'auto') {
447 for (m in io_methods) if (file_exists(lazy_idx(path, m$name))) {
448 method = m$name; break
449 }
450 }
451 if (method == 'auto') method = 'rds'
452 }
453 if (is.list(method)) method else io_methods[[method]]
454 }