| 1 |
#' A customized wrapper for `system2()` |
| 2 |
#' |
| 3 |
#' If `system2()` returns character output (e.g., with the argument `stdout = |
| 4 |
#' TRUE`), check if the output is encoded in UTF-8. If it is, mark it with UTF-8 |
| 5 |
#' explicitly. If it returns an integer, treat it as an error code and throw an |
| 6 |
#' error if it is non-zero. |
| 7 |
#' @param command,args,... Passed to [system2()]. Note that `args` will always |
| 8 |
#' be quoted with [shQuote()] before passing to `system2()`, so you don't need |
| 9 |
#' to quote it yourself. |
| 10 |
#' @return The value returned by `system2()`. |
| 11 |
#' @export |
| 12 |
#' @examplesIf interactive() |
| 13 |
#' a = c('-e', 'print(intToUtf8(c(20320, 22909)))') |
| 14 |
#' x2 = system2('Rscript', shQuote(a), stdout = TRUE) |
| 15 |
#' Encoding(x2) # unknown |
| 16 |
#' |
| 17 |
#' x3 = xfun::system3('Rscript', a, stdout = TRUE) |
| 18 |
#' # encoding of x3 should be UTF-8 if the current locale is UTF-8 |
| 19 |
#' !l10n_info()[['UTF-8']] || Encoding(x3) == 'UTF-8' # should be TRUE |
| 20 |
system3 = function(command, args = character(), ...) { |
| 21 |
res = system2(command, shQuote(args), ...) |
| 22 |
if (is.character(res)) { |
| 23 |
if (all(is_utf8(res))) Encoding(res) = 'UTF-8' |
| 24 |
} |
| 25 |
if (is.integer(res)) { |
| 26 |
if (res != 0) stop("command '", command, "' failed with code: ", res, call. = FALSE) |
| 27 |
invisible(res) |
| 28 |
} else res |
| 29 |
} |
| 30 |
|
| 31 |
#' Run OptiPNG on all PNG files under a directory |
| 32 |
#' |
| 33 |
#' Call the command \command{optipng} via `system2()` to optimize all PNG |
| 34 |
#' files under a directory. |
| 35 |
#' @param dir Path to a directory. |
| 36 |
#' @param files Alternatively, you can choose the specific files to optimize. |
| 37 |
#' @param ... Arguments to be passed to `system2()`. |
| 38 |
#' @references OptiPNG: <https://optipng.sourceforge.net>. |
| 39 |
#' @export |
| 40 |
optipng = function(dir = '.', files = all_files('[.]png$', dir), ...) { |
| 41 |
if (Sys.which('optipng') != '') for (f in files) system2('optipng', shQuote(f), ...) |
| 42 |
} |
| 43 |
|
| 44 |
#' Run the commands \command{Rscript} and \command{R CMD} |
| 45 |
#' |
| 46 |
#' Wrapper functions to run the commands \command{Rscript} and \command{R CMD}. |
| 47 |
#' @param args A character vector of command-line arguments. |
| 48 |
#' @param ... Other arguments to be passed to [system2()]. |
| 49 |
#' @export |
| 50 |
#' @return A value returned by `system2()`. |
| 51 |
#' @examples library(xfun) |
| 52 |
#' Rscript(c('-e', '1+1')) |
| 53 |
#' Rcmd(c('build', '--help')) |
| 54 |
Rscript = function(args, ...) { |
| 55 |
# unset R_TESTS for the new R session: https://stackoverflow.com/a/27994299 |
| 56 |
if (is_R_CMD_check()) { |
| 57 |
v = set_envvar(c(R_TESTS = NA)); on.exit(set_envvar(v), add = TRUE) |
| 58 |
} |
| 59 |
system2(file.path(R.home('bin'), 'Rscript'), args, ...) |
| 60 |
} |
| 61 |
|
| 62 |
#' @rdname Rscript |
| 63 |
#' @export |
| 64 |
Rcmd = function(args, ...) { |
| 65 |
system2(file.path(R.home('bin'), 'R'), c('CMD', args), ...) |
| 66 |
} |
| 67 |
|
| 68 |
#' Call a function in a new R session via `Rscript()` |
| 69 |
#' |
| 70 |
#' Save the argument values of a function in a temporary RDS file, open a new R |
| 71 |
#' session via [Rscript()], read the argument values, call the function, and |
| 72 |
#' read the returned value back to the current R session. |
| 73 |
#' @param fun A function, or a character string that can be parsed and evaluated |
| 74 |
#' to a function. |
| 75 |
#' @param args A list of argument values. |
| 76 |
#' @param options A character vector of options to passed to [Rscript()], e.g., |
| 77 |
#' `"--vanilla"`. |
| 78 |
#' @param ...,wait Arguments to be passed to [system2()]. |
| 79 |
#' @param fail The desired error message when an error occurred in calling the |
| 80 |
#' function. If the actual error message during running the function is |
| 81 |
#' available, it will be appended to this message. |
| 82 |
#' @export |
| 83 |
#' @return If `wait = TRUE`, the returned value of the function in the new R |
| 84 |
#' session. If `wait = FALSE`, three file paths will be returned: the first |
| 85 |
#' one stores `fun` and `args` (as a list), the second one is supposed to |
| 86 |
#' store the returned value of the function, and the third one stores the |
| 87 |
#' possible error message. |
| 88 |
#' @examples factorial(10) |
| 89 |
#' # should return the same value |
| 90 |
#' xfun::Rscript_call('factorial', list(10)) |
| 91 |
#' |
| 92 |
#' # the first argument can be either a character string or a function |
| 93 |
#' xfun::Rscript_call(factorial, list(10)) |
| 94 |
#' |
| 95 |
#' # Run Rscript starting a vanilla R session |
| 96 |
#' xfun::Rscript_call(factorial, list(10), options = c("--vanilla")) |
| 97 |
Rscript_call = function( |
| 98 |
fun, args = list(), options = NULL, ..., wait = TRUE, |
| 99 |
fail = sprintf("Failed to run '%s' in a new R session", deparse(substitute(fun))[1]) |
| 100 |
) { |
| 101 |
f = replicate(3, tempfile(fileext = '.rds')) |
| 102 |
on.exit(if (wait) unlink(f), add = TRUE) |
| 103 |
saveRDS(list(fun, args), f[1]) |
| 104 |
res = Rscript( |
| 105 |
c(options, shQuote(c(pkg_file('scripts', 'call-fun.R'), f))), ..., wait = wait |
| 106 |
) |
| 107 |
if (wait) { |
| 108 |
if (res == 0) readRDS(f[2]) else stop( |
| 109 |
fail, if (file_exists(f[3])) c(': ', readRDS(f[3])) else '.', call. = FALSE |
| 110 |
) |
| 111 |
} else f |
| 112 |
} |
| 113 |
|
| 114 |
# call a function in a background process |
| 115 |
Rscript_bg = function(fun, args = list(), timeout = 10) { |
| 116 |
pid = tempfile() # to store the process ID of the new R session |
| 117 |
saveRDS(NULL, pid) |
| 118 |
|
| 119 |
Rscript_call(function() { |
| 120 |
saveRDS(Sys.getpid(), pid) |
| 121 |
# remove this pid file when the function finishes |
| 122 |
on.exit(unlink(pid), add = TRUE) |
| 123 |
do.call(fun, args) |
| 124 |
}, wait = FALSE) |
| 125 |
|
| 126 |
id = NULL # read the above process ID into this R session |
| 127 |
res = list(pid = id, is_alive = function() FALSE) |
| 128 |
|
| 129 |
# check if the pid file still exists; if not, the process has ended |
| 130 |
if (!file_exists(pid)) return(res) |
| 131 |
|
| 132 |
t0 = Sys.time() |
| 133 |
while (!is_timeout(t0, timeout)) { |
| 134 |
Sys.sleep(.1) |
| 135 |
if (!file_exists(pid)) return(res) |
| 136 |
if (length(id <- readRDS(pid)) == 1) break |
| 137 |
} |
| 138 |
if (length(id) == 0) stop( |
| 139 |
'Failed to launch the background process in ', timeout, ' seconds (timeout).' |
| 140 |
) |
| 141 |
|
| 142 |
list(pid = id, is_alive = function() file_exists(pid)) |
| 143 |
} |
| 144 |
|
| 145 |
#' Kill a process and (optionally) all its child processes |
| 146 |
#' |
| 147 |
#' Run the command \command{taskkill /f /pid} on Windows and \command{kill} on |
| 148 |
#' Unix, respectively, to kill a process. |
| 149 |
#' @param pid The process ID. |
| 150 |
#' @param recursive Whether to kill the child processes of the process. |
| 151 |
#' @param ... Arguments to be passed to [system2()] to run the |
| 152 |
#' command to kill the process. |
| 153 |
#' @return The status code returned from `system2()`. |
| 154 |
#' @export |
| 155 |
proc_kill = function(pid, recursive = TRUE, ...) { |
| 156 |
if (is_windows()) { |
| 157 |
system2('taskkill', c(if (recursive) '/t', '/f', '/pid', pid), ...) |
| 158 |
} else { |
| 159 |
system2('kill', c(pid, if (recursive) child_pids(pid)), ...) |
| 160 |
} |
| 161 |
} |
| 162 |
|
| 163 |
# obtain pids of all child processes (recursively) |
| 164 |
child_pids = function(id) { |
| 165 |
x = system2('sh', shQuote(c(pkg_file('scripts', 'child-pids.sh'), id)), stdout = TRUE) |
| 166 |
grep('^[0-9]+$', x, value = TRUE) |
| 167 |
} |
| 168 |
|
| 169 |
powershell = function(command) { |
| 170 |
if (Sys.which('powershell') == '') return() |
| 171 |
command = paste(command, collapse = ' ') |
| 172 |
system2('powershell', c('-Command', shQuote(command)), stdout = TRUE) |
| 173 |
} |
| 174 |
|
| 175 |
# start a background process via the PowerShell cmdlet and return its pid |
| 176 |
ps_process = function(command, args = character(), verbose = FALSE) { |
| 177 |
powershell(c( |
| 178 |
'echo (Start-Process', '-FilePath', shQuote(command), '-ArgumentList', |
| 179 |
ps_quote(args), '-PassThru', '-WindowStyle', |
| 180 |
sprintf('%s).ID', if (verbose) 'Normal' else 'Hidden') |
| 181 |
)) |
| 182 |
} |
| 183 |
|
| 184 |
# quote PowerShell arguments properly |
| 185 |
ps_quote = function(x) { |
| 186 |
x = gsub('"', '""', x) # '""' mean a literal '"' |
| 187 |
# if an argument contains a space, surround it with escaped double quotes `"`" |
| 188 |
i = grep('\\s', x) |
| 189 |
x[i] = sprintf('`"%s`"', x[i]) |
| 190 |
sprintf('"%s"', paste(x, collapse = ' ')) |
| 191 |
} |
| 192 |
|
| 193 |
#' Start a background process |
| 194 |
#' |
| 195 |
#' Start a background process using the PowerShell cmdlet |
| 196 |
#' \command{Start-Process-PassThru} on Windows or the ampersand \command{&} on |
| 197 |
#' Unix, and return the process ID. |
| 198 |
#' @param command,args The system command and its arguments. They do not need to |
| 199 |
#' be quoted, since they will be quoted via [shQuote()] internally. |
| 200 |
#' @param verbose If `FALSE`, suppress the output from `stdout` (and also |
| 201 |
#' `stderr` on Windows). The default value of this argument can be set via a |
| 202 |
#' global option, e.g., `options(xfun.bg_process.verbose = TRUE)`. |
| 203 |
#' @return The process ID as a character string. |
| 204 |
#' @note On Windows, if PowerShell is not available, try to use |
| 205 |
#' [`system2`]`(wait = FALSE)` to start the background process instead. The |
| 206 |
#' process ID will be identified from the output of the command |
| 207 |
#' \command{tasklist}. This method of looking for the process ID may not be |
| 208 |
#' reliable. If the search is not successful in 30 seconds, it will throw an |
| 209 |
#' error (timeout). If a longer time is needed, you may set |
| 210 |
#' `options(xfun.bg_process.timeout)` to a larger value, but it should be very |
| 211 |
#' rare that a process cannot be started in 30 seconds. When you reach the |
| 212 |
#' timeout, it is more likely that the command actually failed. |
| 213 |
#' @export |
| 214 |
#' @seealso [proc_kill()] to kill a process. |
| 215 |
bg_process = function( |
| 216 |
command, args = character(), verbose = getOption('xfun.bg_process.verbose', FALSE) |
| 217 |
) { |
| 218 |
throw_error = function(...) stop( |
| 219 |
'Failed to run the command', ..., ' in the background: ', |
| 220 |
paste(shQuote(c(command, args)), collapse = ' '), call. = FALSE |
| 221 |
) |
| 222 |
|
| 223 |
# check the possible pid returned from system2() |
| 224 |
check_pid = function(res) { |
| 225 |
if (is.null(res)) return(res) |
| 226 |
if (!is.null(attr2(res, 'status'))) throw_error() |
| 227 |
if (length(res) == 1 && grepl('^[0-9]+$', res)) return(res) |
| 228 |
throw_error() |
| 229 |
} |
| 230 |
|
| 231 |
if (is_windows()) { |
| 232 |
# first try 'Start-Process -PassThrough' to start a background process; if |
| 233 |
# PowerShell is unavailable, fall back to system2(wait = FALSE), and the |
| 234 |
# method to find out the pid is not 100% reliable |
| 235 |
if (length(pid <- check_pid(ps_process(command, args, verbose))) == 1) return(pid) |
| 236 |
|
| 237 |
message( |
| 238 |
'It seems you do not have PowerShell installed. The process ID may be inaccurate.' |
| 239 |
) |
| 240 |
# format of task list: hugo.exe 4592 Console 1 35,188 K |
| 241 |
tasklist = function() system2('tasklist', stdout = TRUE) |
| 242 |
pid1 = tasklist() |
| 243 |
system2(command, shQuote(args), wait = FALSE) |
| 244 |
|
| 245 |
get_pid = function() { |
| 246 |
# make sure the command points to an actual executable (e.g., resolve 'R' |
| 247 |
# to 'R.exe') |
| 248 |
if (!file_exists(command)) { |
| 249 |
if (Sys.which(command) != '') command = Sys.which(command) |
| 250 |
} |
| 251 |
cmd = basename(command) |
| 252 |
|
| 253 |
pid2 = setdiff(tasklist(), pid1) |
| 254 |
# the process's info should start with the command name |
| 255 |
pid2 = pid2[substr(pid2, 1, nchar(cmd)) == cmd] |
| 256 |
if (length(pid2) == 0) return() |
| 257 |
m = regexec('\\s+([0-9]+)\\s+', pid2) |
| 258 |
for (v in regmatches(pid2, m)) if (length(v) >= 2) return(v[2]) |
| 259 |
} |
| 260 |
|
| 261 |
t0 = Sys.time(); id = NULL; timeout = getOption('xfun.bg_process.timeout', 30) |
| 262 |
while (!is_timeout(t0, timeout)) { |
| 263 |
if (length(id <- get_pid()) > 0) break |
| 264 |
} |
| 265 |
|
| 266 |
if (length(id) > 0) return(id) |
| 267 |
|
| 268 |
system2(command, args, timeout = timeout) # see what the error is |
| 269 |
throw_error(' in ', timeout, ' second(s)') |
| 270 |
} else { |
| 271 |
if (isFALSE(verbose)) verbose = '/dev/null' |
| 272 |
pid = tempfile(); on.exit(unlink(pid), add = TRUE) |
| 273 |
code = paste(c( |
| 274 |
shQuote(c(command, args)), if (is.character(verbose)) paste('>', verbose), |
| 275 |
'& echo $! >', shQuote(pid) |
| 276 |
), collapse = ' ') |
| 277 |
system2('sh', c('-c', shQuote(code))) |
| 278 |
check_pid(readLines(pid)) |
| 279 |
} |
| 280 |
} |
| 281 |
|
| 282 |
#' Upload to an FTP server via \command{curl} |
| 283 |
#' |
| 284 |
#' The function `upload_ftp()` runs the command \command{curl -T file |
| 285 |
#' server} to upload a file to an FTP server if the system command |
| 286 |
#' \command{curl} is available, otherwise it uses the R package \pkg{curl}. The |
| 287 |
#' function `upload_win_builder()` uses `upload_ftp()` to upload |
| 288 |
#' packages to the win-builder server. |
| 289 |
#' |
| 290 |
#' These functions were written mainly to save package developers the trouble of |
| 291 |
#' going to the win-builder web page and uploading packages there manually. |
| 292 |
#' @param file Path to a local file. |
| 293 |
#' @param server The address of the FTP server. For `upload_win_builder()`, |
| 294 |
#' `server = 'https'` means uploading to |
| 295 |
#' `'https://win-builder.r-project.org/upload.aspx'`. |
| 296 |
#' @param dir The remote directory to which the file should be uploaded. |
| 297 |
#' @param version The R version(s) on win-builder. |
| 298 |
#' @return Status code returned from [system2()] or |
| 299 |
#' `curl::curl_fetch_memory()`. |
| 300 |
#' @export |
| 301 |
upload_ftp = function(file, server, dir = '') { |
| 302 |
if (dir != '') dir = gsub('/*$', '/', dir) |
| 303 |
server = paste0(server, dir) |
| 304 |
if (Sys.which('curl') == '') { |
| 305 |
curl::curl_upload(file, server)$status_code |
| 306 |
} else { |
| 307 |
system2('curl', shQuote(c('-T', file, server))) |
| 308 |
} |
| 309 |
} |
| 310 |
|
| 311 |
#' @rdname upload_ftp |
| 312 |
#' @export |
| 313 |
upload_win_builder = function( |
| 314 |
file = pkg_build(), version = c("R-devel", "R-release", "R-oldrelease"), |
| 315 |
server = c('ftp', 'https') |
| 316 |
) { |
| 317 |
if (missing(file)) on.exit(file.remove(file), add = TRUE) |
| 318 |
if (system2('git', 'status', stderr = FALSE) == 0) system2('git', 'pull') |
| 319 |
server = server[1] |
| 320 |
server = switch( |
| 321 |
server, |
| 322 |
'ftp' = paste0(server, '://win-builder.r-project.org/'), |
| 323 |
'https' = paste0(server, '://win-builder.r-project.org/upload.aspx'), |
| 324 |
server |
| 325 |
) |
| 326 |
res = if (grepl('^ftp://', server)) { |
| 327 |
lapply(version, upload_ftp, file = file, server = server) |
| 328 |
} else { |
| 329 |
vers = c('R-devel' = 2, 'R-release' = 1, 'R-oldrelease' = 3) |
| 330 |
params = list( |
| 331 |
FileUpload = file, |
| 332 |
Button = 'Upload File', |
| 333 |
# perhaps we should read these tokens dynamically from |
| 334 |
# https://win-builder.r-project.org/upload.aspx |
| 335 |
`__VIEWSTATE` = '/wEPDwULLTE0OTY5NTg0MTUPZBYCAgIPFgIeB2VuY3R5cGUFE211bHRpcGFydC9mb3JtLWRhdGFkZFHMrNH6JjHTyJ00T0dAADGf4oa0', |
| 336 |
`__VIEWSTATEGENERATOR` = '69164837', |
| 337 |
`__EVENTVALIDATION` = '/wEWBQKksYbrBgKM54rGBgK7q7GGCAKF2fXbAwLWlM+bAqR2dARbCNfKVu0vDawqWYgB5kKI' |
| 338 |
) |
| 339 |
lapply(version, function(i) { |
| 340 |
names(params)[1:2] = paste0(names(params)[1:2], vers[i]) |
| 341 |
if (Sys.which('curl') == '') { |
| 342 |
h = curl::new_handle() |
| 343 |
params[[1]] = curl::form_file(params[[1]]) |
| 344 |
curl::handle_setform(h, .list = params) |
| 345 |
curl::curl_fetch_memory(server, h)$status_code |
| 346 |
} else { |
| 347 |
params[1] = paste0('@', params[1]) |
| 348 |
system2('curl', shQuote(c( |
| 349 |
rbind('-F', paste(names(params), params, sep = '=')), |
| 350 |
server |
| 351 |
)), stdout = FALSE) |
| 352 |
} |
| 353 |
}) |
| 354 |
} |
| 355 |
|
| 356 |
setNames(unlist(res), version) |
| 357 |
} |