R/remove_old_directories.R

Defines functions remove_old_dirs

Documented in remove_old_dirs

#' Remove directories older than a specified day
#'
#' This function removes directories in the specified base directory that are
#' older than a specified maximum age in days. It logs the removed directories
#' and any errors encountered during removal.
#'
#' @param base_dir The base directory to search for old directories.
#' @param max_age_in_days The maximum age (in days) for directories to be considered old.
#' @param log_file The name of the log file to store information about removed directories and errors.
#' @param verbose A logical value indicating whether to print messages to the console.
#'
#' @return The function does not return anything. It logs information about removed directories and errors.
#'
remove_old_dirs <- function(base_dir, max_age_in_days=3, log_file="remove_old_dirs.log", verbose=FALSE) {
    current_time <- Sys.time()

    dirs <- list.dirs(base_dir, full.names=TRUE, recursive=FALSE)
    dirs <- dirs[grep("Analysis_", dirs)]

    # Open connection to log file
    con <- file(log_file, open="a")

    for( dir_path in dirs ){
        dir_creation_time <- file.info(dir_path)$ctime
        time_difference_days <- as.numeric(difftime(current_time, dir_creation_time, units="days"))

        if( time_difference_days >= max_age_in_days ){
            tryCatch({
                if (verbose) message("Removing directory: ", dir_path)
                
                unlink(dir_path, recursive=TRUE)
                
                log_msg <- paste("Removed:", dir_path)
                message(log_msg)  
                writeLines(log_msg, con)  
                
            }, error=function(e) {
                error_msg <- paste("Error removing:", dir_path, "\nError message:", e$message)
                message(error_msg) 
                writeLines(error_msg, con)  
            })
        }
    }

    close(con)
}

Try the shinyWGD package in your browser

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

shinyWGD documentation built on April 4, 2025, 2:28 a.m.