Debian Codegraph @

R/utils.R

raw
1 #' Information About the System
2 #'
3 #' `get_caller()` Tries to determine the calling functions based on `where`.
4 #'
5 #' @param where `integer` scalar (usually negative). Look up that many frames
6 #' up the call stack
7 #'
8 #' @seealso [base::sys.call()]
9 #' @export
10 #'
11 #' @rdname system_infos
12 #' @export
13 #'
14 #' @examples
15 #' foo <- function() get_caller(-1L)
16 #' foo()
17 get_caller <- function(
18 where = -1L
19 ){
20 res <- tryCatch(
21 sys.call(where)[[1]],
22 error = function(e) NULL
23 )
24
25 if (is.symbol(res)){
26 deparse(res)
27 } else if (is.null(res)){
28 "(shell)"
29 } else if (inherits(res, "{")){
30 "{...}"
31 } else if (is.function(res)){
32 # rare, but can happen f.e. through plumber
33 fmt_function_signature(res)
34 } else {
35 ptrunc(deparse(res))
36 }
37 }
38
39
40
41
42 #' `get_user()` tries to determine the current user. Defaults to
43 #' `getOption("lgr.user")`. If the option is not set, `Sys.info()[["user"]]`
44 #' is used. If the option is not set and the package **whoami** is available,
45 #' the user name is guessed based on whichever of the following is available:
46 #' `email_address`, `fullname`, `gh_username`, `username`.
47 #'
48 #' @return a `character` scalar.
49 #'
50 #' @seealso [whoami::whoami()]
51 #' @name system_infos
52 #' @param fallback A fallback in case the user name could not be determined
53 #' @rdname system_infos
54 #' @export
55 #' @examples
56 #' get_user()
57
58 get_user <- function(fallback = "unknown user"){
59 guess_user <- function(){
60 if (requireNamespace("whoami", quietly = TRUE)){
61 res <- try({
62 whoami::email_address(
63 whoami::fullname(
64 whoami::gh_username(
65 whoami::username(
66 fallback
67 ))))
68 }, silent = TRUE)
69 } else {
70 res <- try(Sys.info()[["user"]], silent = TRUE)
71 }
72
73 if (inherits(res, "try-error") || is.null(res))
74 res <- fallback
75
76 res
77 }
78
79
80 getOption("lgr.user", guess_user())
81 }
82
83
84
85
86 # internal --------------------------------------------------------------
87
88 #' Paste and Truncate
89 #'
90 #' color aware version of ptrunc from sfmisc
91 #' @noRd
92 ptrunc_col <- function(
93 ...,
94 width = 40L,
95 sep = ", ",
96 collapse = ", ",
97 dots = " ..."
98 ){
99 assert(width > 7L, "The minimum supported width is 8")
100 x <- paste(..., sep = sep, collapse = collapse)
101 width <- width + nchar(x) - col_nchar(x)
102
103 sel <- vapply(x, nchar, integer(1), USE.NAMES = FALSE) > width
104
105 x[sel] <- strtrim(x[sel], width = width - 4L)
106 x[sel] <- paste0(gsub(",{0,1}\\s*$", "", x[sel]), dots)
107 x
108 }
109
110
111
112
113
114
115 # misc --------------------------------------------------------------------
116
117 # nocov start
118 dyn_register_s3_method <- function(
119 pkg,
120 generic,
121 class,
122 fun = NULL
123 ){
124 stopifnot(
125 is_scalar_character(pkg),
126 is_scalar_character(generic),
127 is_scalar_character(class)
128 )
129
130 if (is.null(fun)) {
131 fun <- get(paste0(generic, ".", class), envir = parent.frame())
132 } else {
133 stopifnot(is.function(fun))
134 }
135
136 if (pkg %in% loadedNamespaces()) {
137 registerS3method(generic, class, fun, envir = asNamespace(pkg))
138 }
139
140 # Always register hook in case package is later unloaded & reloaded
141 setHook(
142 packageEvent(pkg, "onLoad"),
143 function(...) {
144 registerS3method(generic, class, fun, envir = asNamespace(pkg))
145 }
146 )
147 }
148
149
150
151
152 last <- function(x){
153 x[length(x)]
154 }
155
156
157
158
159 is_Id = function(x){
160 inherits(x, "Id")
161 }
162
163
164
165
166
167 is_zipcmd_available <- function(cmd = Sys.getenv("R_ZIPCMD", "zip")){
168
169 if (is_blank(cmd)){
170 return(FALSE)
171 }
172
173 if (.Platform$OS.type == "windows"){
174 suppressWarnings(res <- system2("where", cmd, stderr = NULL, stdout = NULL))
175 } else {
176 res <- tryCatch(
177 system2("command", paste("-v", cmd), stderr = NULL, stdout = NULL),
178 warning = function(w) {99}
179 )
180 }
181
182 assert(is_scalar(res))
183 res == 0
184 }
185
186
187
188
189 fmt_bytes <- function(
190 x
191 ){
192 x <- as.numeric(x)
193
194 readablifiy <- function(.x){
195 for (unit in c("B", "KiB", "MiB", "GiB", "TiB")){
196 if (max(abs(.x)) < 1024 || unit == "TiB")
197 break
198 else
199 .x <- .x / 1024
200 }
201 return(paste(round(.x, 1), unit))
202 }
203
204 vapply(x, readablifiy, character(1))
205 }
206
207
208
209 #' Logger Error Conditions
210 #'
211 #' @param class `character` scalar. The abstract class that was mistakenly
212 #' tried to initialize. The default is to discover the class name
213 #' automatically if called inside `$initialize(){...}` in an [R6::R6] class
214 #' definition
215 #'
216 #' @return a condition object
217 #' @export
218 #' @family developer tools
219 CannotInitializeAbstractClassError <- function(
220 class = parent.frame(2)[["classes"]]
221 ){
222 error(
223 paste(fmt_class(class), "is an abstract class and cannot be initlized"),
224 class = c("CannotInitializeAbstractClassError", "NotImplementedError"),
225 call = NULL
226 )
227 }
228
229
230
231
232 # stricter & faster thant base R version & support for R < 3.5
233 isFALSE <- function(x){
234 is.logical(x) && length(x) == 1L && !is.na(x) && !x
235 }
236
237
238
239 # like utils::tail.default, but saves you from importing utils.
240 last_n <- function(x, n){
241 assert(
242 is_n0(n),
243 "`n` must be a postive integer >= 0, not ", string_repr(n)
244 )
245
246 len <- length(x)
247 n <- min(n, len)
248 x[seq.int(to = len, length.out = n)]
249 }
250
251
252
253
254 # conditions --------------------------------------------------------------
255
256 condition <- function(message, class, call = NULL, ...) {
257 structure(
258 class = union(class, "condition"),
259 list(message = message, call = call, ...)
260 )
261 }
262
263
264
265
266 error <- function(message, class = NULL, call = NULL, ...) {
267 structure(
268 class = union(class, c("error", "condition")),
269 list(message = message, call = call, ...)
270 )
271 }
272
273
274
275
276 warning_condition <- function(message, class, call = NULL, ...) {
277 structure(
278 class = union(class, c("warning", "condition")),
279 list(message = message, call = call, ...)
280 )
281 }
282 # nocov end