8 #include <msp/core/systemerror.h>
9 #include <msp/strings/regex.h>
10 #include <msp/strings/utils.h>
24 /** Helper function to determine the location of the program's executable.
25 Caches the last result to cut down filesystem access with repeated calls. */
26 const Path &get_bin_dir(const string &argv0)
28 static string last_argv0;
31 if(!(argv0==last_argv0))
34 if(argv0.find('/')==string::npos)
36 const char *path = getenv("PATH");
37 vector<string> dirs = split(path, ':');
38 for(vector<string>::const_iterator i=dirs.begin(); i!=dirs.end(); ++i)
39 if(exists(Path(*i)/argv0))
41 exe = realpath(Path(*i)/argv0);
46 exe = realpath(argv0);
49 bin_dir = dirname(exe);
58 not_a_directory::not_a_directory(const Path &p):
59 runtime_error(p.str())
63 void mkdir(const Path &path, int mode)
67 // The win32 version of this function doesn't take the mode argument. Go figure.
69 err = ::mkdir(path.str().c_str());
71 err = ::mkdir(path.str().c_str(), mode);
75 throw system_error("mkdir");
78 void mkpath(const Path &path, int mode)
81 for(Path::Iterator i=path.begin(); i!=path.end(); ++i)
85 if(p.size()==1 && p.is_absolute())
89 int err = stat(p, st);
92 if(!S_ISDIR(st.st_mode))
93 throw not_a_directory(p);
96 else if(errno!=ENOENT)
97 throw system_error("mkpath:stat");
103 void rmdir(const Path &path)
105 if(::rmdir(path.str().c_str())==-1)
106 throw system_error("rmdir");
109 void rmdirs(const Path &path)
111 list<string> files = list_files(path);
112 for(list<string>::iterator i=files.begin(); i!=files.end(); ++i)
115 struct stat st = stat(p.str().c_str());
116 if(S_ISDIR(st.st_mode))
125 list<string> list_files(const Path &path)
127 return list_filtered(path, string());
130 list<string> list_filtered(const Path &path, const string &filter)
132 Regex r_filter(filter);
135 DIR *dir = opendir(path.str().c_str());
138 while(dirent *de = readdir(dir))
140 const char *fn = de->d_name;
141 if(fn[0]=='.' && (fn[1]==0 || (fn[1]=='.' && fn[2]==0)))
143 if(r_filter.match(fn))
144 result.push_back(fn);
155 return ::getcwd(buf, sizeof(buf));
162 if(SHGetFolderPath(0, CSIDL_PERSONAL, 0, 0, home)==S_OK)
165 const char *home = getenv("HOME");
172 Path get_user_data_dir(const string &appname)
175 char datadir[MAX_PATH];
176 if(SHGetFolderPath(0, CSIDL_LOCAL_APPDATA, 0, 0, datadir)==S_OK)
177 return Path(datadir)/appname;
180 return get_home_dir()/("."+appname);
184 Path get_sys_conf_dir(const string &argv0)
186 Path dir = get_bin_dir(argv0);
188 if(dir[-1]=="bin" || dir[-1]=="sbin")
199 Path get_sys_data_dir(const string &argv0, const string &appname)
201 Path dir = get_bin_dir(argv0);
203 if(dir[-1]=="bin" || dir[-1]=="sbin")
204 return dir/".."/"share"/appname;
209 Path get_sys_lib_dir(const string &argv0, const string &appname)
211 Path dir = get_bin_dir(argv0);
213 if(dir[-1]=="bin" || dir[-1]=="sbin")
214 return dir/".."/"lib"/appname;
219 void chdir(const Path &path)
221 if(::chdir(path.str().c_str())==-1)
222 throw system_error("chdir");