]> git.tdb.fi Git - libs/datafile.git/blobdiff - source/directorysource.cpp
Redesign automatic object loading
[libs/datafile.git] / source / directorysource.cpp
diff --git a/source/directorysource.cpp b/source/directorysource.cpp
new file mode 100644 (file)
index 0000000..4ee3b80
--- /dev/null
@@ -0,0 +1,73 @@
+#include <msp/fs/dir.h>
+#include <msp/fs/stat.h>
+#include "collection.h"
+#include "directorysource.h"
+
+using namespace std;
+
+namespace Msp {
+namespace DataFile {
+
+DirectorySource::DirectorySource()
+{
+       set_directory(".");
+}
+
+void DirectorySource::set_directory(const FS::Path &d)
+{
+       dirs.clear();
+       add_directory(d);
+}
+
+void DirectorySource::add_directory(const FS::Path &d)
+{
+       dirs.push_back(d);
+}
+
+bool DirectorySource::is_loadable(const CollectionItemTypeBase &, const string &name) const
+{
+       FS::Path path;
+       return lookup_file(name, path);
+}
+
+CollectionSource::NameList DirectorySource::get_names(const CollectionItemTypeBase &type) const
+{
+       NameList names;
+       for(list<FS::Path>::const_iterator i=dirs.begin(); i!=dirs.end(); ++i)
+       {
+               list<string> files = FS::list_files(*i);
+               for(list<string>::const_iterator j=files.begin(); j!=files.end(); ++j)
+                       if(type.match_name(*j))
+                               names.push_back(*j);
+       }
+       return names;
+}
+
+void DirectorySource::load(Collection &coll, const CollectionItemTypeBase &type, const string &name) const
+{
+       FS::Path file;
+       if(lookup_file(name, file))
+       {
+               IO::BufferedFile in(file.str());
+               Parser parser(in, file.str());
+               type.load_item(coll, parser, name);
+       }
+}
+
+bool DirectorySource::lookup_file(const string &name, FS::Path &result) const
+{
+       for(list<FS::Path>::const_iterator i=dirs.begin(); i!=dirs.end(); ++i)
+       {
+               FS::Path file_path = *i/name;
+               if(FS::exists(file_path))
+               {
+                       result = file_path;
+                       return true;
+               }
+       }
+
+       return false;
+}
+
+} // namespace DataFile
+} // namespace Msp