|
| 1 | +#' Progression Updates Reflected as the Size of a File |
| 2 | +#' |
| 3 | +#' @inheritParams make_progression_handler |
| 4 | +#' |
| 5 | +#' @param file (character) A filename. |
| 6 | +#' |
| 7 | +#' @param \ldots Additional arguments passed to [make_progression_handler()]. |
| 8 | +#' |
| 9 | +#' @examples |
| 10 | +#' \donttest{\dontrun{ |
| 11 | +#' handlers(filesize_handler(file = "myscript.progress")) |
| 12 | +#' with_progress(y <- slow_sum(1:100)) |
| 13 | +#' }} |
| 14 | +#' |
| 15 | +#' @importFrom utils file_test |
| 16 | +#' @export |
| 17 | +filesize_handler <- function(file = "default.progress", intrusiveness = getOption("progressr.intrusiveness.file", 5), target = "file", ...) { |
| 18 | + reporter <- local({ |
| 19 | + set_file_size <- function(config, state, progression) { |
| 20 | + ratio <- state$step / config$max_steps |
| 21 | + size <- round(100 * ratio) |
| 22 | + current_size <- file.size(file) |
| 23 | + if (is.na(current_size)) file.create(file, showWarnings = FALSE) |
| 24 | + if (size == 0L) return() |
| 25 | + if (progression$amount == 0) return() |
| 26 | + |
| 27 | + head <- sprintf("%g/%g: ", state$step, config$max_steps) |
| 28 | + nhead <- nchar(head) |
| 29 | + tail <- sprintf(" [%d%%]", round(100 * ratio)) |
| 30 | + ntail <- nchar(tail) |
| 31 | + mid <- paste0(state$message, "") |
| 32 | + nmid <- nchar(mid) |
| 33 | + padding <- size - (nhead + nmid + ntail) |
| 34 | + if (padding <= 0) { |
| 35 | + msg <- paste(head, mid, tail, sep = "") |
| 36 | + if (padding < 0) msg <- substring(msg, first = 1L, last = size) |
| 37 | + } else if (padding > 0) { |
| 38 | + mid <- paste(c(mid, " ", rep(".", times = padding - 1L)), collapse = "") |
| 39 | + msg <- paste(head, mid, tail, sep = "") |
| 40 | + } |
| 41 | + |
| 42 | + cat(file = file, append = FALSE, msg) |
| 43 | + } |
| 44 | + |
| 45 | + list( |
| 46 | + initiate = function(config, state, progression, ...) { |
| 47 | + set_file_size(config = config, state = state, progression = progression) |
| 48 | + }, |
| 49 | + |
| 50 | + update = function(config, state, progression, ...) { |
| 51 | + set_file_size(config = config, state = state, progression = progression) |
| 52 | + }, |
| 53 | + |
| 54 | + finish = function(config, state, progression, ...) { |
| 55 | + if (config$clear) { |
| 56 | + if (file_test("-f", file)) file.remove(file) |
| 57 | + } else { |
| 58 | + set_file_size(config = config, state = state, progression = progression) |
| 59 | + } |
| 60 | + } |
| 61 | + ) |
| 62 | + }) |
| 63 | + |
| 64 | + make_progression_handler("filesize", reporter, intrusiveness = intrusiveness, ...) |
| 65 | +} |
0 commit comments