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
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").
406 return DIR_DELIM "sdcard" DIR_DELIM PROJECT_NAME DIR_DELIM "tmp";
408 return DIR_DELIM "tmp";
414 void GetRecursiveSubPaths(std::string path, std::vector<std::string> &dst)
416 std::vector<DirListNode> content = GetDirListing(path);
417 for(unsigned int i=0; i<content.size(); i++){
418 const DirListNode &n = content[i];
419 std::string fullpath = path + DIR_DELIM + n.name;
420 dst.push_back(fullpath);
421 GetRecursiveSubPaths(fullpath, dst);
425 bool DeletePaths(const std::vector<std::string> &paths)
428 // Go backwards to succesfully delete the output of GetRecursiveSubPaths
429 for(int i=paths.size()-1; i>=0; i--){
430 const std::string &path = paths[i];
431 bool did = DeleteSingleFileOrEmptyDirectory(path);
433 errorstream<<"Failed to delete "<<path<<std::endl;
440 bool RecursiveDeleteContent(std::string path)
442 infostream<<"Removing content of \""<<path<<"\""<<std::endl;
443 std::vector<DirListNode> list = GetDirListing(path);
444 for(unsigned int i=0; i<list.size(); i++)
446 if(trim(list[i].name) == "." || trim(list[i].name) == "..")
448 std::string childpath = path + DIR_DELIM + list[i].name;
449 bool r = RecursiveDelete(childpath);
452 errorstream<<"Removing \""<<childpath<<"\" failed"<<std::endl;
459 bool CreateAllDirs(std::string path)
462 std::vector<std::string> tocreate;
463 std::string basepath = path;
464 while(!PathExists(basepath))
466 tocreate.push_back(basepath);
467 basepath = RemoveLastPathComponent(basepath);
471 for(int i=tocreate.size()-1;i>=0;i--)
472 if(!CreateDir(tocreate[i]))
477 bool CopyFileContents(std::string source, std::string target)
479 FILE *sourcefile = fopen(source.c_str(), "rb");
480 if(sourcefile == NULL){
481 errorstream<<source<<": can't open for reading: "
482 <<strerror(errno)<<std::endl;
486 FILE *targetfile = fopen(target.c_str(), "wb");
487 if(targetfile == NULL){
488 errorstream<<target<<": can't open for writing: "
489 <<strerror(errno)<<std::endl;
497 char readbuffer[BUFSIZ];
499 size_t readbytes = fread(readbuffer, 1,
500 sizeof(readbuffer), sourcefile);
502 if(ferror(sourcefile)){
503 errorstream<<source<<": IO error: "
504 <<strerror(errno)<<std::endl;
509 fwrite(readbuffer, 1, readbytes, targetfile);
511 if(feof(sourcefile) || ferror(sourcefile)){
512 // flush destination file to catch write errors
517 if(ferror(targetfile)){
518 errorstream<<target<<": IO error: "
519 <<strerror(errno)<<std::endl;
524 infostream<<"copied "<<total<<" bytes from "
525 <<source<<" to "<<target<<std::endl;
531 bool CopyDir(std::string source, std::string target)
533 if(PathExists(source)){
534 if(!PathExists(target)){
535 fs::CreateAllDirs(target);
538 std::vector<DirListNode> content = fs::GetDirListing(source);
540 for(unsigned int i=0; i < content.size(); i++){
541 std::string sourcechild = source + DIR_DELIM + content[i].name;
542 std::string targetchild = target + DIR_DELIM + content[i].name;
544 if(!fs::CopyDir(sourcechild, targetchild)){
549 if(!fs::CopyFileContents(sourcechild, targetchild)){
561 bool PathStartsWith(std::string path, std::string prefix)
563 size_t pathsize = path.size();
565 size_t prefixsize = prefix.size();
566 size_t prefixpos = 0;
568 bool delim1 = pathpos == pathsize
569 || IsDirDelimiter(path[pathpos]);
570 bool delim2 = prefixpos == prefixsize
571 || IsDirDelimiter(prefix[prefixpos]);
577 while(pathpos < pathsize &&
578 IsDirDelimiter(path[pathpos]))
580 while(prefixpos < prefixsize &&
581 IsDirDelimiter(prefix[prefixpos]))
583 if(prefixpos == prefixsize)
585 if(pathpos == pathsize)
591 char pathchar = path[pathpos+len];
592 char prefixchar = prefix[prefixpos+len];
593 if(FILESYS_CASE_INSENSITIVE){
594 pathchar = tolower(pathchar);
595 prefixchar = tolower(prefixchar);
597 if(pathchar != prefixchar)
600 } while(pathpos+len < pathsize
601 && !IsDirDelimiter(path[pathpos+len])
602 && prefixpos+len < prefixsize
604 prefix[prefixpos+len]));
611 std::string RemoveLastPathComponent(std::string path,
612 std::string *removed, int count)
617 size_t remaining = path.size();
619 for(int i = 0; i < count; ++i){
620 // strip a dir delimiter
621 while(remaining != 0 && IsDirDelimiter(path[remaining-1]))
623 // strip a path component
624 size_t component_end = remaining;
625 while(remaining != 0 && !IsDirDelimiter(path[remaining-1]))
627 size_t component_start = remaining;
628 // strip a dir delimiter
629 while(remaining != 0 && IsDirDelimiter(path[remaining-1]))
632 std::string component = path.substr(component_start,
633 component_end - component_start);
635 *removed = component + DIR_DELIM + *removed;
637 *removed = component;
640 return path.substr(0, remaining);
643 std::string RemoveRelativePathComponents(std::string path)
645 size_t pos = path.size();
646 size_t dotdot_count = 0;
648 size_t component_with_delim_end = pos;
649 // skip a dir delimiter
650 while(pos != 0 && IsDirDelimiter(path[pos-1]))
652 // strip a path component
653 size_t component_end = pos;
654 while(pos != 0 && !IsDirDelimiter(path[pos-1]))
656 size_t component_start = pos;
658 std::string component = path.substr(component_start,
659 component_end - component_start);
660 bool remove_this_component = false;
661 if(component == "."){
662 remove_this_component = true;
664 else if(component == ".."){
665 remove_this_component = true;
668 else if(dotdot_count != 0){
669 remove_this_component = true;
673 if(remove_this_component){
674 while(pos != 0 && IsDirDelimiter(path[pos-1]))
676 path = path.substr(0, pos) + DIR_DELIM +
677 path.substr(component_with_delim_end,
686 // remove trailing dir delimiters
688 while(pos != 0 && IsDirDelimiter(path[pos-1]))
690 return path.substr(0, pos);
693 bool safeWriteToFile(const std::string &path, const std::string &content)
695 std::string tmp_file = path + ".~mt";
697 // Write to a tmp file
698 std::ofstream os(tmp_file.c_str(), std::ios::binary);
705 remove(tmp_file.c_str());
710 remove(path.c_str());
711 if(rename(tmp_file.c_str(), path.c_str())) {
712 remove(tmp_file.c_str());