2411: add copyright headers to our R files.
[arvados.git] / sdk / R / R / util.R
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: Apache-2.0
4
5 #' listAll
6 #'
7 #' List all resources even if the number of items is greater than maximum API limit.
8 #'
9 #' @param fn Arvados method used to retrieve items from REST service.
10 #' @param ... Optional arguments which will be pased to fn .
11 #' @examples
12 #' \dontrun{
13 #' arv <- Arvados$new("your Arvados token", "example.arvadosapi.com")
14 #' cl <- listAll(arv$collections.list, filters = list(list("name", "like", "test%"))
15 #' }
16 #' @export 
17 listAll <- function(fn, ...)
18 {
19     offset <- 0
20     itemsAvailable <- .Machine$integer.max
21     items <- c()
22
23     while(length(items) < itemsAvailable)
24     {
25         serverResponse <- fn(offset = offset, ...)
26
27         if(!is.null(serverResponse$errors))
28             stop(serverResponse$errors)
29
30         items          <- c(items, serverResponse$items)
31         offset         <- length(items)
32         itemsAvailable <- serverResponse$items_available
33     }
34
35     items
36 }
37
38
39 #NOTE: Package private functions
40
41 trimFromStart <- function(sample, trimCharacters)
42 {
43     if(startsWith(sample, trimCharacters))
44         sample <- substr(sample, nchar(trimCharacters) + 1, nchar(sample))
45
46     sample
47 }
48
49 trimFromEnd <- function(sample, trimCharacters)
50 {
51     if(endsWith(sample, trimCharacters))
52         sample <- substr(sample, 0, nchar(sample) - nchar(trimCharacters))
53
54     sample
55 }
56
57 RListToPythonList <- function(RList, separator = ", ")
58 {
59     pythonArrayContent <- sapply(RList, function(elementInList)
60     {
61         if((is.vector(elementInList) || is.list(elementInList)) &&
62             length(elementInList) > 1)
63         {
64             return(RListToPythonList(elementInList, separator))
65         }
66         else
67         {
68             return(paste0("\"", elementInList, "\""))
69         }
70     })
71
72     pythonArray <- paste0("[", paste0(pythonArrayContent, collapse = separator), "]")
73     pythonArray
74 }
75
76 appendToStartIfNotExist <- function(sample, characters)
77 {
78     if(!startsWith(sample, characters))
79         sample <- paste0(characters, sample)
80
81     sample
82 }
83
84 splitToPathAndName = function(path)
85 {
86     path <- appendToStartIfNotExist(path, "/")
87     components <- unlist(stringr::str_split(path, "/"))
88     nameAndPath <- list()
89     nameAndPath$name <- components[length(components)]
90     nameAndPath$path <- trimFromStart(paste0(components[-length(components)], collapse = "/"),
91                                       "/")
92     nameAndPath
93 }