]> git.tdb.fi Git - libs/datafile.git/commitdiff
Add DirectoryCollection class for creating directory-backed collections
authorMikko Rasa <tdb@tdb.fi>
Fri, 20 Jan 2012 20:28:06 +0000 (22:28 +0200)
committerMikko Rasa <tdb@tdb.fi>
Fri, 20 Jan 2012 20:28:06 +0000 (22:28 +0200)
source/directorycollection.cpp [new file with mode: 0644]
source/directorycollection.h [new file with mode: 0644]

diff --git a/source/directorycollection.cpp b/source/directorycollection.cpp
new file mode 100644 (file)
index 0000000..25808d6
--- /dev/null
@@ -0,0 +1,41 @@
+#include <msp/fs/stat.h>
+#include "directorycollection.h"
+
+using namespace std;
+
+namespace Msp {
+namespace DataFile {
+
+DirectoryCollection::DirectoryCollection()
+{
+       set_directory(".");
+}
+
+void DirectoryCollection::set_directory(const FS::Path &d)
+{
+       dirs.clear();
+       add_directory(d);
+}
+
+void DirectoryCollection::add_directory(const FS::Path &d)
+{
+       dirs.push_back(d);
+}
+
+bool DirectoryCollection::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
diff --git a/source/directorycollection.h b/source/directorycollection.h
new file mode 100644 (file)
index 0000000..93f9354
--- /dev/null
@@ -0,0 +1,52 @@
+#ifndef MSP_DATAFILE_DIRECTORYCOLLECTION_H_
+#define MSP_DATAFILE_DIRECTORYCOLLECTION_H_
+
+#include <msp/fs/path.h>
+#include "collection.h"
+
+namespace Msp {
+namespace DataFile {
+
+/**
+A Collection that can automatically load items from files in a directory.
+*/
+class DirectoryCollection: public Collection
+{
+private:
+       std::list<FS::Path> dirs;
+
+public:
+       DirectoryCollection();
+
+protected:
+       void set_directory(const FS::Path &);
+       void add_directory(const FS::Path &);
+
+       template<typename T>
+       CollectionItemType<T> &add_type()
+       {
+               return Collection::add_type<T>().creator(&DirectoryCollection::create<T>);
+       }
+
+private:
+       template<typename T>
+       T *create(const std::string &name)
+       {
+               FS::Path file;
+               if(lookup_file(name, file))
+               {
+                       RefPtr<T> item = new T;
+                       load(*item, file.str());
+                       return item.release();
+               }
+               else
+                       return 0;
+       }
+
+       bool lookup_file(const std::string &, FS::Path &) const;
+};
+
+} // namespace DataFile
+} // namespace Msp
+
+#endif