FsDiscoverer.cpp 1.68 KB
Newer Older
1 2 3 4
#include "FsDiscoverer.h"

#include "factory/FileSystem.h"
#include <queue>
5
#include <iostream>
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32

FsDiscoverer::FsDiscoverer( std::shared_ptr<factory::IFileSystem> fsFactory, IDiscovererCb* discoveryCb )
    : m_discoveryCb( discoveryCb )
{
    if ( fsFactory != nullptr )
        m_fsFactory = fsFactory;
    else
        m_fsFactory.reset( new factory::FileSystemDefaultFactory );
}

bool FsDiscoverer::discover( const std::string &entryPoint )
{
    std::queue<std::pair<std::string, FolderPtr>> folders;

    folders.emplace( entryPoint, nullptr );
    while ( folders.empty() == false )
    {
        std::unique_ptr<fs::IDirectory> dir;
        auto currentFolder = folders.front();
        auto currentPath = currentFolder.first;
        auto parent = currentFolder.second;
        folders.pop();

        try
        {
            dir = m_fsFactory->createDirectory( currentPath );
        }
33
        catch ( std::runtime_error& ex )
34
        {
35
            std::cerr << ex.what() << std::endl;
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
            // If the first directory fails to open, stop now.
            // Otherwise, assume something went wrong in a subdirectory.
            if (parent == nullptr)
                return false;
            continue;
        }

        auto folder = m_discoveryCb->onNewFolder( dir.get(), parent );
        if ( folder == nullptr && parent == nullptr )
            return false;
        if ( folder == nullptr )
            continue;

        for ( auto& f : dir->files() )
        {
            auto fsFile = m_fsFactory->createFile( f );
            m_discoveryCb->onNewFile( fsFile.get(), folder );
        }
        for ( auto& f : dir->dirs() )
            folders.emplace( f, folder );
    }
    return true;
}