1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: Apache-2.0
5 source("./R/Subcollection.R")
6 source("./R/ArvadosFile.R")
9 CollectionTree <- R6::R6Class(
15 initialize = function(fileContent, collection)
17 self$pathsList <- fileContent
18 treeBranches <- sapply(fileContent, function(filePath) self$createBranch(filePath))
19 root <- Subcollection$new("")
20 sapply(treeBranches, function(branch) self$addBranch(root, branch))
21 root$setCollection(collection)
25 createBranch = function(filePath)
27 splitPath <- unlist(strsplit(filePath, "/", fixed = TRUE))
29 lastElementIndex <- length(splitPath)
31 for(elementIndex in lastElementIndex:1)
33 if(elementIndex == lastElementIndex)
35 branch <- ArvadosFile$new(splitPath[[elementIndex]])
39 newFolder <- Subcollection$new(splitPath[[elementIndex]])
48 addBranch = function(container, node)
50 child <- container$get(node$getName())
54 # Make sure we are don't make any REST call while adding child
55 collection <- container$getCollection()
56 container$setCollection(NULL, setRecursively = FALSE)
58 container$setCollection(collection, setRecursively = FALSE)
62 # Note: REST always returns folder name alone before other folder
63 # content, so in first iteration we don't know if it's a file
64 # or folder since its just a name, so we assume it's a file.
65 # If we encounter that same name again we know
66 # it's a folder so we need to replace ArvadosFile with Subcollection.
67 if("ArvadosFile" %in% class(child))
68 child = private$replaceFileWithSubcollection(child)
70 self$addBranch(child, node$getFirst())
74 getElement = function(relativePath)
76 relativePath <- trimFromStart(relativePath, "./")
77 relativePath <- trimFromEnd(relativePath, "/")
79 if(endsWith(relativePath, "/"))
80 relativePath <- substr(relativePath, 0, nchar(relativePath) - 1)
82 splitPath <- unlist(strsplit(relativePath, "/", fixed = TRUE))
83 returnElement <- private$tree
85 for(pathFragment in splitPath)
87 returnElement <- returnElement$get(pathFragment)
89 if(is.null(returnElement))
96 getTree = function() private$tree
103 replaceFileWithSubcollection = function(arvadosFile)
105 subcollection <- Subcollection$new(arvadosFile$getName())
106 fileParent <- arvadosFile$getParent()
107 fileParent$remove(arvadosFile$getName())
108 fileParent$add(subcollection)
110 arvadosFile$setParent(NULL)