bsnes: redump sprite/palette functions
[lsnes.git] / src / library / filelist.cpp
blobe3b1d9a6a2fb010cca4f48ef47fc7e6309444b1b
1 #include "filelist.hpp"
2 #include <fstream>
3 #include <string>
4 #include "filelist.hpp"
5 #include "directory.hpp"
6 #include "zip.hpp"
7 #include "string.hpp"
9 filelist::filelist(const std::string& _backingfile, const std::string& _directory)
10 : backingfile(_backingfile), directory(_directory)
14 filelist::~filelist()
18 std::set<std::string> filelist::enumerate()
20 auto contents = readfile();
21 check_stale(contents);
22 writeback(contents);
23 std::set<std::string> ret;
24 for(auto i : contents)
25 if(i.second != 0)
26 ret.insert(i.first);
27 return ret;
30 void filelist::add(const std::string& filename)
32 auto contents = readfile();
33 int64_t ts = file_get_mtime(directory + "/" + filename);
34 contents[filename] = ts;
35 writeback(contents);
38 void filelist::remove(const std::string& filename)
40 auto contents = readfile();
41 int64_t ts = file_get_mtime(directory + "/" + filename);
42 contents.erase(filename);
43 writeback(contents);
46 void filelist::rename(const std::string& oldname, const std::string& newname)
48 auto contents = readfile();
49 contents[newname] = contents[oldname];
50 contents.erase(oldname);
51 writeback(contents);
54 std::map<std::string, int64_t> filelist::readfile()
56 std::map<std::string, int64_t> contents;
57 std::ifstream strm(backingfile);
58 std::string line;
59 while(std::getline(strm, line)) {
60 regex_results r = regex("([0-9]+) (.*)", line);
61 if(!r) continue;
62 int64_t ts;
63 try { ts = parse_value<int64_t>(r[1]); } catch(...) { continue; }
64 contents[r[2]] = ts;
66 return contents;
69 void filelist::check_stale(std::map<std::string, int64_t>& data)
71 for(auto& i : data) {
72 int64_t ts = file_get_mtime(directory + "/" + i.first);
73 //If file timestamp does not match, mark the file as stale.
74 if(i.second != ts)
75 i.second = 0;
79 void filelist::writeback(const std::map<std::string, int64_t>& data)
81 std::string backingtmp = backingfile + ".new";
82 std::ofstream strm(backingtmp);
83 if(!strm)
84 return;
85 for(auto& i : data)
86 if(i.second != 0)
87 strm << i.second << " " << i.first << std::endl;
88 strm.close();
89 zip::rename_overwrite(backingtmp.c_str(), backingfile.c_str());