R/os_tools.R

Defines functions open_vscode open_project open_file open_dir get_os is_wsl

Documented in get_os is_wsl open_dir open_file open_project open_vscode

#' Check if using WSL on Windows
#' @export
is_wsl <- function() {
  sys_info <- base::Sys.info()
  if (isTRUE(base::grepl("(M|m)icrosoft", sys_info["release"]))) {
    kernel_wsl <- "wsl-kernel"
  } else {
    rlang::abort("Kernel is not WSL")
  }
  if (isTRUE(stringr::str_detect(
    base::readLines("/proc/version"),
    as.character(sys_info["release"])
  ))) {
    kernel_wsl <- "wsl-kernel"
  } else {
    rlang::abort("Kernel is not WSL")
  }
  os_type <- base::.Platform$OS.type
  r_version_os <- base::R.version$os
  os <- glue::glue("{os_type}-{r_version_os}-{kernel_wsl}")
  if (isTRUE(base::tolower(os) == "unix-linux-gnu-wsl-kernel")) {
    return(TRUE)
  } else {
    return(FALSE)
  }
}

#' Check OS
#' @export
get_os <- function() {
  sysinf <- base::Sys.info()
  if (!is.null(sysinf)) {
    os <- sysinf["sysname"]
    if (os == "Darwin") {
      os <- "osx"
    }
  } else {
    ## mystery machine
    os <- base::.Platform$OS.type
    if (grepl("^darwin", base::R.version$os)) {
      os <- "osx"
    }
    if (grepl("linux-gnu", base::R.version$os)) {
      os <- "linux"
    }
  }
  base::tolower(os)
}

#' Open current directory
#' @export
open_dir <- function() {
  file_path <- rstudioapi::getSourceEditorContext()$path
  dir <- dirname(file_path)
  sys::exec_wait("xdg-open", dir)
}

#' Open current file
#' @export
open_file <- function() {
  file_path <- rstudioapi::getSourceEditorContext()$path
  sys::exec_wait("xdg-open", file_path)
}

#' Open Current Project Directory
#' @export
open_project <- function() {
  project_path <- rstudioapi::getActiveProject()
  sys::exec_wait("xdg-open", project_path)
}

#' Open Current File to edit on VS Code
#' @export
open_vscode <- function() {
  file_path <- rstudioapi::getSourceEditorContext()$path

  possible_binaries <- c("code-insiders", "code", "vscode-insiders", "vscode")
  base::Sys.which(possible_binaries)
  installed_binaries <- base::Sys.which(possible_binaries)
  installed_binaries <- installed_binaries[
    stringr::str_detect(installed_binaries, "")
  ]

  if (length(installed_binaries) == 0) {
    cli::cli_alert_danger(
      "None of those binaries installed: {.pkg {possible_binaries}}."
    )
    rlang::abort("Install one of the packages above.")
  }
  choosen_binary <- installed_binaries[1]

  cli::cli_alert_success("Opening {.pkg {choosen_binary}}.")

  dir <- dirname(file_path)

  sys::exec_wait(choosen_binary, dir)
}
luciorq/luciolib documentation built on Dec. 18, 2020, 11:43 a.m.