3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 #include "util/string.h"
33 #ifdef _WIN32 // WINDOWS
35 #define _WIN32_WINNT 0x0501
39 std::vector<DirListNode> GetDirListing(const std::string &pathstring)
41 std::vector<DirListNode> listing;
43 WIN32_FIND_DATA FindFileData;
44 HANDLE hFind = INVALID_HANDLE_VALUE;
47 std::string dirSpec = pathstring + "\\*";
49 // Find the first file in the directory.
50 hFind = FindFirstFile(dirSpec.c_str(), &FindFileData);
52 if (hFind == INVALID_HANDLE_VALUE) {
53 dwError = GetLastError();
54 if (dwError != ERROR_FILE_NOT_FOUND && dwError != ERROR_PATH_NOT_FOUND) {
55 errorstream << "GetDirListing: FindFirstFile error."
56 << " Error is " << dwError << std::endl;
60 // Be very sure to not include '..' in the results, it will
61 // result in an epic failure when deleting stuff.
64 node.name = FindFileData.cFileName;
65 node.dir = FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
66 if (node.name != "." && node.name != "..")
67 listing.push_back(node);
69 // List all the other files in the directory.
70 while (FindNextFile(hFind, &FindFileData) != 0) {
72 node.name = FindFileData.cFileName;
73 node.dir = FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
74 if(node.name != "." && node.name != "..")
75 listing.push_back(node);
78 dwError = GetLastError();
80 if (dwError != ERROR_NO_MORE_FILES) {
81 errorstream << "GetDirListing: FindNextFile error."
82 << " Error is " << dwError << std::endl;
90 bool CreateDir(const std::string &path)
92 bool r = CreateDirectory(path.c_str(), NULL);
95 if(GetLastError() == ERROR_ALREADY_EXISTS)
100 bool PathExists(const std::string &path)
102 return (GetFileAttributes(path.c_str()) != INVALID_FILE_ATTRIBUTES);
105 bool IsPathAbsolute(const std::string &path)
107 return !PathIsRelative(path.c_str());
110 bool IsDir(const std::string &path)
112 DWORD attr = GetFileAttributes(path.c_str());
113 return (attr != INVALID_FILE_ATTRIBUTES &&
114 (attr & FILE_ATTRIBUTE_DIRECTORY));
117 bool IsDirDelimiter(char c)
119 return c == '/' || c == '\\';
122 bool RecursiveDelete(const std::string &path)
124 infostream<<"Recursively deleting \""<<path<<"\""<<std::endl;
126 DWORD attr = GetFileAttributes(path.c_str());
127 bool is_directory = (attr != INVALID_FILE_ATTRIBUTES &&
128 (attr & FILE_ATTRIBUTE_DIRECTORY));
131 infostream<<"RecursiveDelete: Deleting file "<<path<<std::endl;
132 //bool did = DeleteFile(path.c_str());
135 errorstream<<"RecursiveDelete: Failed to delete file "
142 infostream<<"RecursiveDelete: Deleting content of directory "
144 std::vector<DirListNode> content = GetDirListing(path);
145 for(size_t i=0; i<content.size(); i++){
146 const DirListNode &n = content[i];
147 std::string fullpath = path + DIR_DELIM + n.name;
148 bool did = RecursiveDelete(fullpath);
150 errorstream<<"RecursiveDelete: Failed to recurse to "
151 <<fullpath<<std::endl;
155 infostream<<"RecursiveDelete: Deleting directory "<<path<<std::endl;
156 //bool did = RemoveDirectory(path.c_str();
159 errorstream<<"Failed to recursively delete directory "
167 bool DeleteSingleFileOrEmptyDirectory(const std::string &path)
169 DWORD attr = GetFileAttributes(path.c_str());
170 bool is_directory = (attr != INVALID_FILE_ATTRIBUTES &&
171 (attr & FILE_ATTRIBUTE_DIRECTORY));
174 bool did = DeleteFile(path.c_str());
179 bool did = RemoveDirectory(path.c_str());
184 std::string TempPath()
186 DWORD bufsize = GetTempPath(0, NULL);
188 errorstream<<"GetTempPath failed, error = "<<GetLastError()<<std::endl;
191 std::vector<char> buf(bufsize);
192 DWORD len = GetTempPath(bufsize, &buf[0]);
193 if(len == 0 || len > bufsize){
194 errorstream<<"GetTempPath failed, error = "<<GetLastError()<<std::endl;
197 return std::string(buf.begin(), buf.begin() + len);
202 #include <sys/types.h>
204 #include <sys/stat.h>
205 #include <sys/wait.h>
208 std::vector<DirListNode> GetDirListing(const std::string &pathstring)
210 std::vector<DirListNode> listing;
214 if((dp = opendir(pathstring.c_str())) == NULL) {
215 //infostream<<"Error("<<errno<<") opening "<<pathstring<<std::endl;
219 while ((dirp = readdir(dp)) != NULL) {
221 // Be very sure to not include '..' in the results, it will
222 // result in an epic failure when deleting stuff.
223 if(strcmp(dirp->d_name, ".") == 0 || strcmp(dirp->d_name, "..") == 0)
227 node.name = dirp->d_name;
229 int isdir = -1; // -1 means unknown
232 POSIX doesn't define d_type member of struct dirent and
233 certain filesystems on glibc/Linux will only return
234 DT_UNKNOWN for the d_type member.
236 Also we don't know whether symlinks are directories or not.
238 #ifdef _DIRENT_HAVE_D_TYPE
239 if(dirp->d_type != DT_UNKNOWN && dirp->d_type != DT_LNK)
240 isdir = (dirp->d_type == DT_DIR);
241 #endif /* _DIRENT_HAVE_D_TYPE */
244 Was d_type DT_UNKNOWN, DT_LNK or nonexistent?
249 if (stat((pathstring + "/" + node.name).c_str(), &statbuf))
251 isdir = ((statbuf.st_mode & S_IFDIR) == S_IFDIR);
254 listing.push_back(node);
261 bool CreateDir(const std::string &path)
263 int r = mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
270 // If already exists, return true
277 bool PathExists(const std::string &path)
280 return (stat(path.c_str(),&st) == 0);
283 bool IsPathAbsolute(const std::string &path)
285 return path[0] == '/';
288 bool IsDir(const std::string &path)
291 if(stat(path.c_str(), &statbuf))
292 return false; // Actually error; but certainly not a directory
293 return ((statbuf.st_mode & S_IFDIR) == S_IFDIR);
296 bool IsDirDelimiter(char c)
301 bool RecursiveDelete(const std::string &path)
304 Execute the 'rm' command directly, by fork() and execve()
307 infostream<<"Removing \""<<path<<"\""<<std::endl;
311 pid_t child_pid = fork();
316 char argv_data[3][10000];
317 strcpy(argv_data[0], "/bin/rm");
318 strcpy(argv_data[1], "-rf");
319 strncpy(argv_data[2], path.c_str(), 10000);
321 argv[0] = argv_data[0];
322 argv[1] = argv_data[1];
323 argv[2] = argv_data[2];
326 verbosestream<<"Executing '"<<argv[0]<<"' '"<<argv[1]<<"' '"
327 <<argv[2]<<"'"<<std::endl;
329 execv(argv[0], argv);
331 // Execv shouldn't return. Failed.
340 tpid = wait(&child_status);
341 //if(tpid != child_pid) process_terminated(tpid);
342 }while(tpid != child_pid);
343 return (child_status == 0);
347 bool DeleteSingleFileOrEmptyDirectory(const std::string &path)
350 bool did = (rmdir(path.c_str()) == 0);
352 errorstream<<"rmdir errno: "<<errno<<": "<<strerror(errno)
356 bool did = (unlink(path.c_str()) == 0);
358 errorstream<<"unlink errno: "<<errno<<": "<<strerror(errno)
364 std::string TempPath()
367 Should the environment variables TMPDIR, TMP and TEMP
368 and the macro P_tmpdir (if defined by stdio.h) be checked
369 before falling back on /tmp?
371 Probably not, because this function is intended to be
372 compatible with lua's os.tmpname which under the default
373 configuration hardcodes mkstemp("/tmp/lua_XXXXXX").
376 return DIR_DELIM "sdcard" DIR_DELIM PROJECT_NAME DIR_DELIM "tmp";
378 return DIR_DELIM "tmp";
384 void GetRecursiveSubPaths(const std::string &path, std::vector<std::string> &dst)
386 std::vector<DirListNode> content = GetDirListing(path);
387 for(unsigned int i=0; i<content.size(); i++){
388 const DirListNode &n = content[i];
389 std::string fullpath = path + DIR_DELIM + n.name;
390 dst.push_back(fullpath);
392 GetRecursiveSubPaths(fullpath, dst);
397 bool DeletePaths(const std::vector<std::string> &paths)
400 // Go backwards to succesfully delete the output of GetRecursiveSubPaths
401 for(int i=paths.size()-1; i>=0; i--){
402 const std::string &path = paths[i];
403 bool did = DeleteSingleFileOrEmptyDirectory(path);
405 errorstream<<"Failed to delete "<<path<<std::endl;
412 bool RecursiveDeleteContent(const std::string &path)
414 infostream<<"Removing content of \""<<path<<"\""<<std::endl;
415 std::vector<DirListNode> list = GetDirListing(path);
416 for(unsigned int i=0; i<list.size(); i++)
418 if(trim(list[i].name) == "." || trim(list[i].name) == "..")
420 std::string childpath = path + DIR_DELIM + list[i].name;
421 bool r = RecursiveDelete(childpath);
424 errorstream<<"Removing \""<<childpath<<"\" failed"<<std::endl;
431 bool CreateAllDirs(const std::string &path)
434 std::vector<std::string> tocreate;
435 std::string basepath = path;
436 while(!PathExists(basepath))
438 tocreate.push_back(basepath);
439 basepath = RemoveLastPathComponent(basepath);
443 for(int i=tocreate.size()-1;i>=0;i--)
444 if(!CreateDir(tocreate[i]))
449 bool CopyFileContents(const std::string &source, const std::string &target)
451 FILE *sourcefile = fopen(source.c_str(), "rb");
452 if(sourcefile == NULL){
453 errorstream<<source<<": can't open for reading: "
454 <<strerror(errno)<<std::endl;
458 FILE *targetfile = fopen(target.c_str(), "wb");
459 if(targetfile == NULL){
460 errorstream<<target<<": can't open for writing: "
461 <<strerror(errno)<<std::endl;
469 char readbuffer[BUFSIZ];
471 size_t readbytes = fread(readbuffer, 1,
472 sizeof(readbuffer), sourcefile);
474 if(ferror(sourcefile)){
475 errorstream<<source<<": IO error: "
476 <<strerror(errno)<<std::endl;
481 fwrite(readbuffer, 1, readbytes, targetfile);
483 if(feof(sourcefile) || ferror(sourcefile)){
484 // flush destination file to catch write errors
489 if(ferror(targetfile)){
490 errorstream<<target<<": IO error: "
491 <<strerror(errno)<<std::endl;
496 infostream<<"copied "<<total<<" bytes from "
497 <<source<<" to "<<target<<std::endl;
503 bool CopyDir(const std::string &source, const std::string &target)
505 if(PathExists(source)){
506 if(!PathExists(target)){
507 fs::CreateAllDirs(target);
510 std::vector<DirListNode> content = fs::GetDirListing(source);
512 for(unsigned int i=0; i < content.size(); i++){
513 std::string sourcechild = source + DIR_DELIM + content[i].name;
514 std::string targetchild = target + DIR_DELIM + content[i].name;
516 if(!fs::CopyDir(sourcechild, targetchild)){
521 if(!fs::CopyFileContents(sourcechild, targetchild)){
533 bool PathStartsWith(const std::string &path, const std::string &prefix)
535 size_t pathsize = path.size();
537 size_t prefixsize = prefix.size();
538 size_t prefixpos = 0;
540 bool delim1 = pathpos == pathsize
541 || IsDirDelimiter(path[pathpos]);
542 bool delim2 = prefixpos == prefixsize
543 || IsDirDelimiter(prefix[prefixpos]);
549 while(pathpos < pathsize &&
550 IsDirDelimiter(path[pathpos]))
552 while(prefixpos < prefixsize &&
553 IsDirDelimiter(prefix[prefixpos]))
555 if(prefixpos == prefixsize)
557 if(pathpos == pathsize)
563 char pathchar = path[pathpos+len];
564 char prefixchar = prefix[prefixpos+len];
565 if(FILESYS_CASE_INSENSITIVE){
566 pathchar = tolower(pathchar);
567 prefixchar = tolower(prefixchar);
569 if(pathchar != prefixchar)
572 } while(pathpos+len < pathsize
573 && !IsDirDelimiter(path[pathpos+len])
574 && prefixpos+len < prefixsize
576 prefix[prefixpos+len]));
583 std::string RemoveLastPathComponent(const std::string &path,
584 std::string *removed, int count)
589 size_t remaining = path.size();
591 for(int i = 0; i < count; ++i){
592 // strip a dir delimiter
593 while(remaining != 0 && IsDirDelimiter(path[remaining-1]))
595 // strip a path component
596 size_t component_end = remaining;
597 while(remaining != 0 && !IsDirDelimiter(path[remaining-1]))
599 size_t component_start = remaining;
600 // strip a dir delimiter
601 while(remaining != 0 && IsDirDelimiter(path[remaining-1]))
604 std::string component = path.substr(component_start,
605 component_end - component_start);
607 *removed = component + DIR_DELIM + *removed;
609 *removed = component;
612 return path.substr(0, remaining);
615 std::string RemoveRelativePathComponents(std::string path)
617 size_t pos = path.size();
618 size_t dotdot_count = 0;
620 size_t component_with_delim_end = pos;
621 // skip a dir delimiter
622 while(pos != 0 && IsDirDelimiter(path[pos-1]))
624 // strip a path component
625 size_t component_end = pos;
626 while(pos != 0 && !IsDirDelimiter(path[pos-1]))
628 size_t component_start = pos;
630 std::string component = path.substr(component_start,
631 component_end - component_start);
632 bool remove_this_component = false;
633 if(component == "."){
634 remove_this_component = true;
636 else if(component == ".."){
637 remove_this_component = true;
640 else if(dotdot_count != 0){
641 remove_this_component = true;
645 if(remove_this_component){
646 while(pos != 0 && IsDirDelimiter(path[pos-1]))
648 path = path.substr(0, pos) + DIR_DELIM +
649 path.substr(component_with_delim_end,
658 // remove trailing dir delimiters
660 while(pos != 0 && IsDirDelimiter(path[pos-1]))
662 return path.substr(0, pos);
665 std::string AbsolutePath(const std::string &path)
668 char *abs_path = _fullpath(NULL, path.c_str(), MAX_PATH);
670 char *abs_path = realpath(path.c_str(), NULL);
672 if (!abs_path) return "";
673 std::string abs_path_str(abs_path);
678 const char *GetFilenameFromPath(const char *path)
680 const char *filename = strrchr(path, DIR_DELIM_CHAR);
681 return filename ? filename + 1 : path;
684 bool safeWriteToFile(const std::string &path, const std::string &content)
686 std::string tmp_file = path + ".~mt";
688 // Write to a tmp file
689 std::ofstream os(tmp_file.c_str(), std::ios::binary);
696 remove(tmp_file.c_str());
701 remove(path.c_str());
702 if(rename(tmp_file.c_str(), path.c_str())) {
703 remove(tmp_file.c_str());