]> git.tdb.fi Git - libs/datafile.git/blob - source/directorysource.cpp
4ee3b80657eb014bf9bfee540d365879c27fc8c2
[libs/datafile.git] / source / directorysource.cpp
1 #include <msp/fs/dir.h>
2 #include <msp/fs/stat.h>
3 #include "collection.h"
4 #include "directorysource.h"
5
6 using namespace std;
7
8 namespace Msp {
9 namespace DataFile {
10
11 DirectorySource::DirectorySource()
12 {
13         set_directory(".");
14 }
15
16 void DirectorySource::set_directory(const FS::Path &d)
17 {
18         dirs.clear();
19         add_directory(d);
20 }
21
22 void DirectorySource::add_directory(const FS::Path &d)
23 {
24         dirs.push_back(d);
25 }
26
27 bool DirectorySource::is_loadable(const CollectionItemTypeBase &, const string &name) const
28 {
29         FS::Path path;
30         return lookup_file(name, path);
31 }
32
33 CollectionSource::NameList DirectorySource::get_names(const CollectionItemTypeBase &type) const
34 {
35         NameList names;
36         for(list<FS::Path>::const_iterator i=dirs.begin(); i!=dirs.end(); ++i)
37         {
38                 list<string> files = FS::list_files(*i);
39                 for(list<string>::const_iterator j=files.begin(); j!=files.end(); ++j)
40                         if(type.match_name(*j))
41                                 names.push_back(*j);
42         }
43         return names;
44 }
45
46 void DirectorySource::load(Collection &coll, const CollectionItemTypeBase &type, const string &name) const
47 {
48         FS::Path file;
49         if(lookup_file(name, file))
50         {
51                 IO::BufferedFile in(file.str());
52                 Parser parser(in, file.str());
53                 type.load_item(coll, parser, name);
54         }
55 }
56
57 bool DirectorySource::lookup_file(const string &name, FS::Path &result) const
58 {
59         for(list<FS::Path>::const_iterator i=dirs.begin(); i!=dirs.end(); ++i)
60         {
61                 FS::Path file_path = *i/name;
62                 if(FS::exists(file_path))
63                 {
64                         result = file_path;
65                         return true;
66                 }
67         }
68
69         return false;
70 }
71
72 } // namespace DataFile
73 } // namespace Msp