-
Notifications
You must be signed in to change notification settings - Fork 0
/
Config.h
120 lines (109 loc) · 3.07 KB
/
Config.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#pragma once
#include <sstream>
#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>
#include <vector>
#include <iostream>
#include <fstream>
#include <map>
class Config
{
public:
static Config* GetInstance()
{
if(instance == 0)
{
instance = new Config;
}
return instance;
}
std::vector<std::string> GetLibDirs()
{
std::vector<std::string> dirs;
std::string cfgvalue = m_configs["libdirs"];
cfgvalue.erase(cfgvalue.begin());
cfgvalue.erase(cfgvalue.end()-1);
cfgvalue = this->Trim(cfgvalue);
std::istringstream iss(cfgvalue);
std::string dir;
while( std::getline(iss, dir, ',') )
{
dir = this->Trim(dir);
dir.erase(dir.begin());
dir.erase(dir.end()-1);
dir = this->Trim(dir);
dirs.push_back(dir);
}
return dirs;
}
// NOTE: default behavior is false
bool GetRepeat()
{
return m_configs["repeat"] == "true";
}
// NOTE: default behavior is false
bool GetShuffle()
{
return m_configs["shuffle"] == "true";
}
private:
Config()
{
struct passwd *pw = getpwuid(getuid());
std::string configpath = std::string(pw->pw_dir) + "/.mmconfig";
if(std::ifstream(configpath))
{
// std::cout << "found config file" << std::endl;
}
else
{
// std::cout << "config file not found, creating one" << std::endl;
std::ofstream configfile(configpath);
configfile << "# configuration file for music-magister" << std::endl;
configfile << std::endl;
configfile << "repeat = false" << std::endl;
configfile << "shuffle = true" << std::endl;
configfile << "libdirs = ['" << pw->pw_dir << "/Music']" << std::endl;
}
this->Process(configpath);
}
void Process(std::string filename)
{
std::ifstream infile(filename);
std::string line;
while (std::getline(infile, line))
{
this->ParseLine(line);
}
}
std::string Trim(std::string s)
{
std::string::const_iterator it = s.begin();
while (it != s.end() && isspace(*it))
it++;
std::string::const_reverse_iterator rit = s.rbegin();
while (rit.base() != it && isspace(*rit))
rit++;
s = std::string(it, rit.base());
return s;
}
void ParseLine(std::string line)
{
line = this->Trim(line);
std::istringstream iss(line);
std::string key, value;
if(line.length() > 0 && line.at(0) != '#')
{
if( std::getline(iss, key, '=') )
{
std::getline(iss, value);
m_configs[this->Trim(key)] = this->Trim(value);
//std::cout << "key: " << key << ", value: " << value << std::endl;
}
}
}
std::map<std::string, std::string> m_configs;
static Config* instance;
};
Config* Config::instance = 0;