xref: /haiku/src/apps/haikudepot/util/StorageUtils.cpp (revision aa3083e086e5a929c061c72983e09d916c548a38)
1 /*
2  * Copyright 2017, Andrew Lindesay <apl@lindesay.co.nz>.
3  * All rights reserved. Distributed under the terms of the MIT License.
4  */
5 
6 #include "StorageUtils.h"
7 
8 #include <Directory.h>
9 #include <File.h>
10 #include <Entry.h>
11 #include <String.h>
12 
13 #include <stdio.h>
14 #include <errno.h>
15 
16 #define FILE_TO_STRING_BUFFER_LEN 64
17 
18 
19 /* This method will append the contents of the file at the supplied path to the
20  * string provided.
21  */
22 
23 status_t
24 StorageUtils::AppendToString(BPath& path, BString& result)
25 {
26 	BFile file(path.Path(), O_RDONLY);
27 	uint8_t buffer[FILE_TO_STRING_BUFFER_LEN];
28 	size_t buffer_read;
29 
30 	while((buffer_read = file.Read(buffer, FILE_TO_STRING_BUFFER_LEN)) > 0)
31 		result.Append((char *) buffer, buffer_read);
32 
33 	return (status_t) buffer_read;
34 }
35 
36 
37 /* This method will traverse the directory structure and will remove all of the
38  * files that are present in the directories as well as the directories
39  * themselves.
40  */
41 
42 status_t
43 StorageUtils::RemoveDirectoryContents(BPath& path)
44 {
45 	BDirectory directory(path.Path());
46 	BEntry directoryEntry;
47 	status_t result = B_OK;
48 
49 	while (result == B_OK &&
50 		directory.GetNextEntry(&directoryEntry) != B_ENTRY_NOT_FOUND) {
51 
52 		bool exists = false;
53 		bool isDirectory = false;
54 		BPath directroyEntryPath;
55 
56 		result = directoryEntry.GetPath(&directroyEntryPath);
57 
58 		if (result == B_OK)
59 			result = ExistsDirectory(directroyEntryPath, &exists, &isDirectory);
60 
61 		if (result == B_OK) {
62 			if (isDirectory)
63 				RemoveDirectoryContents(directroyEntryPath);
64 
65 			if (remove(directroyEntryPath.Path()) == 0) {
66 				fprintf(stdout, "did delete [%s]\n",
67 					directroyEntryPath.Path());
68 			} else {
69 				fprintf(stderr, "unable to delete [%s]\n",
70 					directroyEntryPath.Path());
71 				result = B_ERROR;
72 			}
73 		}
74 
75 	}
76 
77 	return result;
78 }
79 
80 
81 /* This method checks to see if a file object exists at the path specified.  If
82  * something does exist then the value of the 'exists' pointer is set to true.
83  * If the object is a directory then this value is also set to true.
84  */
85 
86 status_t
87 StorageUtils::ExistsDirectory(BPath& directory,
88 	bool* exists,
89 	bool* isDirectory)
90 {
91 	struct stat s;
92 
93 	*exists = false;
94 	*isDirectory = false;
95 
96 	if (-1 == stat(directory.Path(), &s)) {
97 		if (ENOENT != errno)
98 			 return B_ERROR;
99 	} else {
100 		*exists = true;
101 		*isDirectory = S_ISDIR(s.st_mode);
102 	}
103 
104 	return B_OK;
105 }
106