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.
33 #ifdef _WIN32 // WINDOWS
35 #define _WIN32_WINNT 0x0501
41 #define BUFSIZE MAX_PATH
43 std::vector<DirListNode> GetDirListing(std::string pathstring)
45 std::vector<DirListNode> listing;
47 WIN32_FIND_DATA FindFileData;
48 HANDLE hFind = INVALID_HANDLE_VALUE;
53 DirSpec = (LPTSTR) malloc (BUFSIZE);
57 errorstream<<"GetDirListing: Insufficient memory available"<<std::endl;
62 // Check that the input is not larger than allowed.
63 if (pathstring.size() > (BUFSIZE - 2))
65 errorstream<<"GetDirListing: Input directory is too large."<<std::endl;
70 //_tprintf (TEXT("Target directory is %s.\n"), pathstring.c_str());
72 sprintf(DirSpec, "%s", (pathstring + "\\*").c_str());
74 // Find the first file in the directory.
75 hFind = FindFirstFile(DirSpec, &FindFileData);
77 if (hFind == INVALID_HANDLE_VALUE)
85 // Be very sure to not include '..' in the results, it will
86 // result in an epic failure when deleting stuff.
89 node.name = FindFileData.cFileName;
90 node.dir = FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
91 if(node.name != "." && node.name != "..")
92 listing.push_back(node);
94 // List all the other files in the directory.
95 while (FindNextFile(hFind, &FindFileData) != 0)
98 node.name = FindFileData.cFileName;
99 node.dir = FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
100 if(node.name != "." && node.name != "..")
101 listing.push_back(node);
104 dwError = GetLastError();
106 if (dwError != ERROR_NO_MORE_FILES)
108 errorstream<<"GetDirListing: FindNextFile error. Error is "
109 <<dwError<<std::endl;
119 if(retval != 0) listing.clear();
121 //for(unsigned int i=0; i<listing.size(); i++){
122 // infostream<<listing[i].name<<(listing[i].dir?" (dir)":" (file)")<<std::endl;
128 bool CreateDir(std::string path)
130 bool r = CreateDirectory(path.c_str(), NULL);
133 if(GetLastError() == ERROR_ALREADY_EXISTS)
138 bool PathExists(std::string path)
140 return (GetFileAttributes(path.c_str()) != INVALID_FILE_ATTRIBUTES);
143 bool IsDir(std::string path)
145 DWORD attr = GetFileAttributes(path.c_str());
146 return (attr != INVALID_FILE_ATTRIBUTES &&
147 (attr & FILE_ATTRIBUTE_DIRECTORY));
150 bool IsDirDelimiter(char c)
152 return c == '/' || c == '\\';
155 bool RecursiveDelete(std::string path)
157 infostream<<"Recursively deleting \""<<path<<"\""<<std::endl;
159 DWORD attr = GetFileAttributes(path.c_str());
160 bool is_directory = (attr != INVALID_FILE_ATTRIBUTES &&
161 (attr & FILE_ATTRIBUTE_DIRECTORY));
164 infostream<<"RecursiveDelete: Deleting file "<<path<<std::endl;
165 //bool did = DeleteFile(path.c_str());
168 errorstream<<"RecursiveDelete: Failed to delete file "
175 infostream<<"RecursiveDelete: Deleting content of directory "
177 std::vector<DirListNode> content = GetDirListing(path);
178 for(int i=0; i<content.size(); i++){
179 const DirListNode &n = content[i];
180 std::string fullpath = path + DIR_DELIM + n.name;
181 bool did = RecursiveDelete(fullpath);
183 errorstream<<"RecursiveDelete: Failed to recurse to "
184 <<fullpath<<std::endl;
188 infostream<<"RecursiveDelete: Deleting directory "<<path<<std::endl;
189 //bool did = RemoveDirectory(path.c_str();
192 errorstream<<"Failed to recursively delete directory "
200 bool DeleteSingleFileOrEmptyDirectory(std::string path)
202 DWORD attr = GetFileAttributes(path.c_str());
203 bool is_directory = (attr != INVALID_FILE_ATTRIBUTES &&
204 (attr & FILE_ATTRIBUTE_DIRECTORY));
207 bool did = DeleteFile(path.c_str());
212 bool did = RemoveDirectory(path.c_str());
217 std::string TempPath()
219 DWORD bufsize = GetTempPath(0, "");
221 errorstream<<"GetTempPath failed, error = "<<GetLastError()<<std::endl;
224 std::vector<char> buf(bufsize);
225 DWORD len = GetTempPath(bufsize, &buf[0]);
226 if(len == 0 || len > bufsize){
227 errorstream<<"GetTempPath failed, error = "<<GetLastError()<<std::endl;
230 return std::string(buf.begin(), buf.begin() + len);
235 #include <sys/types.h>
237 #include <sys/stat.h>
238 #include <sys/wait.h>
241 std::vector<DirListNode> GetDirListing(std::string pathstring)
243 std::vector<DirListNode> listing;
247 if((dp = opendir(pathstring.c_str())) == NULL) {
248 //infostream<<"Error("<<errno<<") opening "<<pathstring<<std::endl;
252 while ((dirp = readdir(dp)) != NULL) {
254 // Be very sure to not include '..' in the results, it will
255 // result in an epic failure when deleting stuff.
256 if(dirp->d_name[0]!='.'){
258 node.name = dirp->d_name;
259 if(node.name == "." || node.name == "..")
262 int isdir = -1; // -1 means unknown
265 POSIX doesn't define d_type member of struct dirent and
266 certain filesystems on glibc/Linux will only return
267 DT_UNKNOWN for the d_type member.
269 Also we don't know whether symlinks are directories or not.
271 #ifdef _DIRENT_HAVE_D_TYPE
272 if(dirp->d_type != DT_UNKNOWN && dirp->d_type != DT_LNK)
273 isdir = (dirp->d_type == DT_DIR);
274 #endif /* _DIRENT_HAVE_D_TYPE */
277 Was d_type DT_UNKNOWN, DT_LNK or nonexistent?
283 if (stat((pathstring + "/" + node.name).c_str(), &statbuf))
285 isdir = ((statbuf.st_mode & S_IFDIR) == S_IFDIR);
288 listing.push_back(node);
296 bool CreateDir(std::string path)
298 int r = mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
305 // If already exists, return true
312 bool PathExists(std::string path)
315 return (stat(path.c_str(),&st) == 0);
318 bool IsDir(std::string path)
321 if(stat(path.c_str(), &statbuf))
322 return false; // Actually error; but certainly not a directory
323 return ((statbuf.st_mode & S_IFDIR) == S_IFDIR);
326 bool IsDirDelimiter(char c)
331 bool RecursiveDelete(std::string path)
334 Execute the 'rm' command directly, by fork() and execve()
337 infostream<<"Removing \""<<path<<"\""<<std::endl;
341 pid_t child_pid = fork();
346 char argv_data[3][10000];
347 strcpy(argv_data[0], "/bin/rm");
348 strcpy(argv_data[1], "-rf");
349 strncpy(argv_data[2], path.c_str(), 10000);
351 argv[0] = argv_data[0];
352 argv[1] = argv_data[1];
353 argv[2] = argv_data[2];
356 verbosestream<<"Executing '"<<argv[0]<<"' '"<<argv[1]<<"' '"
357 <<argv[2]<<"'"<<std::endl;
359 execv(argv[0], argv);
361 // Execv shouldn't return. Failed.
370 tpid = wait(&child_status);
371 //if(tpid != child_pid) process_terminated(tpid);
372 }while(tpid != child_pid);
373 return (child_status == 0);
377 bool DeleteSingleFileOrEmptyDirectory(std::string path)
380 bool did = (rmdir(path.c_str()) == 0);
382 errorstream<<"rmdir errno: "<<errno<<": "<<strerror(errno)
386 bool did = (unlink(path.c_str()) == 0);
388 errorstream<<"unlink errno: "<<errno<<": "<<strerror(errno)
394 std::string TempPath()
397 Should the environment variables TMPDIR, TMP and TEMP
398 and the macro P_tmpdir (if defined by stdio.h) be checked
399 before falling back on /tmp?
401 Probably not, because this function is intended to be
402 compatible with lua's os.tmpname which under the default
403 configuration hardcodes mkstemp("/tmp/lua_XXXXXX").
405 return std::string(DIR_DELIM) + "tmp";
410 void GetRecursiveSubPaths(std::string path, std::vector<std::string> &dst)
412 std::vector<DirListNode> content = GetDirListing(path);
413 for(unsigned int i=0; i<content.size(); i++){
414 const DirListNode &n = content[i];
415 std::string fullpath = path + DIR_DELIM + n.name;
416 dst.push_back(fullpath);
417 GetRecursiveSubPaths(fullpath, dst);
421 bool DeletePaths(const std::vector<std::string> &paths)
424 // Go backwards to succesfully delete the output of GetRecursiveSubPaths
425 for(int i=paths.size()-1; i>=0; i--){
426 const std::string &path = paths[i];
427 bool did = DeleteSingleFileOrEmptyDirectory(path);
429 errorstream<<"Failed to delete "<<path<<std::endl;
436 bool RecursiveDeleteContent(std::string path)
438 infostream<<"Removing content of \""<<path<<"\""<<std::endl;
439 std::vector<DirListNode> list = GetDirListing(path);
440 for(unsigned int i=0; i<list.size(); i++)
442 if(trim(list[i].name) == "." || trim(list[i].name) == "..")
444 std::string childpath = path + DIR_DELIM + list[i].name;
445 bool r = RecursiveDelete(childpath);
448 errorstream<<"Removing \""<<childpath<<"\" failed"<<std::endl;
455 bool CreateAllDirs(std::string path)
458 std::vector<std::string> tocreate;
459 std::string basepath = path;
460 while(!PathExists(basepath))
462 tocreate.push_back(basepath);
463 basepath = RemoveLastPathComponent(basepath);
467 for(int i=tocreate.size()-1;i>=0;i--)
468 if(!CreateDir(tocreate[i]))
473 bool CopyFileContents(std::string source, std::string target)
475 FILE *sourcefile = fopen(source.c_str(), "rb");
476 if(sourcefile == NULL){
477 errorstream<<source<<": can't open for reading: "
478 <<strerror(errno)<<std::endl;
482 FILE *targetfile = fopen(target.c_str(), "wb");
483 if(targetfile == NULL){
484 errorstream<<target<<": can't open for writing: "
485 <<strerror(errno)<<std::endl;
493 char readbuffer[BUFSIZ];
495 size_t readbytes = fread(readbuffer, 1,
496 sizeof(readbuffer), sourcefile);
498 if(ferror(sourcefile)){
499 errorstream<<source<<": IO error: "
500 <<strerror(errno)<<std::endl;
505 fwrite(readbuffer, 1, readbytes, targetfile);
507 if(feof(sourcefile) || ferror(sourcefile)){
508 // flush destination file to catch write errors
513 if(ferror(targetfile)){
514 errorstream<<target<<": IO error: "
515 <<strerror(errno)<<std::endl;
520 infostream<<"copied "<<total<<" bytes from "
521 <<source<<" to "<<target<<std::endl;
527 bool CopyDir(std::string source, std::string target)
529 if(PathExists(source)){
530 if(!PathExists(target)){
531 fs::CreateAllDirs(target);
534 std::vector<DirListNode> content = fs::GetDirListing(source);
536 for(unsigned int i=0; i < content.size(); i++){
537 std::string sourcechild = source + DIR_DELIM + content[i].name;
538 std::string targetchild = target + DIR_DELIM + content[i].name;
540 if(!fs::CopyDir(sourcechild, targetchild)){
545 if(!fs::CopyFileContents(sourcechild, targetchild)){
557 bool PathStartsWith(std::string path, std::string prefix)
559 size_t pathsize = path.size();
561 size_t prefixsize = prefix.size();
562 size_t prefixpos = 0;
564 bool delim1 = pathpos == pathsize
565 || IsDirDelimiter(path[pathpos]);
566 bool delim2 = prefixpos == prefixsize
567 || IsDirDelimiter(prefix[prefixpos]);
573 while(pathpos < pathsize &&
574 IsDirDelimiter(path[pathpos]))
576 while(prefixpos < prefixsize &&
577 IsDirDelimiter(prefix[prefixpos]))
579 if(prefixpos == prefixsize)
581 if(pathpos == pathsize)
587 char pathchar = path[pathpos+len];
588 char prefixchar = prefix[prefixpos+len];
589 if(FILESYS_CASE_INSENSITIVE){
590 pathchar = tolower(pathchar);
591 prefixchar = tolower(prefixchar);
593 if(pathchar != prefixchar)
596 } while(pathpos+len < pathsize
597 && !IsDirDelimiter(path[pathpos+len])
598 && prefixpos+len < prefixsize
600 prefix[prefixpos+len]));
607 std::string RemoveLastPathComponent(std::string path,
608 std::string *removed, int count)
613 size_t remaining = path.size();
615 for(int i = 0; i < count; ++i){
616 // strip a dir delimiter
617 while(remaining != 0 && IsDirDelimiter(path[remaining-1]))
619 // strip a path component
620 size_t component_end = remaining;
621 while(remaining != 0 && !IsDirDelimiter(path[remaining-1]))
623 size_t component_start = remaining;
624 // strip a dir delimiter
625 while(remaining != 0 && IsDirDelimiter(path[remaining-1]))
628 std::string component = path.substr(component_start,
629 component_end - component_start);
631 *removed = component + DIR_DELIM + *removed;
633 *removed = component;
636 return path.substr(0, remaining);
639 std::string RemoveRelativePathComponents(std::string path)
641 size_t pos = path.size();
642 size_t dotdot_count = 0;
644 size_t component_with_delim_end = pos;
645 // skip a dir delimiter
646 while(pos != 0 && IsDirDelimiter(path[pos-1]))
648 // strip a path component
649 size_t component_end = pos;
650 while(pos != 0 && !IsDirDelimiter(path[pos-1]))
652 size_t component_start = pos;
654 std::string component = path.substr(component_start,
655 component_end - component_start);
656 bool remove_this_component = false;
657 if(component == "."){
658 remove_this_component = true;
660 else if(component == ".."){
661 remove_this_component = true;
664 else if(dotdot_count != 0){
665 remove_this_component = true;
669 if(remove_this_component){
670 while(pos != 0 && IsDirDelimiter(path[pos-1]))
672 path = path.substr(0, pos) + DIR_DELIM +
673 path.substr(component_with_delim_end,
682 // remove trailing dir delimiters
684 while(pos != 0 && IsDirDelimiter(path[pos-1]))
686 return path.substr(0, pos);
689 bool safeWriteToFile(const std::string &path, const std::string &content)
691 std::string tmp_file = path + ".~mt";
693 // Write to a tmp file
694 std::ofstream os(tmp_file.c_str(), std::ios::binary);
705 remove(path.c_str());
706 return (rename(tmp_file.c_str(), path.c_str()) == 0);
708 return (rename(tmp_file.c_str(), path.c_str()) == 0);