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"
32 #ifdef _WIN32 // WINDOWS
34 #define _WIN32_WINNT 0x0501
40 #define BUFSIZE MAX_PATH
42 std::vector<DirListNode> GetDirListing(std::string pathstring)
44 std::vector<DirListNode> listing;
46 WIN32_FIND_DATA FindFileData;
47 HANDLE hFind = INVALID_HANDLE_VALUE;
52 DirSpec = (LPTSTR) malloc (BUFSIZE);
56 errorstream<<"GetDirListing: Insufficient memory available"<<std::endl;
61 // Check that the input is not larger than allowed.
62 if (pathstring.size() > (BUFSIZE - 2))
64 errorstream<<"GetDirListing: Input directory is too large."<<std::endl;
69 //_tprintf (TEXT("Target directory is %s.\n"), pathstring.c_str());
71 sprintf(DirSpec, "%s", (pathstring + "\\*").c_str());
73 // Find the first file in the directory.
74 hFind = FindFirstFile(DirSpec, &FindFileData);
76 if (hFind == INVALID_HANDLE_VALUE)
84 // Be very sure to not include '..' in the results, it will
85 // result in an epic failure when deleting stuff.
88 node.name = FindFileData.cFileName;
89 node.dir = FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
90 if(node.name != "." && node.name != "..")
91 listing.push_back(node);
93 // List all the other files in the directory.
94 while (FindNextFile(hFind, &FindFileData) != 0)
97 node.name = FindFileData.cFileName;
98 node.dir = FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
99 if(node.name != "." && node.name != "..")
100 listing.push_back(node);
103 dwError = GetLastError();
105 if (dwError != ERROR_NO_MORE_FILES)
107 errorstream<<"GetDirListing: FindNextFile error. Error is "
108 <<dwError<<std::endl;
118 if(retval != 0) listing.clear();
120 //for(unsigned int i=0; i<listing.size(); i++){
121 // infostream<<listing[i].name<<(listing[i].dir?" (dir)":" (file)")<<std::endl;
127 bool CreateDir(std::string path)
129 bool r = CreateDirectory(path.c_str(), NULL);
132 if(GetLastError() == ERROR_ALREADY_EXISTS)
137 bool PathExists(std::string path)
139 return (GetFileAttributes(path.c_str()) != INVALID_FILE_ATTRIBUTES);
142 bool IsDir(std::string path)
144 DWORD attr = GetFileAttributes(path.c_str());
145 return (attr != INVALID_FILE_ATTRIBUTES &&
146 (attr & FILE_ATTRIBUTE_DIRECTORY));
149 bool IsDirDelimiter(char c)
151 return c == '/' || c == '\\';
154 bool RecursiveDelete(std::string path)
156 infostream<<"Recursively deleting \""<<path<<"\""<<std::endl;
158 DWORD attr = GetFileAttributes(path.c_str());
159 bool is_directory = (attr != INVALID_FILE_ATTRIBUTES &&
160 (attr & FILE_ATTRIBUTE_DIRECTORY));
163 infostream<<"RecursiveDelete: Deleting file "<<path<<std::endl;
164 //bool did = DeleteFile(path.c_str());
167 errorstream<<"RecursiveDelete: Failed to delete file "
174 infostream<<"RecursiveDelete: Deleting content of directory "
176 std::vector<DirListNode> content = GetDirListing(path);
177 for(int i=0; i<content.size(); i++){
178 const DirListNode &n = content[i];
179 std::string fullpath = path + DIR_DELIM + n.name;
180 bool did = RecursiveDelete(fullpath);
182 errorstream<<"RecursiveDelete: Failed to recurse to "
183 <<fullpath<<std::endl;
187 infostream<<"RecursiveDelete: Deleting directory "<<path<<std::endl;
188 //bool did = RemoveDirectory(path.c_str();
191 errorstream<<"Failed to recursively delete directory "
199 bool DeleteSingleFileOrEmptyDirectory(std::string path)
201 DWORD attr = GetFileAttributes(path.c_str());
202 bool is_directory = (attr != INVALID_FILE_ATTRIBUTES &&
203 (attr & FILE_ATTRIBUTE_DIRECTORY));
206 bool did = DeleteFile(path.c_str());
211 bool did = RemoveDirectory(path.c_str());
216 std::string TempPath()
218 DWORD bufsize = GetTempPath(0, "");
220 errorstream<<"GetTempPath failed, error = "<<GetLastError()<<std::endl;
223 std::vector<char> buf(bufsize);
224 DWORD len = GetTempPath(bufsize, &buf[0]);
225 if(len == 0 || len > bufsize){
226 errorstream<<"GetTempPath failed, error = "<<GetLastError()<<std::endl;
229 return std::string(buf.begin(), buf.begin() + len);
234 #include <sys/types.h>
236 #include <sys/stat.h>
237 #include <sys/wait.h>
240 std::vector<DirListNode> GetDirListing(std::string pathstring)
242 std::vector<DirListNode> listing;
246 if((dp = opendir(pathstring.c_str())) == NULL) {
247 //infostream<<"Error("<<errno<<") opening "<<pathstring<<std::endl;
251 while ((dirp = readdir(dp)) != NULL) {
253 // Be very sure to not include '..' in the results, it will
254 // result in an epic failure when deleting stuff.
255 if(dirp->d_name[0]!='.'){
257 node.name = dirp->d_name;
258 if(node.name == "." || node.name == "..")
261 int isdir = -1; // -1 means unknown
264 POSIX doesn't define d_type member of struct dirent and
265 certain filesystems on glibc/Linux will only return
266 DT_UNKNOWN for the d_type member.
268 Also we don't know whether symlinks are directories or not.
270 #ifdef _DIRENT_HAVE_D_TYPE
271 if(dirp->d_type != DT_UNKNOWN && dirp->d_type != DT_LNK)
272 isdir = (dirp->d_type == DT_DIR);
273 #endif /* _DIRENT_HAVE_D_TYPE */
276 Was d_type DT_UNKNOWN, DT_LNK or nonexistent?
282 if (stat((pathstring + "/" + node.name).c_str(), &statbuf))
284 isdir = ((statbuf.st_mode & S_IFDIR) == S_IFDIR);
287 listing.push_back(node);
295 bool CreateDir(std::string path)
297 int r = mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
304 // If already exists, return true
311 bool PathExists(std::string path)
314 return (stat(path.c_str(),&st) == 0);
317 bool IsDir(std::string path)
320 if(stat(path.c_str(), &statbuf))
321 return false; // Actually error; but certainly not a directory
322 return ((statbuf.st_mode & S_IFDIR) == S_IFDIR);
325 bool IsDirDelimiter(char c)
330 bool RecursiveDelete(std::string path)
333 Execute the 'rm' command directly, by fork() and execve()
336 infostream<<"Removing \""<<path<<"\""<<std::endl;
340 pid_t child_pid = fork();
345 char argv_data[3][10000];
346 strcpy(argv_data[0], "/bin/rm");
347 strcpy(argv_data[1], "-rf");
348 strncpy(argv_data[2], path.c_str(), 10000);
350 argv[0] = argv_data[0];
351 argv[1] = argv_data[1];
352 argv[2] = argv_data[2];
355 verbosestream<<"Executing '"<<argv[0]<<"' '"<<argv[1]<<"' '"
356 <<argv[2]<<"'"<<std::endl;
358 execv(argv[0], argv);
360 // Execv shouldn't return. Failed.
369 tpid = wait(&child_status);
370 //if(tpid != child_pid) process_terminated(tpid);
371 }while(tpid != child_pid);
372 return (child_status == 0);
376 bool DeleteSingleFileOrEmptyDirectory(std::string path)
379 bool did = (rmdir(path.c_str()) == 0);
381 errorstream<<"rmdir errno: "<<errno<<": "<<strerror(errno)
385 bool did = (unlink(path.c_str()) == 0);
387 errorstream<<"unlink errno: "<<errno<<": "<<strerror(errno)
393 std::string TempPath()
396 Should the environment variables TMPDIR, TMP and TEMP
397 and the macro P_tmpdir (if defined by stdio.h) be checked
398 before falling back on /tmp?
400 Probably not, because this function is intended to be
401 compatible with lua's os.tmpname which under the default
402 configuration hardcodes mkstemp("/tmp/lua_XXXXXX").
404 return std::string(DIR_DELIM) + "tmp";
409 void GetRecursiveSubPaths(std::string path, std::vector<std::string> &dst)
411 std::vector<DirListNode> content = GetDirListing(path);
412 for(unsigned int i=0; i<content.size(); i++){
413 const DirListNode &n = content[i];
414 std::string fullpath = path + DIR_DELIM + n.name;
415 dst.push_back(fullpath);
416 GetRecursiveSubPaths(fullpath, dst);
420 bool DeletePaths(const std::vector<std::string> &paths)
423 // Go backwards to succesfully delete the output of GetRecursiveSubPaths
424 for(int i=paths.size()-1; i>=0; i--){
425 const std::string &path = paths[i];
426 bool did = DeleteSingleFileOrEmptyDirectory(path);
428 errorstream<<"Failed to delete "<<path<<std::endl;
435 bool RecursiveDeleteContent(std::string path)
437 infostream<<"Removing content of \""<<path<<"\""<<std::endl;
438 std::vector<DirListNode> list = GetDirListing(path);
439 for(unsigned int i=0; i<list.size(); i++)
441 if(trim(list[i].name) == "." || trim(list[i].name) == "..")
443 std::string childpath = path + DIR_DELIM + list[i].name;
444 bool r = RecursiveDelete(childpath);
447 errorstream<<"Removing \""<<childpath<<"\" failed"<<std::endl;
454 bool CreateAllDirs(std::string path)
457 std::vector<std::string> tocreate;
458 std::string basepath = path;
459 while(!PathExists(basepath))
461 tocreate.push_back(basepath);
462 basepath = RemoveLastPathComponent(basepath);
466 for(int i=tocreate.size()-1;i>=0;i--)
467 if(!CreateDir(tocreate[i]))
472 bool CopyFileContents(std::string source, std::string target)
474 FILE *sourcefile = fopen(source.c_str(), "rb");
475 if(sourcefile == NULL){
476 errorstream<<source<<": can't open for reading: "
477 <<strerror(errno)<<std::endl;
481 FILE *targetfile = fopen(target.c_str(), "wb");
482 if(targetfile == NULL){
483 errorstream<<target<<": can't open for writing: "
484 <<strerror(errno)<<std::endl;
492 char readbuffer[BUFSIZ];
494 size_t readbytes = fread(readbuffer, 1,
495 sizeof(readbuffer), sourcefile);
497 if(ferror(sourcefile)){
498 errorstream<<source<<": IO error: "
499 <<strerror(errno)<<std::endl;
504 fwrite(readbuffer, 1, readbytes, targetfile);
506 if(feof(sourcefile) || ferror(sourcefile)){
507 // flush destination file to catch write errors
512 if(ferror(targetfile)){
513 errorstream<<target<<": IO error: "
514 <<strerror(errno)<<std::endl;
519 infostream<<"copied "<<total<<" bytes from "
520 <<source<<" to "<<target<<std::endl;
526 bool CopyDir(std::string source, std::string target)
528 if(PathExists(source)){
529 if(!PathExists(target)){
530 fs::CreateAllDirs(target);
533 std::vector<DirListNode> content = fs::GetDirListing(source);
535 for(unsigned int i=0; i < content.size(); i++){
536 std::string sourcechild = source + DIR_DELIM + content[i].name;
537 std::string targetchild = target + DIR_DELIM + content[i].name;
539 if(!fs::CopyDir(sourcechild, targetchild)){
544 if(!fs::CopyFileContents(sourcechild, targetchild)){
556 bool PathStartsWith(std::string path, std::string prefix)
558 size_t pathsize = path.size();
560 size_t prefixsize = prefix.size();
561 size_t prefixpos = 0;
563 bool delim1 = pathpos == pathsize
564 || IsDirDelimiter(path[pathpos]);
565 bool delim2 = prefixpos == prefixsize
566 || IsDirDelimiter(prefix[prefixpos]);
572 while(pathpos < pathsize &&
573 IsDirDelimiter(path[pathpos]))
575 while(prefixpos < prefixsize &&
576 IsDirDelimiter(prefix[prefixpos]))
578 if(prefixpos == prefixsize)
580 if(pathpos == pathsize)
586 char pathchar = path[pathpos+len];
587 char prefixchar = prefix[prefixpos+len];
588 if(FILESYS_CASE_INSENSITIVE){
589 pathchar = tolower(pathchar);
590 prefixchar = tolower(prefixchar);
592 if(pathchar != prefixchar)
595 } while(pathpos+len < pathsize
596 && !IsDirDelimiter(path[pathpos+len])
597 && prefixpos+len < prefixsize
599 prefix[prefixpos+len]));
606 std::string RemoveLastPathComponent(std::string path,
607 std::string *removed, int count)
612 size_t remaining = path.size();
614 for(int i = 0; i < count; ++i){
615 // strip a dir delimiter
616 while(remaining != 0 && IsDirDelimiter(path[remaining-1]))
618 // strip a path component
619 size_t component_end = remaining;
620 while(remaining != 0 && !IsDirDelimiter(path[remaining-1]))
622 size_t component_start = remaining;
623 // strip a dir delimiter
624 while(remaining != 0 && IsDirDelimiter(path[remaining-1]))
627 std::string component = path.substr(component_start,
628 component_end - component_start);
630 *removed = component + DIR_DELIM + *removed;
632 *removed = component;
635 return path.substr(0, remaining);
638 std::string RemoveRelativePathComponents(std::string path)
640 size_t pos = path.size();
641 size_t dotdot_count = 0;
643 size_t component_with_delim_end = pos;
644 // skip a dir delimiter
645 while(pos != 0 && IsDirDelimiter(path[pos-1]))
647 // strip a path component
648 size_t component_end = pos;
649 while(pos != 0 && !IsDirDelimiter(path[pos-1]))
651 size_t component_start = pos;
653 std::string component = path.substr(component_start,
654 component_end - component_start);
655 bool remove_this_component = false;
656 if(component == "."){
657 remove_this_component = true;
659 else if(component == ".."){
660 remove_this_component = true;
663 else if(dotdot_count != 0){
664 remove_this_component = true;
668 if(remove_this_component){
669 while(pos != 0 && IsDirDelimiter(path[pos-1]))
671 path = path.substr(0, pos) + DIR_DELIM +
672 path.substr(component_with_delim_end,
681 // remove trailing dir delimiters
683 while(pos != 0 && IsDirDelimiter(path[pos-1]))
685 return path.substr(0, pos);
688 bool safeWriteToFile(const std::string &path, const std::string &content)
690 std::string tmp_file = path + ".~mt";
692 // Write to a tmp file
693 std::ofstream os(tmp_file.c_str(), std::ios::binary);
704 remove(path.c_str());
705 return (rename(tmp_file.c_str(), path.c_str()) == 0);
707 return (rename(tmp_file.c_str(), path.c_str()) == 0);