directory tree -> array

Dick Kriesel dick.kriesel at mail.com
Sat Feb 1 16:16:50 EST 2020


> On Jan 22, 2020, at 10:17 AM, Richard Gaskin via use-livecode <use-livecode at lists.runrev.com> wrote:
> 
> I stumbled across a code challenge for y'all, one that seems seductively simple but I don't think it is:
> 
> What is the simplest way to build an array that reflects the files and folders within a given folder?
> 
> There's a discussion about this here:
> 
> https://forums.livecode.com/viewtopic.php?f=7&t=33565
> 
> 
> On Jan 22, 2020, at 10:26 AM, Richard Gaskin via use-livecode <use-livecode at lists.runrev.com> wrote:

> 
> We have many handlers that deliver directory trees as lists, but arrays are a different beast.  Because the depth is both unknowable and varied, I can't think of a way to do this without resorting to "do".



Since that thread vanished last week, and hasn’t returned, I'm offering help here instead.

The list of full paths contains enough information to build an array representation of the directory tree.

<code>
/**

Summary: Given a list of full paths, and given the partial path they share, build an array representing the directory structure

pPaths: a return-delimited list of full paths

pPath: the path that was used to generate the list of full paths

Returns (array): A array with a branch node for each folder and a leaf node for each file

Description: Eliminate pPath from every line of pPaths. Then insert each line into an array.

email subject "directory tree -> array"

forum topic "f=7&t=33565"

*/


function arrayFromPaths pPaths, pPath -- a list of full paths, and the path that was used to generate the list

local tPaths, tFile, tArray

set the itemDelimiter to "/"


put char 2 to -1 of replaceText( cr & pPaths, cr & pPath & slash, cr ) into tPaths -- eliminate pPath from every full path

repeat for each line tPath in tPaths -- insert each file name into the array

put the last item of tPath into tFile

delete the last item of tPath

if tPath is empty then -- the file is in folder pPath

put "true" into tArray[ tFile ]

else -- the file is in a folder in folder pPath

split tPath by slash

put "true" into tArray[ tPath ][ tFile ]

end if

end repeat


return tArray

end arrayFromPaths


on mouseUp

local tPaths = "a/b/c,a/b/d/e,a/b/d/f" -- folder a/b contains file c and folder d, which contains files e and f

local tPath = "a/b" -- the shared partial path

replace comma with cr in tPaths


get arrayFromPaths( tPaths, tPath )


breakpoint

end mouseUp


</code>

If the topic reappears soon, I’ll repost there because reading code is easier there.

By, the way, thanks to RG for the bug report on my earlier posting in the now-vanished thread.

— Dick






More information about the use-livecode mailing list