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);
381 GetRecursiveSubPaths(fullpath, dst);
386 bool DeletePaths(const std::vector<std::string> &paths)
389 // Go backwards to succesfully delete the output of GetRecursiveSubPaths
390 for(int i=paths.size()-1; i>=0; i--){
391 const std::string &path = paths[i];
392 bool did = DeleteSingleFileOrEmptyDirectory(path);
394 errorstream<<"Failed to delete "<<path<<std::endl;
401 bool RecursiveDeleteContent(std::string path)
403 infostream<<"Removing content of \""<<path<<"\""<<std::endl;
404 std::vector<DirListNode> list = GetDirListing(path);
405 for(unsigned int i=0; i<list.size(); i++)
407 if(trim(list[i].name) == "." || trim(list[i].name) == "..")
409 std::string childpath = path + DIR_DELIM + list[i].name;
410 bool r = RecursiveDelete(childpath);
413 errorstream<<"Removing \""<<childpath<<"\" failed"<<std::endl;
420 bool CreateAllDirs(std::string path)
423 std::vector<std::string> tocreate;
424 std::string basepath = path;
425 while(!PathExists(basepath))
427 tocreate.push_back(basepath);
428 basepath = RemoveLastPathComponent(basepath);
432 for(int i=tocreate.size()-1;i>=0;i--)
433 if(!CreateDir(tocreate[i]))
438 bool CopyFileContents(std::string source, std::string target)
440 FILE *sourcefile = fopen(source.c_str(), "rb");
441 if(sourcefile == NULL){
442 errorstream<<source<<": can't open for reading: "
443 <<strerror(errno)<<std::endl;
447 FILE *targetfile = fopen(target.c_str(), "wb");
448 if(targetfile == NULL){
449 errorstream<<target<<": can't open for writing: "
450 <<strerror(errno)<<std::endl;
458 char readbuffer[BUFSIZ];
460 size_t readbytes = fread(readbuffer, 1,
461 sizeof(readbuffer), sourcefile);
463 if(ferror(sourcefile)){
464 errorstream<<source<<": IO error: "
465 <<strerror(errno)<<std::endl;
470 fwrite(readbuffer, 1, readbytes, targetfile);
472 if(feof(sourcefile) || ferror(sourcefile)){
473 // flush destination file to catch write errors
478 if(ferror(targetfile)){
479 errorstream<<target<<": IO error: "
480 <<strerror(errno)<<std::endl;
485 infostream<<"copied "<<total<<" bytes from "
486 <<source<<" to "<<target<<std::endl;
492 bool CopyDir(std::string source, std::string target)
494 if(PathExists(source)){
495 if(!PathExists(target)){
496 fs::CreateAllDirs(target);
499 std::vector<DirListNode> content = fs::GetDirListing(source);
501 for(unsigned int i=0; i < content.size(); i++){
502 std::string sourcechild = source + DIR_DELIM + content[i].name;
503 std::string targetchild = target + DIR_DELIM + content[i].name;
505 if(!fs::CopyDir(sourcechild, targetchild)){
510 if(!fs::CopyFileContents(sourcechild, targetchild)){
522 bool PathStartsWith(std::string path, std::string prefix)
524 size_t pathsize = path.size();
526 size_t prefixsize = prefix.size();
527 size_t prefixpos = 0;
529 bool delim1 = pathpos == pathsize
530 || IsDirDelimiter(path[pathpos]);
531 bool delim2 = prefixpos == prefixsize
532 || IsDirDelimiter(prefix[prefixpos]);
538 while(pathpos < pathsize &&
539 IsDirDelimiter(path[pathpos]))
541 while(prefixpos < prefixsize &&
542 IsDirDelimiter(prefix[prefixpos]))
544 if(prefixpos == prefixsize)
546 if(pathpos == pathsize)
552 char pathchar = path[pathpos+len];
553 char prefixchar = prefix[prefixpos+len];
554 if(FILESYS_CASE_INSENSITIVE){
555 pathchar = tolower(pathchar);
556 prefixchar = tolower(prefixchar);
558 if(pathchar != prefixchar)
561 } while(pathpos+len < pathsize
562 && !IsDirDelimiter(path[pathpos+len])
563 && prefixpos+len < prefixsize
565 prefix[prefixpos+len]));
572 std::string RemoveLastPathComponent(std::string path,
573 std::string *removed, int count)
578 size_t remaining = path.size();
580 for(int i = 0; i < count; ++i){
581 // strip a dir delimiter
582 while(remaining != 0 && IsDirDelimiter(path[remaining-1]))
584 // strip a path component
585 size_t component_end = remaining;
586 while(remaining != 0 && !IsDirDelimiter(path[remaining-1]))
588 size_t component_start = remaining;
589 // strip a dir delimiter
590 while(remaining != 0 && IsDirDelimiter(path[remaining-1]))
593 std::string component = path.substr(component_start,
594 component_end - component_start);
596 *removed = component + DIR_DELIM + *removed;
598 *removed = component;
601 return path.substr(0, remaining);
604 std::string RemoveRelativePathComponents(std::string path)
606 size_t pos = path.size();
607 size_t dotdot_count = 0;
609 size_t component_with_delim_end = pos;
610 // skip a dir delimiter
611 while(pos != 0 && IsDirDelimiter(path[pos-1]))
613 // strip a path component
614 size_t component_end = pos;
615 while(pos != 0 && !IsDirDelimiter(path[pos-1]))
617 size_t component_start = pos;
619 std::string component = path.substr(component_start,
620 component_end - component_start);
621 bool remove_this_component = false;
622 if(component == "."){
623 remove_this_component = true;
625 else if(component == ".."){
626 remove_this_component = true;
629 else if(dotdot_count != 0){
630 remove_this_component = true;
634 if(remove_this_component){
635 while(pos != 0 && IsDirDelimiter(path[pos-1]))
637 path = path.substr(0, pos) + DIR_DELIM +
638 path.substr(component_with_delim_end,
647 // remove trailing dir delimiters
649 while(pos != 0 && IsDirDelimiter(path[pos-1]))
651 return path.substr(0, pos);
654 bool safeWriteToFile(const std::string &path, const std::string &content)
656 std::string tmp_file = path + ".~mt";
658 // Write to a tmp file
659 std::ofstream os(tmp_file.c_str(), std::ios::binary);
666 remove(tmp_file.c_str());
671 remove(path.c_str());
672 if(rename(tmp_file.c_str(), path.c_str())) {
673 remove(tmp_file.c_str());