1scan_path_for_rtools <- function(debug = FALSE) {
2  if (debug)
3    cat("Scanning path...\n")
4
5  # Next looks for ls and gcc on path
6  ls_path <- Sys.which("ls")
7  if (ls_path == "")
8    return(NULL)
9  if (debug)
10    cat("ls:", ls_path, "\n")
11
12  # We have a candidate install_path
13  install_path <- dirname(dirname(ls_path))
14
15  gcc_path <- Sys.which("gcc")
16  if (debug)
17    cat("gcc_path:", gcc_path, "\n")
18
19  if (gcc_path != "") {
20    # Check both candidate install paths are same
21    install_path2 <- dirname(dirname(dirname(gcc_path)))
22    if (tolower(install_path2) != tolower(install_path))
23      return(NULL)
24  } else {
25    # Maybe isn't on path, but is in default location
26    gcc_default <- find_arch_exe(
27      file.path(install_path, paste0("mingw_", gcc_arch()), "bin", "gcc.exe"),
28      debug = debug
29    )
30    if (gcc_default == "") {
31      return(NULL)
32    }
33  }
34
35  version <- installed_version(install_path, debug = debug)
36  if (debug)
37    cat("Version:", version, "\n")
38
39  rtools(install_path, version)
40}
41
42find_arch_exe <- function(path, debug = FALSE) {
43
44  # Convert unix path to Windows
45  if(grepl("^/", path)){
46    path <- convert_unix_path(path)
47  }
48
49  full_path <- Sys.which(path)
50
51  if (nchar(full_path) == 0) {
52    if (debug)
53      cat("'", path, "' does not exist\n", sep = "")
54    return("")
55  }
56
57  # Then check architecture matches
58  file_info <- file.info(full_path)
59  if (file_info$exe != paste0("win", gcc_arch())) {
60    if (debug)
61      cat("  Architecture doesn't match\n")
62    return("")
63  }
64
65  full_path
66}
67
68# This assumes cygpath is on your PATH,
69# but it should be if you are using /foo/bar paths in R CMD config,
70# so we don't need to handle this
71convert_unix_path <- function(path){
72  system2("cygpath", c('-m', path), stdout = TRUE)
73}
74