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
38 std::vector<DirListNode> GetDirListing(std::string pathstring)
40 std::vector<DirListNode> listing;
42 WIN32_FIND_DATA FindFileData;
43 HANDLE hFind = INVALID_HANDLE_VALUE;
46 std::string dirSpec = pathstring + "\\*";
48 // Find the first file in the directory.
49 hFind = FindFirstFile(dirSpec.c_str(), &FindFileData);
51 if (hFind == INVALID_HANDLE_VALUE) {
52 dwError = GetLastError();
53 if (dwError != ERROR_FILE_NOT_FOUND && dwError != ERROR_PATH_NOT_FOUND) {
54 errorstream << "GetDirListing: FindFirstFile error."
55 << " Error is " << dwError << std::endl;
59 // Be very sure to not include '..' in the results, it will
60 // result in an epic failure when deleting stuff.
63 node.name = FindFileData.cFileName;
64 node.dir = FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
65 if (node.name != "." && node.name != "..")
66 listing.push_back(node);
68 // List all the other files in the directory.
69 while (FindNextFile(hFind, &FindFileData) != 0) {
71 node.name = FindFileData.cFileName;
72 node.dir = FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
73 if(node.name != "." && node.name != "..")
74 listing.push_back(node);
77 dwError = GetLastError();
79 if (dwError != ERROR_NO_MORE_FILES) {
80 errorstream << "GetDirListing: FindNextFile error."
81 << " Error is " << dwError << std::endl;
89 bool CreateDir(std::string path)
91 bool r = CreateDirectory(path.c_str(), NULL);
94 if(GetLastError() == ERROR_ALREADY_EXISTS)
99 bool PathExists(std::string path)
101 return (GetFileAttributes(path.c_str()) != INVALID_FILE_ATTRIBUTES);
104 bool IsDir(std::string path)
106 DWORD attr = GetFileAttributes(path.c_str());
107 return (attr != INVALID_FILE_ATTRIBUTES &&
108 (attr & FILE_ATTRIBUTE_DIRECTORY));
111 bool IsDirDelimiter(char c)
113 return c == '/' || c == '\\';
116 bool RecursiveDelete(std::string path)
118 infostream<<"Recursively deleting \""<<path<<"\""<<std::endl;
120 DWORD attr = GetFileAttributes(path.c_str());
121 bool is_directory = (attr != INVALID_FILE_ATTRIBUTES &&
122 (attr & FILE_ATTRIBUTE_DIRECTORY));
125 infostream<<"RecursiveDelete: Deleting file "<<path<<std::endl;
126 //bool did = DeleteFile(path.c_str());
129 errorstream<<"RecursiveDelete: Failed to delete file "
136 infostream<<"RecursiveDelete: Deleting content of directory "
138 std::vector<DirListNode> content = GetDirListing(path);
139 for(int i=0; i<content.size(); i++){
140 const DirListNode &n = content[i];
141 std::string fullpath = path + DIR_DELIM + n.name;
142 bool did = RecursiveDelete(fullpath);
144 errorstream<<"RecursiveDelete: Failed to recurse to "
145 <<fullpath<<std::endl;
149 infostream<<"RecursiveDelete: Deleting directory "<<path<<std::endl;
150 //bool did = RemoveDirectory(path.c_str();
153 errorstream<<"Failed to recursively delete directory "
161 bool DeleteSingleFileOrEmptyDirectory(std::string path)
163 DWORD attr = GetFileAttributes(path.c_str());
164 bool is_directory = (attr != INVALID_FILE_ATTRIBUTES &&
165 (attr & FILE_ATTRIBUTE_DIRECTORY));
168 bool did = DeleteFile(path.c_str());
173 bool did = RemoveDirectory(path.c_str());
178 std::string TempPath()
180 DWORD bufsize = GetTempPath(0, "");
182 errorstream<<"GetTempPath failed, error = "<<GetLastError()<<std::endl;
185 std::vector<char> buf(bufsize);
186 DWORD len = GetTempPath(bufsize, &buf[0]);
187 if(len == 0 || len > bufsize){
188 errorstream<<"GetTempPath failed, error = "<<GetLastError()<<std::endl;
191 return std::string(buf.begin(), buf.begin() + len);
196 #include <sys/types.h>
198 #include <sys/stat.h>
199 #include <sys/wait.h>
202 std::vector<DirListNode> GetDirListing(std::string pathstring)
204 std::vector<DirListNode> listing;
208 if((dp = opendir(pathstring.c_str())) == NULL) {
209 //infostream<<"Error("<<errno<<") opening "<<pathstring<<std::endl;
213 while ((dirp = readdir(dp)) != NULL) {
215 // Be very sure to not include '..' in the results, it will
216 // result in an epic failure when deleting stuff.
217 if(strcmp(dirp->d_name, ".") == 0 || strcmp(dirp->d_name, "..") == 0)
221 node.name = dirp->d_name;
223 int isdir = -1; // -1 means unknown
226 POSIX doesn't define d_type member of struct dirent and
227 certain filesystems on glibc/Linux will only return
228 DT_UNKNOWN for the d_type member.
230 Also we don't know whether symlinks are directories or not.
232 #ifdef _DIRENT_HAVE_D_TYPE
233 if(dirp->d_type != DT_UNKNOWN && dirp->d_type != DT_LNK)
234 isdir = (dirp->d_type == DT_DIR);
235 #endif /* _DIRENT_HAVE_D_TYPE */
238 Was d_type DT_UNKNOWN, DT_LNK or nonexistent?
243 if (stat((pathstring + "/" + node.name).c_str(), &statbuf))
245 isdir = ((statbuf.st_mode & S_IFDIR) == S_IFDIR);
248 listing.push_back(node);
255 bool CreateDir(std::string path)
257 int r = mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
264 // If already exists, return true
271 bool PathExists(std::string path)
274 return (stat(path.c_str(),&st) == 0);
277 bool IsDir(std::string path)
280 if(stat(path.c_str(), &statbuf))
281 return false; // Actually error; but certainly not a directory
282 return ((statbuf.st_mode & S_IFDIR) == S_IFDIR);
285 bool IsDirDelimiter(char c)
290 bool RecursiveDelete(std::string path)
293 Execute the 'rm' command directly, by fork() and execve()
296 infostream<<"Removing \""<<path<<"\""<<std::endl;
300 pid_t child_pid = fork();
305 char argv_data[3][10000];
306 strcpy(argv_data[0], "/bin/rm");
307 strcpy(argv_data[1], "-rf");
308 strncpy(argv_data[2], path.c_str(), 10000);
310 argv[0] = argv_data[0];
311 argv[1] = argv_data[1];
312 argv[2] = argv_data[2];
315 verbosestream<<"Executing '"<<argv[0]<<"' '"<<argv[1]<<"' '"
316 <<argv[2]<<"'"<<std::endl;
318 execv(argv[0], argv);
320 // Execv shouldn't return. Failed.
329 tpid = wait(&child_status);
330 //if(tpid != child_pid) process_terminated(tpid);
331 }while(tpid != child_pid);
332 return (child_status == 0);
336 bool DeleteSingleFileOrEmptyDirectory(std::string path)
339 bool did = (rmdir(path.c_str()) == 0);
341 errorstream<<"rmdir errno: "<<errno<<": "<<strerror(errno)
345 bool did = (unlink(path.c_str()) == 0);
347 errorstream<<"unlink errno: "<<errno<<": "<<strerror(errno)
353 std::string TempPath()
356 Should the environment variables TMPDIR, TMP and TEMP
357 and the macro P_tmpdir (if defined by stdio.h) be checked
358 before falling back on /tmp?
360 Probably not, because this function is intended to be
361 compatible with lua's os.tmpname which under the default
362 configuration hardcodes mkstemp("/tmp/lua_XXXXXX").
365 return DIR_DELIM "sdcard" DIR_DELIM PROJECT_NAME DIR_DELIM "tmp";
367 return DIR_DELIM "tmp";
373 void GetRecursiveSubPaths(std::string path, std::vector<std::string> &dst)
375 std::vector<DirListNode> content = GetDirListing(path);
376 for(unsigned int i=0; i<content.size(); i++){
377 const DirListNode &n = content[i];
378 std::string fullpath = path + DIR_DELIM + n.name;
379 dst.push_back(fullpath);
380 GetRecursiveSubPaths(fullpath, dst);
384 bool DeletePaths(const std::vector<std::string> &paths)
387 // Go backwards to succesfully delete the output of GetRecursiveSubPaths
388 for(int i=paths.size()-1; i>=0; i--){
389 const std::string &path = paths[i];
390 bool did = DeleteSingleFileOrEmptyDirectory(path);
392 errorstream<<"Failed to delete "<<path<<std::endl;
399 bool RecursiveDeleteContent(std::string path)
401 infostream<<"Removing content of \""<<path<<"\""<<std::endl;
402 std::vector<DirListNode> list = GetDirListing(path);
403 for(unsigned int i=0; i<list.size(); i++)
405 if(trim(list[i].name) == "." || trim(list[i].name) == "..")
407 std::string childpath = path + DIR_DELIM + list[i].name;
408 bool r = RecursiveDelete(childpath);
411 errorstream<<"Removing \""<<childpath<<"\" failed"<<std::endl;
418 bool CreateAllDirs(std::string path)
421 std::vector<std::string> tocreate;
422 std::string basepath = path;
423 while(!PathExists(basepath))
425 tocreate.push_back(basepath);
426 basepath = RemoveLastPathComponent(basepath);
430 for(int i=tocreate.size()-1;i>=0;i--)
431 if(!CreateDir(tocreate[i]))
436 bool CopyFileContents(std::string source, std::string target)
438 FILE *sourcefile = fopen(source.c_str(), "rb");
439 if(sourcefile == NULL){
440 errorstream<<source<<": can't open for reading: "
441 <<strerror(errno)<<std::endl;
445 FILE *targetfile = fopen(target.c_str(), "wb");
446 if(targetfile == NULL){
447 errorstream<<target<<": can't open for writing: "
448 <<strerror(errno)<<std::endl;
456 char readbuffer[BUFSIZ];
458 size_t readbytes = fread(readbuffer, 1,
459 sizeof(readbuffer), sourcefile);
461 if(ferror(sourcefile)){
462 errorstream<<source<<": IO error: "
463 <<strerror(errno)<<std::endl;
468 fwrite(readbuffer, 1, readbytes, targetfile);
470 if(feof(sourcefile) || ferror(sourcefile)){
471 // flush destination file to catch write errors
476 if(ferror(targetfile)){
477 errorstream<<target<<": IO error: "
478 <<strerror(errno)<<std::endl;
483 infostream<<"copied "<<total<<" bytes from "
484 <<source<<" to "<<target<<std::endl;
490 bool CopyDir(std::string source, std::string target)
492 if(PathExists(source)){
493 if(!PathExists(target)){
494 fs::CreateAllDirs(target);
497 std::vector<DirListNode> content = fs::GetDirListing(source);
499 for(unsigned int i=0; i < content.size(); i++){
500 std::string sourcechild = source + DIR_DELIM + content[i].name;
501 std::string targetchild = target + DIR_DELIM + content[i].name;
503 if(!fs::CopyDir(sourcechild, targetchild)){
508 if(!fs::CopyFileContents(sourcechild, targetchild)){
520 bool PathStartsWith(std::string path, std::string prefix)
522 size_t pathsize = path.size();
524 size_t prefixsize = prefix.size();
525 size_t prefixpos = 0;
527 bool delim1 = pathpos == pathsize
528 || IsDirDelimiter(path[pathpos]);
529 bool delim2 = prefixpos == prefixsize
530 || IsDirDelimiter(prefix[prefixpos]);
536 while(pathpos < pathsize &&
537 IsDirDelimiter(path[pathpos]))
539 while(prefixpos < prefixsize &&
540 IsDirDelimiter(prefix[prefixpos]))
542 if(prefixpos == prefixsize)
544 if(pathpos == pathsize)
550 char pathchar = path[pathpos+len];
551 char prefixchar = prefix[prefixpos+len];
552 if(FILESYS_CASE_INSENSITIVE){
553 pathchar = tolower(pathchar);
554 prefixchar = tolower(prefixchar);
556 if(pathchar != prefixchar)
559 } while(pathpos+len < pathsize
560 && !IsDirDelimiter(path[pathpos+len])
561 && prefixpos+len < prefixsize
563 prefix[prefixpos+len]));
570 std::string RemoveLastPathComponent(std::string path,
571 std::string *removed, int count)
576 size_t remaining = path.size();
578 for(int i = 0; i < count; ++i){
579 // strip a dir delimiter
580 while(remaining != 0 && IsDirDelimiter(path[remaining-1]))
582 // strip a path component
583 size_t component_end = remaining;
584 while(remaining != 0 && !IsDirDelimiter(path[remaining-1]))
586 size_t component_start = remaining;
587 // strip a dir delimiter
588 while(remaining != 0 && IsDirDelimiter(path[remaining-1]))
591 std::string component = path.substr(component_start,
592 component_end - component_start);
594 *removed = component + DIR_DELIM + *removed;
596 *removed = component;
599 return path.substr(0, remaining);
602 std::string RemoveRelativePathComponents(std::string path)
604 size_t pos = path.size();
605 size_t dotdot_count = 0;
607 size_t component_with_delim_end = pos;
608 // skip a dir delimiter
609 while(pos != 0 && IsDirDelimiter(path[pos-1]))
611 // strip a path component
612 size_t component_end = pos;
613 while(pos != 0 && !IsDirDelimiter(path[pos-1]))
615 size_t component_start = pos;
617 std::string component = path.substr(component_start,
618 component_end - component_start);
619 bool remove_this_component = false;
620 if(component == "."){
621 remove_this_component = true;
623 else if(component == ".."){
624 remove_this_component = true;
627 else if(dotdot_count != 0){
628 remove_this_component = true;
632 if(remove_this_component){
633 while(pos != 0 && IsDirDelimiter(path[pos-1]))
635 path = path.substr(0, pos) + DIR_DELIM +
636 path.substr(component_with_delim_end,
645 // remove trailing dir delimiters
647 while(pos != 0 && IsDirDelimiter(path[pos-1]))
649 return path.substr(0, pos);
652 bool safeWriteToFile(const std::string &path, const std::string &content)
654 std::string tmp_file = path + ".~mt";
656 // Write to a tmp file
657 std::ofstream os(tmp_file.c_str(), std::ios::binary);
664 remove(tmp_file.c_str());
669 remove(path.c_str());
670 if(rename(tmp_file.c_str(), path.c_str())) {
671 remove(tmp_file.c_str());