Move all subfolder files to the current / selected folder (Flatten folders) (Unpack folders)

Move files in all subfolders to the current folder, auto rename, delete empty folders, two-step undo:

//Function : Flatten folders (undoable in two steps, including all subfolders)
//Created  : 2022-11-08 (Ken)
//Version  : v0.6 (2026-10-17)


var fsu = DOpus.FSUtil;
FlattenFolders()

function FlattenFolders() {
    var tab = DOpus.listers(0).activetab;
    var dirs = tab.selected_dirs;   // Selected folders
    if (dirs.count == 0) {
        var dirs = tab.dirs;        // Or all folders
        if (dirs.count == 0) return
        var dlgTitle = "Flatten all folders?"
    } else
        var dlgTitle = "Flatten the selected folders?"

    var dlg = DOpus.dlg();
    dlg.title = "Flatten Folders (Undoable in Two Steps)";
    dlg.message = dlgTitle;
    dlg.buttons = "&OK|&Cancel";
    dlg.show;
    if (dlg.result != 1) return

    var soucepath = tab.path;
    var cmd = DOpus.Create().Command;

    // Enumerate all files in each selected folder, including subfolders
    cmd.ClearFiles();
    for (var eSel = new Enumerator(dirs); !eSel.atEnd(); eSel.moveNext())
	{
        var eFolder = eSel.item();
        var folderEnum = fsu.ReadDir(eFolder, "r");
        while (!folderEnum.complete) {
            var item = folderEnum.Next;
            if (!item.is_dir)
                cmd.AddFile(item)
        }
    }

    // Move all files to the current folder using the Rename command
    if (cmd.filecount)
        cmd.RunCommand('Rename PATTERN="*" TO="' + soucepath + '\\' + '*"' + ' AUTORENAME');

    // Check whether each folder contains any files
    cmd.ClearFiles();
    for (var eSel = new Enumerator(dirs); !eSel.atEnd(); eSel.moveNext())
	{
        var eItem = eSel.item();
        if (!FileCountRecursive(eItem))
            cmd.AddFile(eItem);
    }

    // Delete the selected folders if they are empty
    if (cmd.filecount)
        cmd.RunCommand('Delete FILE RECYCLE QUIET');

    DOpus.Notify("Flatten Folders", "Folder flattening completed!", "n");
}

function FileCountRecursive(filePath) {
    var fileCount = 0;
    var folderEnum = fsu.ReadDir(filePath, "r");
    while (!folderEnum.complete) {
        var folderItem = folderEnum.Next;
        if (!folderItem.is_dir) {
            ++fileCount;
        }
    }
    return fileCount;
}

Toolbar button:
Unpack folders v0.6.dcf (4.5 KB)
Unpack folders v0.5.dcf (3.5 KB)

=========================================================================
Move all subfolder files to the selected folders:

//Function : Flatten subfolders (undoable in two steps, including all nested subfolders)
//Created  : 2023-08-21 (Ken)
//Version  : v0.3 (2026-10-17)


var fsu = DOpus.FSUtil;
FlattenFolders()

function FlattenFolders() {
    var tab = DOpus.listers(0).activetab;
    var dirs = tab.selected_dirs;   // Selected folders
    if (dirs.count == 0) {
        var dirs = tab.dirs;        // Or all folders
        if (dirs.count == 0) return
        var dlgTitle = "Flatten all subfolders in all folders?"
    } else
        var dlgTitle = "Flatten all subfolders in the selected folders?"

    var dlg = DOpus.dlg();
    dlg.title = "Flatten Subfolders (Undoable in Two Steps)";
    dlg.message = dlgTitle;
    dlg.buttons = "&OK|&Cancel";
    dlg.show;
    if (dlg.result != 1) return

    var cmd = DOpus.Create().Command;

    // Add the folders to the command object (equivalent to @dirsonly)
    cmd.ClearFiles();
    for (var eSel = new Enumerator(dirs); !eSel.atEnd(); eSel.moveNext())
	{
        var eFolder = eSel.item();
        cmd.AddFile(eFolder);
    }

    // Move files from subfolders to their parent folders using the Rename command
    cmd.RunCommand('Rename FROM="{filepath}\*\*" TYPE=dirs TO="{filepath}*" AUTORENAME RECURSE');

    // Check whether each subfolder contains any files
    cmd.ClearFiles();
    for (var eSel = new Enumerator(dirs); !eSel.atEnd(); eSel.moveNext())
	{
        var eFolder = eSel.item();
        var folderEnum = fsu.ReadDir(eFolder);
        while (!folderEnum.complete) {
            var folderItem = folderEnum.Next;
            if (folderItem.is_dir)
                if (!FileCountRecursive(folderItem))
                    cmd.AddFile(folderItem);
        }
    }

    // Delete empty subfolders
    if (cmd.filecount)
        cmd.RunCommand('Delete FILE RECYCLE QUIET');

    DOpus.Notify("Flatten Subfolders", "Subfolder flattening completed!", "n");
}

function FileCountRecursive(filePath) {
    var fileCount = 0;
    var folderEnum = fsu.ReadDir(filePath, "r");
    while (!folderEnum.complete) {
        var folderItem = folderEnum.Next;
        if (!folderItem.is_dir) {
            ++fileCount;
        }
    }
    return fileCount;
}

Toolbar button: Move all subfolder files to the selected folders
Unpack subfolders v0.3.dcf (4.5 KB)
Unpack subfolders v0.2.dcf (4.4 KB)

5 Likes

Is this different to the more simple Move everything up command from the pinned Quick buttons for directory organisation post?

The Delete command has a SKIPNOTEMPTY argument which should make that a one-liner.

I modified the topic, similar to this script:
Command:Unpack folders with one step undoable - Buttons/Scripts - Directory Opus Resource Centre (dopus.com)
But there seems to be something wrong with this script.

Yes, I tried and tried some combinations, but it says that an error occurred.

It helps if you tell us what the error was, and also what the command was. :slight_smile:

Ok I have time to report it now, start a new topic.
Edit:
This is not an issue. . .
I want to delete the folders to the recycle.
image

Hi @WKen, your code is very useful, congratulations!!!

I replaced in the line: cmd.RunCommand('Rename PATTERN="*" TO="{filepath|..}*" AUTORENAME RECURSE HERE');

"{filepath|..}*" with "{filepath$}*"

So that the files are moved to the root of the selected folder, and I managed to move the files, but empty subfolders are not removed.

Before

Folder ABC (selected folder)
    Sudfolder 1
        File 1
        File 2
    Sudfolder 2
        File 3
        File 4

After

Folder ABC  (selected folder)
    Sudfolder 1 (empty)
    Sudfolder 2 (empty)
         File 1
         File 2
         File 3
         File 4

Could you help me to remove these empty subfolders? Thank you so much!

Perfect @WKen , thank you very much, it has left me very happy! :grinning: