Skip to content

Instantly share code, notes, and snippets.

@jonocarroll
Last active November 13, 2023 23:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonocarroll/d5d315f1504d4cf8a06caf0bfdf58af5 to your computer and use it in GitHub Desktop.
Save jonocarroll/d5d315f1504d4cf8a06caf0bfdf58af5 to your computer and use it in GitHub Desktop.
Microsoft365 Sharepoint File Tree Capture and View
library(Microsoft365R)
library(jsTree) # for viewing results
sp_url <- "https://org.sharepoint.com/sites/SITENAME/"
# sharepoint site
site <- get_sharepoint_site(site_url = sp_url)
# default document library
drv <- site$get_drive()
# use a depth-first search to list all the files and folders
# in a document library recursively, up to some depth max_i
dfs <- function(drv, tree = drv$list_items()[NULL, ], start = "", i = 0, max_i = 8) {
start_df <- drv$list_items(start)
# non-folders at this level
files <- start_df[!start_df$isdir, , drop = FALSE]
files$name <- file.path(start, files$name)
tree <- rbind(tree, files)
# folders at this level
folders <- start_df[start_df$isdir, , drop = FALSE]
if (nrow(folders) == 0) {
return(tree)
}
for (x in seq_len(nrow(folders))) {
newstart <- file.path(start, folders$name[x])
message("Entering: ", newstart)
# message(" ( i = ", i, " )")
if (i < max_i) {
tree <- dfs(drv, tree, start = newstart, i = i + 1, max_i = max_i)
} else {
return(tree)
}
}
tree
}
tree <- dfs(drv, max_i = 4)
# view the tree interactively
tmptree <- tree$name
tmptree <- sub("/", "", tmptree)
jsTree(tmptree)
@tarensanders
Copy link

Stumbled across this and it was exactly what I needed.

One small suggested edit is that this line

tree <- dfs(drv, tree, start = newstart, i = i + 1)

should be

tree <- dfs(drv, tree, start = newstart, i = i + 1, max_i = max_i)

Otherwise, it ignores the max_i parameter provided and uses the default as it progresses the tree.

@jonocarroll
Copy link
Author

Ah, yes - I fixed that in my local copy but forgot to upload here; thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment