File: quote.R

package info (click to toggle)
r-cran-sys 3.4.3-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 220 kB
  • sloc: ansic: 540; sh: 13; makefile: 2
file content (35 lines) | stat: -rw-r--r-- 1,025 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#' Quote arguments on Windows
#'
#' Quotes and escapes shell arguments when needed so that they get properly parsed
#' by most Windows programs. This function is used internally to automatically quote
#' system commands, the user should normally not quote arguments manually.
#'
#' Algorithm is ported to R from
#' [libuv](https://github.com/libuv/libuv/blob/v1.23.0/src/win/process.c#L454-L524).
#'
#' @export
#' @rdname quote
#' @name quote
#' @param args character vector with arguments
windows_quote <- function(args){
  if(is.null(args))
    return(args)
  stopifnot(is.character(args))
  args <- enc2utf8(args)
  vapply(args, windows_quote_one, character(1), USE.NAMES = FALSE)
}

windows_quote_one <- function(str){
  if(!nchar(str)){
    return('""')
  }
  if(!grepl('[ \t"]', str)){
    return(str)
  }
  if(!grepl('["\\]', str)){
    return(paste0('"', str, '"'))
  }
  str <- gsub('([\\]*)"', '\\1\\1\\\\"', str, useBytes = TRUE)
  str <- gsub('([\\]+)$', '\\1\\1', str, useBytes = TRUE)
  paste0('"', str, '"')
}