aboutsummaryrefslogtreecommitdiff
path: root/src/FileUtil.cpp
blob: d075f2b60f7f08b78c6e313876adf4e35820a22a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
#include "../include/FileUtil.hpp"
#include "../include/env.hpp"
#include <cstdio>

#if OS_FAMILY == OS_FAMILY_POSIX
#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>
#include <fcntl.h>
#endif

using namespace std;

namespace sibs
{
    FileType getFileType(const char *path)
    {
        tinydir_file file;
        if(tinydir_file_open(&file, path) == 0)
        {
            return file.is_dir ? FileType::DIRECTORY : FileType::REGULAR;
        }
        else
        {
            return FileType::FILE_NOT_FOUND;
        }
    }

    // TODO: Handle failure (directory doesn't exist, no permission etc)
    void walkDir(const char *directory, FileWalkCallbackFunc callbackFunc)
    {
        tinydir_dir dir;
        tinydir_open(&dir, directory);

        while (dir.has_next)
        {
            tinydir_file file;
            tinydir_readfile(&dir, &file);
            if(_tinydir_strcmp(file.name, ".") != 0 && _tinydir_strcmp(file.name, "..") != 0)
                callbackFunc(&file);
            tinydir_next(&dir);
        }

        tinydir_close(&dir);
    }

    // TODO: Handle failure (directory doesn't exist, no permission etc)
    void walkDirFiles(const char *directory, FileWalkCallbackFunc callbackFunc)
    {
        tinydir_dir dir;
        tinydir_open(&dir, directory);

        while (dir.has_next)
        {
            tinydir_file file;
            tinydir_readfile(&dir, &file);
            if(file.is_reg)
                callbackFunc(&file);
            tinydir_next(&dir);
        }

        tinydir_close(&dir);
    }

    // TODO: Handle failure (directory doesn't exist, no permission etc)
    void walkDirFilesRecursive(const char *directory, FileWalkCallbackFunc callbackFunc)
    {
        tinydir_dir dir;
        tinydir_open(&dir, directory);

        while (dir.has_next)
        {
            tinydir_file file;
            tinydir_readfile(&dir, &file);
            if(file.is_reg)
                callbackFunc(&file);
            else if(_tinydir_strcmp(file.name, ".") != 0 && _tinydir_strcmp(file.name, "..") != 0)
                walkDirFilesRecursive(file.path, callbackFunc);
            tinydir_next(&dir);
        }

        tinydir_close(&dir);
    }

    Result<StringView> getFileContent(const char *filepath)
    {
        FILE *file = fopen(filepath, "rb");
        if(!file)
        {
            int error = errno;
            string errMsg = "Failed to open file: ";
            errMsg += filepath;
            errMsg += "; reason: ";
            errMsg += strerror(error);
            return Result<StringView>::Err(errMsg);
        }

        fseek(file, 0, SEEK_END);
        size_t fileSize = ftell(file);
        fseek(file, 0, SEEK_SET);

        // TODO: Change this to string so it can be deallocated and use std::move to prevent copies
        char *result = (char*)malloc(fileSize + 1);
        if(!result)
        {
            std::string errMsg = "Failed to load file content from file: ";
            errMsg += filepath;
            throw std::runtime_error(errMsg);
        }
        result[fileSize] = '\0';
        fread(result, 1, fileSize, file);
        fclose(file);
        return Result<StringView>::Ok(StringView(result, fileSize));
    }

    Result<bool> fileOverwrite(const char *filepath, StringView data)
    {
        FILE *file = fopen(filepath, "wb");
        if(!file)
        {
            int error = errno;
            string errMsg = "Failed to overwrite file: ";
            errMsg += filepath;
            errMsg += "; reason: ";
            errMsg += strerror(error);
            return Result<bool>::Err(errMsg);
        }
        setbuf(file, NULL);
        fwrite(data.data, 1, data.size, file);
        fclose(file);
        return Result<bool>::Ok(true);
    }

    const char* getHomeDir()
    {
        const char *homeDir = getenv("HOME");
        if(!homeDir)
        {
            passwd *pw = getpwuid(getuid());
            homeDir = pw->pw_dir;
        }
        return homeDir;
    }

    Result<string> getCwd()
    {
        string cwd;
        cwd.reserve(PATH_MAX);
        if(getcwd(&cwd[0], PATH_MAX) != 0)
        {
            if(cwd.empty()) cwd = ".";
            return Result<string>::Ok(cwd);
        }

        return Result<string>::Err(strerror(errno));
    }

#if OS_FAMILY == OS_FAMILY_POSIX
    Result<bool> createDirectoryRecursive(const char *path)
    {
        char pathBuffer[PATH_MAX];
        size_t pathLength = strlen(path);
        if(pathLength > sizeof(pathBuffer) - 1)
        {
            string errMsg = "Directory path too long: ";
            errMsg += string(path, pathLength);
            return Result<bool>::Err(errMsg, ENAMETOOLONG);
        }
        strcpy(pathBuffer, path);

        char *p = pathBuffer;
        for(size_t i = 0; i < pathLength; ++i)
        {
            if(i > 0 && *p == '/')
            {
                *p = '\0';
                if(mkdir(pathBuffer, S_IRWXU) != 0)
                {
                    int error = errno;
                    if(error != EEXIST)
                    {
                        string errMsg = "Failed to create directory: ";
                        errMsg += pathBuffer;
                        errMsg += "; reason: ";
                        errMsg += strerror(error);
                        return Result<bool>::Err(errMsg, error);
                    }
                }
                *p = '/';
            }
            ++p;
        }

        if(mkdir(pathBuffer, S_IRWXU) != 0)
        {
            int error = errno;
            if(error != EEXIST)
            {
                string errMsg = "Failed to create directory: ";
                errMsg += pathBuffer;
                errMsg += "; reason: ";
                errMsg += strerror(error);
                return Result<bool>::Err(errMsg, error);
            }
        }

        return Result<bool>::Ok(true);
    }

    Result<string> getRealPath(const char *path)
    {
        // TODO: Verify NULL can be passed as 'resolved' argument with different compilers and operating systems (clang, freebsd etc)
        char *resolved = realpath(path, nullptr);
        if(!resolved)
        {
            int error = errno;
            string errMsg = "Failed to get real path for \"";
            errMsg += path;
            errMsg += "\": ";
            errMsg += strerror(error);
            return Result<string>::Err(errMsg, error);
        }

        string result = resolved;
        free(resolved);
        return Result<string>::Ok(result);
    }
#else
#error "TODO: Implement createDirectoryRecursive and getRealPath on windows"
#endif
}