4 #include <msp/core/systemerror.h>
5 #include <msp/strings/regex.h>
6 #include <msp/strings/utils.h>
29 /** Helper function to determine the location of the program's executable.
30 Caches the last result to cut down filesystem access with repeated calls. */
31 const Path &get_bin_dir(const string &argv0)
33 static string last_argv0;
36 if(!(argv0==last_argv0))
39 if(argv0.find('/')==string::npos)
41 const char *path = getenv("PATH");
42 vector<string> dirs = split(path, ITEMSEP);
43 for(vector<string>::const_iterator i=dirs.begin(); i!=dirs.end(); ++i)
44 if(exists(Path(*i)/argv0))
46 exe = realpath(Path(*i)/argv0);
52 exe = realpath(argv0);
55 bin_dir = dirname(exe);
64 not_a_directory::not_a_directory(const Path &p):
65 runtime_error(p.str())
69 void mkpath(const Path &path, int mode)
72 for(Path::Iterator i=path.begin(); i!=path.end(); ++i)
76 if(p.size()==1 && p.is_absolute())
79 if(FS::Stat st = stat(p))
81 if(!st.is_directory())
82 throw not_a_directory(p);
90 void rmpath(const Path &path)
92 list<string> files = list_files(path);
93 for(list<string>::iterator i=files.begin(); i!=files.end(); ++i)
105 list<string> list_files(const Path &path)
107 return list_filtered(path, string());
110 list<string> list_filtered(const Path &path, const string &filter)
112 Regex r_filter(filter);
115 DIR *dir = opendir(path.str().c_str());
117 throw system_error("opendir");
119 while(dirent *de = readdir(dir))
121 const char *fn = de->d_name;
122 if(fn[0]=='.' && (fn[1]==0 || (fn[1]=='.' && fn[2]==0)))
124 if(r_filter.match(fn))
125 result.push_back(fn);
135 return ::getcwd(buf, sizeof(buf));
138 Path get_sys_conf_dir(const string &argv0)
140 Path dir = get_bin_dir(argv0);
142 if(dir[-1]=="bin" || dir[-1]=="sbin")
153 Path get_sys_data_dir(const string &argv0, const string &appname)
155 Path dir = get_bin_dir(argv0);
157 if(dir[-1]=="bin" || dir[-1]=="sbin")
158 return dir/".."/"share"/appname;
159 else if(dir[-1]=="MacOS")
160 return dir/".."/"Resources";
165 Path get_sys_lib_dir(const string &argv0, const string &appname)
167 Path dir = get_bin_dir(argv0);
169 if(dir[-1]=="bin" || dir[-1]=="sbin")
170 return dir/".."/"lib"/appname;
175 void chdir(const Path &path)
177 if(::chdir(path.str().c_str())==-1)
178 throw system_error("chdir");