]> git.tdb.fi Git - libs/datafile.git/blob - source/directorysource.cpp
Simplify DirectorySource path management
[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 void DirectorySource::add_directory(const FS::Path &d)
12 {
13         dirs.push_back(d);
14 }
15
16 bool DirectorySource::is_loadable(const CollectionItemTypeBase &, const string &name) const
17 {
18         FS::Path path;
19         return lookup_file(name, path);
20 }
21
22 CollectionSource::NameList DirectorySource::get_names(const CollectionItemTypeBase &type) const
23 {
24         NameList names;
25         for(list<FS::Path>::const_iterator i=dirs.begin(); i!=dirs.end(); ++i)
26         {
27                 list<string> files = FS::list_files(*i);
28                 for(list<string>::const_iterator j=files.begin(); j!=files.end(); ++j)
29                         if(type.match_name(*j))
30                                 names.push_back(*j);
31         }
32         return names;
33 }
34
35 void DirectorySource::load(Collection &coll, const CollectionItemTypeBase &type, const string &name) const
36 {
37         FS::Path file;
38         if(lookup_file(name, file))
39         {
40                 IO::BufferedFile in(file.str());
41                 Parser parser(in, file.str());
42                 type.load_item(coll, parser, name);
43         }
44 }
45
46 bool DirectorySource::lookup_file(const string &name, FS::Path &result) const
47 {
48         for(list<FS::Path>::const_iterator i=dirs.begin(); i!=dirs.end(); ++i)
49         {
50                 FS::Path file_path = *i/name;
51                 if(FS::exists(file_path))
52                 {
53                         result = file_path;
54                         return true;
55                 }
56         }
57
58         return false;
59 }
60
61 } // namespace DataFile
62 } // namespace Msp