File: paths.R

package info (click to toggle)
r-cran-xml2 1.1.0-1~bpo8%2B1
  • links: PTS, VCS
  • area: main
  • in suites: jessie-backports
  • size: 852 kB
  • sloc: cpp: 1,057; xml: 115; sh: 53; ansic: 12; makefile: 6
file content (58 lines) | stat: -rw-r--r-- 1,264 bytes parent folder | download | duplicates (5)
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
path_to_connection <- function(path, check = c("file", "dir")) {
  check <- match.arg(check)

  if (!is.character(path) || length(path) != 1L)
    return(path)

  if (is_url(path)) {
    if (requireNamespace("curl", quietly = TRUE)) {
      return(curl::curl(path))
    } else {
      return(url(path))
    }
  }

  if (check == "file") {
    path <- check_path(path)
  } else {
    path <- file.path(check_path(dirname(path)), basename(path))
  }
  switch(tools::file_ext(path),
    gz = gzfile(path, ""),
    bz2 = bzfile(path, ""),
    xz = xzfile(path, ""),
    zip = zipfile(path, ""),
    path
  )
}

is_url <- function(path) {
  grepl("^(http|ftp)s?://", path)
}

check_path <- function(path) {
  if (file.exists(path))
    return(normalizePath(path, "/", mustWork = FALSE))

  stop("'", path, "' does not exist",
    if (!is_absolute_path(path))
      paste0(" in current working directory ('", getwd(), "')"),
    ".",
    call. = FALSE
  )
}

is_absolute_path <- function(path) {
  grepl("^(/|[A-Za-z]:|\\\\|~)", path)
}

zipfile <- function(path, open = "r") {
  files <- utils::unzip(path, list = TRUE)
  file <- files$Name[[1]]

  if (nrow(files) > 1) {
    message("Multiple files in zip: reading '", file, "'")
  }

  unz(path, file, open = open)
}