R/os.R

Defines functions user_dir which_os has_internet where has_bin which_cmd print.exec exec

Documented in exec has_internet user_dir

#' run system command
#' @family os-utils
#'
#'
#' @title exec
#' @param command system command to run
#' @return An `exec` instance that stores system command outputs
#' @export
#' @author Guangchuang Yu
exec <- function(command) {
    res <- system(command, intern=TRUE)
    structure(res, class = "exec")
}



#' @method print exec
#' @export
print.exec <- function(x, ...) {
    cat(x, sep='\n')
}
    


which_cmd <- function(bin) {
    os <- which_os()
    which <- "which"
    if (os == "Windows") {
        which <- "where"
    }

    command <- sprintf("%s %s", which, bin)

    return(command)
}

has_bin <- function(bin) {
    command <- which_cmd(bin)

    exit_code <- system(command, 
        ignore.stdout = TRUE, 
        ignore.stderr = TRUE)

    return(exit_code == 0)    
}


where <- function(bin) {
    if (!has_bin(bin)) return("")
    
    command <- which_cmd(bin)
    exec(command)
}

#' test for internect connection via reading lines from a URL
#' @family os-utils
#'
#'
#' @title has_internet
#' @param site URL to test connection
#' @return logical value
#' @export
#' @author Guangchuang Yu
has_internet <- function(site = "https://www.baidu.com/") {
    ret <- tryCatch(
        suppressWarnings(readLines(site, n = 1)),
        error = function(e) NULL
    )
    
    return(!is.null(ret))
}

which_os <- function() {
    Sys.info()[["sysname"]]
}

#' get the user dir to save app caches, logs and data (a wrapper function of `rappdirs::user_cache_dir()`)
#' @family os-utils
#' 
#' @title user_dir
#' @param appname App name
#' @param appauthor App author
#' @param ... additional parameters
#' @return a directory (created if not exists)
#' @importFrom rappdirs user_data_dir
#' @export
#' @author Guangchuang Yu
user_dir <- function(appname = NULL, appauthor = NULL, ...) {
    dir <- rappdirs::user_data_dir(
        appname = appname, 
        appauthor = appauthor, 
        ...)

    if (!dir.exists(dir)) dir.create(dir, recursive = TRUE)
    
    return(dir)
}

Try the yulab.utils package in your browser

Any scripts or data that you put into this service are public.

yulab.utils documentation built on Feb. 5, 2026, 9:10 a.m.