blob: 55be5cfdebfb124157e2926798e908aa8ffdddb1 [file] [log] [blame]
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001#' Logging utilities for RKorAPClient
2#'
3#' This module provides centralized logging functions used throughout the package
4#' for progress reporting and ETA calculations.
5
6#' Log informational messages with optional coloring
7#'
8#' @param v logical flag indicating whether to output the message
9#' @param ... message components to concatenate and display
10#' @keywords internal
11log_info <- function(v, ...) {
12 green <- "\033[32m"
13 reset <- "\033[0m"
14 cat(ifelse(v, paste0(green, ..., reset), ""))
15}
16
17#' Format duration in seconds to human-readable format
18#'
19#' Converts a duration in seconds to a formatted string with days, hours, minutes, and seconds.
20#' Used for ETA calculations and progress reporting.
21#'
22#' @param seconds numeric duration in seconds
23#' @return character string with formatted duration
24#' @keywords internal
25#' @examples
26#' \dontrun{
27#' format_duration(3661) # "01h 01m 01s"
28#' format_duration(86461) # "1d 00h 01m 01s"
29#' }
30format_duration <- function(seconds) {
31 if (is.na(seconds) || !is.finite(seconds) || seconds < 0) {
32 return("00s")
33 }
34
35 days <- floor(seconds / (24 * 3600))
36 seconds <- seconds %% (24 * 3600)
37 hours <- floor(seconds / 3600)
38 seconds <- seconds %% 3600
39 minutes <- floor(seconds / 60)
40 seconds <- floor(seconds %% 60)
41
42 paste0(
43 if (days > 0) paste0(days, "d ") else "",
44 if (hours > 0 || days > 0) paste0(sprintf("%02d", hours), "h ") else "",
45 if (minutes > 0 || hours > 0 || days > 0) paste0(sprintf("%02d", minutes), "m ") else "",
46 paste0(sprintf("%02d", seconds), "s")
47 )
48}
49
50#' Calculate and format ETA for batch operations
51#'
52#' Helper function to calculate estimated time of arrival based on elapsed time
53#' and progress through a batch operation.
54#'
55#' @param current_item current item number (1-based)
56#' @param total_items total number of items to process
57#' @param start_time POSIXct start time of the operation
58#' @return character string with formatted ETA and completion time or empty string if not calculable
59#' @keywords internal
60calculate_eta <- function(current_item, total_items, start_time) {
61 if (current_item <= 1 || total_items <= 1) {
62 return("")
63 }
64
65 elapsed_time <- as.numeric(difftime(Sys.time(), start_time, units = "secs"))
66 if (elapsed_time <= 0) {
67 return("")
68 }
69
70 avg_time_per_item <- elapsed_time / (current_item - 1)
71 remaining_items <- total_items - current_item + 1
72 eta_seconds <- avg_time_per_item * remaining_items
73 estimated_completion_time <- Sys.time() + eta_seconds
74 completion_time_str <- format(estimated_completion_time, "%Y-%m-%d %H:%M:%S")
75
76 paste0(". ETA: ", format_duration(eta_seconds), " (", completion_time_str, ")")
77}