| 1 | #include "common.hh" |
| 2 | |
| 3 | #include <cstdio> |
| 4 | #include <cstdlib> |
| 5 | #include <cstring> |
| 6 | |
| 7 | #include <fstream> |
| 8 | #include <iostream> |
| 9 | #include <errno.h> |
| 10 | |
| 11 | std::string Common::getbasedir(bool trailing) { |
| 12 | std::string homedir = std::getenv("HOME") ? std::getenv("HOME") : ""; |
| 13 | if (homedir.empty()) return ""; |
| 14 | |
| 15 | #if defined(__HAIKU__) |
| 16 | std::string basedir = "/config/settings/sp"; |
| 17 | std::string slash = "/"; |
| 18 | #elif defined(_WIN32) |
| 19 | std::string basedir = "\\AppData\\Local\\076\\sp"; |
| 20 | std::string slash = "\\"; |
| 21 | #else |
| 22 | std::string basedir = "/.local/share/sp"; |
| 23 | std::string slash = "/"; |
| 24 | #endif |
| 25 | |
| 26 | return trailing ? (homedir + basedir + slash) : (homedir + basedir); |
| 27 | } |
| 28 | |
| 29 | std::string Common::getlang() { |
| 30 | const char *env = std::getenv("SP_LANG"); |
| 31 | std::string lang; |
| 32 | |
| 33 | if (env) lang = env; |
| 34 | else lang = "ja"; |
| 35 | |
| 36 | return lang; |
| 37 | } |
| 38 | |
| 39 | int Common::mkdir_r(const std::string &path, mode_t mode) { |
| 40 | char tmp[256]; |
| 41 | size_t len; |
| 42 | |
| 43 | std::snprintf(tmp, sizeof(tmp), "%s", path.c_str()); |
| 44 | |
| 45 | len = std::strlen(tmp); |
| 46 | if (tmp[len - 1] == '/') { |
| 47 | tmp[len - 1] = 0; |
| 48 | } |
| 49 | |
| 50 | for (char *p = tmp + 1; *p; p++) { |
| 51 | if (*p == '/') { |
| 52 | *p = 0; |
| 53 | if (mkdir(tmp, mode) != 0 && errno != EEXIST) return -1; |
| 54 | *p = '/'; |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | if (mkdir(tmp, mode) != 0 && errno != EEXIST) { |
| 59 | return -1; |
| 60 | } |
| 61 | |
| 62 | return 0; |
| 63 | } |
| 64 | |
| 65 | void Common::tmpcopy(const std::string &inpath, const std::string &outpath) { |
| 66 | std::ifstream src(inpath, std::ios::binary); |
| 67 | std::ofstream dst(outpath, std::ios::binary); |
| 68 | } |
| 69 | |
| 70 | std::vector<std::string> Common::explode(const std::string &str, char delimiter) { |
| 71 | std::vector<std::string> tokens; |
| 72 | std::string token; |
| 73 | size_t start = 0, end = 0; |
| 74 | |
| 75 | while ((end = str.find(delimiter, start)) != std::string::npos) { |
| 76 | tokens.push_back(str.substr(start, end - start)); |
| 77 | start = end + 1; |
| 78 | } |
| 79 | tokens.push_back(str.substr(start)); |
| 80 | |
| 81 | return tokens; |
| 82 | } |