1 getAPIDocument <- function(){
2 url <- "https://4xphq.arvadosapi.com/discovery/v1/apis/arvados/v1/rest"
3 serverResponse <- httr::RETRY("GET", url = url)
5 httr::content(serverResponse, as = "parsed", type = "application/json")
9 generateAPI <- function()
11 #TODO: Consider passing discovery document URL as parameter.
12 #TODO: Consider passing location where to create new files.
13 discoveryDocument <- getAPIDocument()
15 methodResources <- discoveryDocument$resources
16 resourceNames <- names(methodResources)
18 methodDoc <- genMethodsDoc(methodResources, resourceNames)
19 classDoc <- genAPIClassDoc(methodResources, resourceNames)
20 arvadosAPIHeader <- genAPIClassHeader()
21 arvadosProjectMethods <- genProjectMethods()
22 arvadosClassMethods <- genClassContent(methodResources, resourceNames)
23 arvadosAPIFooter <- genAPIClassFooter()
25 arvadosClass <- c(methodDoc,
28 arvadosProjectMethods,
32 fileConn <- file("./R/Arvados.R", "w")
33 writeLines(unlist(arvadosClass), fileConn)
38 genAPIClassHeader <- function()
40 c("Arvados <- R6::R6Class(",
46 "\t\tinitialize = function(authToken = NULL, hostName = NULL, numRetries = 0)",
48 "\t\t\tif(!is.null(hostName))",
49 "\t\t\t\tSys.setenv(ARVADOS_API_HOST = hostName)",
51 "\t\t\tif(!is.null(authToken))",
52 "\t\t\t\tSys.setenv(ARVADOS_API_TOKEN = authToken)",
54 "\t\t\thostName <- Sys.getenv(\"ARVADOS_API_HOST\")",
55 "\t\t\ttoken <- Sys.getenv(\"ARVADOS_API_TOKEN\")",
57 "\t\t\tif(hostName == \"\" | token == \"\")",
58 "\t\t\t\tstop(paste(\"Please provide host name and authentification token\",",
59 "\t\t\t\t\t\t \"or set ARVADOS_API_HOST and ARVADOS_API_TOKEN\",",
60 "\t\t\t\t\t\t \"environment variables.\"))",
62 "\t\t\tprivate$token <- token",
63 "\t\t\tprivate$host <- paste0(\"https://\", hostName, \"/arvados/v1/\")",
64 "\t\t\tprivate$numRetries <- numRetries",
65 "\t\t\tprivate$REST <- RESTService$new(token, hostName,",
66 "\t\t\t HttpRequest$new(), HttpParser$new(),",
72 genProjectMethods <- function()
74 c("\t\tprojects.get = function(uuid)",
76 "\t\t\tself$groups.get(uuid)",
79 "\t\tprojects.create = function(group, ensure_unique_name = \"false\")",
81 "\t\t\tgroup <- c(\"group_class\" = \"project\", group)",
82 "\t\t\tself$groups.create(group, ensure_unique_name)",
85 "\t\tprojects.update = function(group, uuid)",
87 "\t\t\tgroup <- c(\"group_class\" = \"project\", group)",
88 "\t\t\tself$groups.update(group, uuid)",
91 "\t\tprojects.list = function(filters = NULL, where = NULL,",
92 "\t\t\torder = NULL, select = NULL, distinct = NULL,",
93 "\t\t\tlimit = \"100\", offset = \"0\", count = \"exact\",",
94 "\t\t\tinclude_trash = NULL)",
96 "\t\t\tfilters[[length(filters) + 1]] <- list(\"group_class\", \"=\", \"project\")",
97 "\t\t\tself$groups.list(filters, where, order, select, distinct,",
98 "\t\t\t limit, offset, count, include_trash)",
101 "\t\tprojects.delete = function(uuid)",
103 "\t\t\tself$groups.delete(uuid)",
108 genClassContent <- function(methodResources, resourceNames)
110 arvadosMethods <- Map(function(resource, resourceName)
112 methodNames <- names(resource$methods)
114 functions <- Map(function(methodMetaData, methodName)
116 #NOTE: Index, show and destroy are aliases for the preferred names
117 # "list", "get" and "delete". Until they are removed from discovery
118 # document we will filter them here.
119 if(methodName %in% c("index", "show", "destroy"))
122 methodName <- paste0(resourceName, ".", methodName)
123 createMethod(methodName, methodMetaData)
125 }, resource$methods, methodNames)
127 unlist(unname(functions))
129 }, methodResources, resourceNames)
134 genAPIClassFooter <- function()
136 c("\t\tgetHostName = function() private$host,",
137 "\t\tgetToken = function() private$token,",
138 "\t\tsetRESTService = function(newREST) private$REST <- newREST,",
139 "\t\tgetRESTService = function() private$REST",
147 "\t\tnumRetries = NULL",
150 "\tcloneable = FALSE",
154 createMethod <- function(name, methodMetaData)
156 args <- getMethodArguments(methodMetaData)
157 signature <- getMethodSignature(name, args)
158 body <- getMethodBody(methodMetaData)
166 getMethodArguments <- function(methodMetaData)
168 request <- methodMetaData$request
171 if(!is.null(request))
173 resourceName <- tolower(request$properties[[1]][[1]])
176 requestArgs <- resourceName
178 requestArgs <- paste(resourceName, "=", "NULL")
181 argNames <- names(methodMetaData$parameters)
183 args <- sapply(argNames, function(argName)
185 arg <- methodMetaData$parameters[[argName]]
189 if(!is.null(arg$default))
190 return(paste0(argName, " = ", "\"", arg$default, "\""))
192 return(paste(argName, "=", "NULL"))
201 getMethodSignature <- function(methodName, args)
203 collapsedArgs <- paste0(args, collapse = ", ")
204 lineLengthLimit <- 40
206 if(nchar(collapsedArgs) > lineLengthLimit)
208 return(paste0("\t\t",
209 formatArgs(paste(methodName, "= function("),
210 "\t", args, ")", lineLengthLimit)))
214 return(paste0("\t\t", methodName, " = function(", collapsedArgs, ")"))
218 getMethodBody <- function(methodMetaData)
220 url <- getRequestURL(methodMetaData)
221 headers <- getRequestHeaders()
222 requestQueryList <- getRequestQueryList(methodMetaData)
223 requestBody <- getRequestBody(methodMetaData)
224 request <- getRequest(methodMetaData)
225 response <- getResponse(methodMetaData)
226 errorCheck <- getErrorCheckingCode()
227 returnStatement <- getReturnObject()
231 requestQueryList, "",
233 request, response, "",
237 paste0("\t\t\t", body)
240 getRequestURL <- function(methodMetaData)
242 endPoint <- methodMetaData$path
243 endPoint <- stringr::str_replace_all(endPoint, "\\{", "${")
244 url <- c(paste0("endPoint <- stringr::str_interp(\"", endPoint, "\")"),
245 paste0("url <- paste0(private$host, endPoint)"))
249 getRequestHeaders <- function()
251 c("headers <- list(Authorization = paste(\"OAuth2\", private$token), ",
252 " \"Content-Type\" = \"application/json\")")
255 getRequestQueryList <- function(methodMetaData)
257 queryArgs <- names(Filter(function(arg) arg$location == "query",
258 methodMetaData$parameters))
260 if(length(queryArgs) == 0)
261 return("queryArgs <- NULL")
263 queryArgs <- sapply(queryArgs, function(arg) paste0(arg, " = ", arg))
264 collapsedArgs <- paste0(queryArgs, collapse = ", ")
266 lineLengthLimit <- 40
268 if(nchar(collapsedArgs) > lineLengthLimit)
269 return(formatArgs("queryArgs <- list(", "\t\t\t\t ", queryArgs, ")",
272 return(paste0("queryArgs <- list(", collapsedArgs, ")"))
275 getRequestBody <- function(methodMetaData)
277 request <- methodMetaData$request
279 if(is.null(request) || !request$required)
280 return("body <- NULL")
282 resourceName <- tolower(request$properties[[1]][[1]])
284 requestParameterName <- names(request$properties)[1]
286 c(paste0("if(length(", resourceName, ") > 0)"),
287 paste0("\tbody <- jsonlite::toJSON(list(", resourceName, " = ", resourceName, "), "),
288 "\t auto_unbox = TRUE)",
293 getRequest <- function(methodMetaData)
295 method <- methodMetaData$httpMethod
296 c(paste0("response <- private$REST$http$exec(\"", method, "\", url, headers, body,"),
297 " queryArgs, private$numRetries)")
300 getResponse <- function(methodMetaData)
302 "resource <- private$REST$httpParser$parseJSONResponse(response)"
305 getErrorCheckingCode <- function()
307 c("if(!is.null(resource$errors))",
308 "\tstop(resource$errors)")
311 getReturnObject <- function()
316 #NOTE: Arvados class documentation:
318 genMethodsDoc <- function(methodResources, resourceNames)
320 methodsDoc <- unlist(unname(Map(function(resource, resourceName)
322 methodNames <- names(resource$methods)
324 methodDoc <- Map(function(methodMetaData, methodName)
326 #NOTE: Index, show and destroy are aliases for the preferred names
327 # "list", "get" and "delete". Until they are removed from discovery
328 # document we will filter them here.
329 if(methodName %in% c("index", "show", "destroy"))
332 methodName <- paste0(resourceName, ".", methodName)
333 getMethodDoc(methodName, methodMetaData)
335 }, resource$methods, methodNames)
337 unlist(unname(methodDoc))
339 }, methodResources, resourceNames)))
341 projectDoc <- genProjectMethodsDoc()
343 c(methodsDoc, projectDoc)
346 genAPIClassDoc <- function(methodResources, resourceNames)
350 "#' Arvados class gives users ability to access Arvados REST API.",
352 "#' @section Usage:",
353 "#' \\preformatted{arv = Arvados$new(authToken = NULL, hostName = NULL, numRetries = 0)}",
355 "#' @section Arguments:",
357 "#' \t\\item{authToken}{Authentification token. If not specified ARVADOS_API_TOKEN environment variable will be used.}",
358 "#' \t\\item{hostName}{Host name. If not specified ARVADOS_API_HOST environment variable will be used.}",
359 "#' \t\\item{numRetries}{Number which specifies how many times to retry failed service requests.}",
362 "#' @section Methods:",
364 getAPIClassMethodList(methodResources, resourceNames),
370 "#' arv <- Arvados$new(\"your Arvados token\", \"example.arvadosapi.com\")",
372 "#' collection <- arv$collections.get(\"uuid\")",
374 "#' collectionList <- arv$collections.list(list(list(\"name\", \"like\", \"Test%\")))",
375 "#' collectionList <- listAll(arv$collections.list, list(list(\"name\", \"like\", \"Test%\")))",
377 "#' deletedCollection <- arv$collections.delete(\"uuid\")",
379 "#' updatedCollection <- arv$collections.update(list(name = \"New name\", description = \"New description\"),",
382 "#' createdCollection <- arv$collections.create(list(name = \"Example\",",
383 "#' description = \"This is a test collection\"))",
390 getAPIClassMethodList <- function(methodResources, resourceNames)
392 methodList <- unlist(unname(Map(function(resource, resourceName)
394 methodNames <- names(resource$methods)
397 methodNames[!(methodNames %in% c("index", "show", "destroy"))])
399 }, methodResources, resourceNames)))
401 hardcodedMethods <- c("projects.create", "projects.get",
402 "projects.list", "projects.update", "projects.delete")
403 paste0("#' \t\\item{}{\\code{\\link{", sort(c(methodList, hardcodedMethods)), "}}}")
406 getMethodDoc <- function(methodName, methodMetaData)
408 name <- paste("#' @name", methodName)
409 usage <- getMethodUsage(methodName, methodMetaData)
410 description <- paste("#'", methodName, "is a method defined in Arvados class.")
411 params <- getMethodDescription(methodMetaData)
412 returnValue <- paste("#' @return", methodMetaData$response[["$ref"]], "object.")
424 getMethodUsage <- function(methodName, methodMetaData)
426 lineLengthLimit <- 40
427 args <- getMethodArguments(methodMetaData)
428 c(formatArgs(paste0("#' @usage arv$", methodName,
429 "("), "#' \t", args, ")", lineLengthLimit))
432 getMethodDescription <- function(methodMetaData)
434 request <- methodMetaData$request
437 if(!is.null(request))
439 requestDoc <- unname(unlist(sapply(request$properties, function(prop)
441 className <- sapply(prop, function(ref) ref)
442 objectName <- paste0(tolower(substr(className, 1, 1)),
443 substr(className, 2, nchar(className)))
444 paste("#' @param", objectName, className, "object.")
448 argNames <- names(methodMetaData$parameters)
450 argsDoc <- unname(unlist(sapply(argNames, function(argName)
452 arg <- methodMetaData$parameters[[argName]]
453 argDescription <- arg$description
454 paste("#' @param", argName, argDescription)
457 c(requestDoc, argsDoc)
460 genProjectMethodsDoc <- function()
462 #TODO: Manually update this documentation to reflect changes in discovery document.
463 c("#' projects.get is equivalent to groups.get method.",
465 "#' @usage arv$projects.get(uuid)",
466 "#' @param uuid The UUID of the Group in question.",
467 "#' @return Group object.",
468 "#' @name projects.get",
471 "#' projects.create wrapps groups.create method by setting group_class attribute to \"project\".",
473 "#' @usage arv$projects.create(group, ensure_unique_name = \"false\")",
474 "#' @param group Group object.",
475 "#' @param ensure_unique_name Adjust name to ensure uniqueness instead of returning an error on (owner_uuid, name) collision.",
476 "#' @return Group object.",
477 "#' @name projects.create",
480 "#' projects.update wrapps groups.update method by setting group_class attribute to \"project\".",
482 "#' @usage arv$projects.update(group, uuid)",
483 "#' @param group Group object.",
484 "#' @param uuid The UUID of the Group in question.",
485 "#' @return Group object.",
486 "#' @name projects.update",
489 "#' projects.delete is equivalent to groups.delete method.",
491 "#' @usage arv$project.delete(uuid)",
492 "#' @param uuid The UUID of the Group in question.",
493 "#' @return Group object.",
494 "#' @name projects.delete",
497 "#' projects.list wrapps groups.list method by setting group_class attribute to \"project\".",
499 "#' @usage arv$projects.list(filters = NULL,",
500 "#' where = NULL, order = NULL, distinct = NULL,",
501 "#' limit = \"100\", offset = \"0\", count = \"exact\",",
502 "#' include_trash = NULL, uuid = NULL, recursive = NULL)",
503 "#' @param filters ",
506 "#' @param distinct ",
510 "#' @param include_trash Include items whose is_trashed attribute is true.",
512 "#' @param recursive Include contents from child groups recursively.",
513 "#' @return Group object.",
514 "#' @name projects.list",
519 #NOTE: Utility functions:
521 # This function is used to split very long lines of code into smaller chunks.
522 # This is usually the case when we pass a lot of named argumets to a function.
523 formatArgs <- function(prependAtStart, prependToEachSplit,
524 args, appendAtEnd, lineLength)
528 args[1:(length(args) - 1)] <- paste0(args[1:(length(args) - 1)], ",")
531 args[1] <- paste0(prependAtStart, args[1])
532 args[length(args)] <- paste0(args[length(args)], appendAtEnd)
534 argsLength <- length(args)
538 while(index <= argsLength)
543 while(nchar(line) < lineLength && index <= argsLength)
545 line <- paste(line, args[index])
549 argLines <- c(argLines, line)
552 argLines <- unlist(argLines)
553 argLinesLen <- length(argLines)
556 argLines[2:argLinesLen] <- paste0(prependToEachSplit, argLines[2:argLinesLen])