blob: d3cf0d8cd0f381b8644a1db2331d3344d5387e74 [file] [log] [blame]
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001/*
2 * Copyright 2016 Google Inc. All rights reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17// clang-format off
18// Dont't remove `format off`, it prevent reordering of win-includes.
Austin Schuh272c6132020-11-14 16:37:52 -080019
Austin Schuh2dd86a92022-09-14 21:19:23 -070020#include <cstring>
Austin Schuh272c6132020-11-14 16:37:52 -080021#if defined(__MINGW32__) || defined(__MINGW64__) || defined(__CYGWIN__) || \
22 defined(__QNXNTO__)
23# define _POSIX_C_SOURCE 200809L
24# define _XOPEN_SOURCE 700L
25#endif
26
Austin Schuh2dd86a92022-09-14 21:19:23 -070027#if defined(_WIN32) || defined(__MINGW32__) || defined(__MINGW64__) || defined(__CYGWIN__)
Austin Schuhe89fa2d2019-08-14 20:24:23 -070028# ifndef WIN32_LEAN_AND_MEAN
29# define WIN32_LEAN_AND_MEAN
30# endif
31# ifndef NOMINMAX
32# define NOMINMAX
33# endif
34# ifdef _MSC_VER
35# include <crtdbg.h>
36# endif
37# include <windows.h> // Must be included before <direct.h>
Austin Schuh2dd86a92022-09-14 21:19:23 -070038# ifndef __CYGWIN__
39# include <direct.h>
40# endif
Austin Schuhe89fa2d2019-08-14 20:24:23 -070041# include <winbase.h>
42# undef interface // This is also important because of reasons
Austin Schuhe89fa2d2019-08-14 20:24:23 -070043#endif
44// clang-format on
45
Austin Schuhe89fa2d2019-08-14 20:24:23 -070046#include "flatbuffers/util.h"
47
48#include <sys/stat.h>
James Kuszmaul8e62b022022-03-22 09:33:25 -070049
Austin Schuhe89fa2d2019-08-14 20:24:23 -070050#include <clocale>
Austin Schuh272c6132020-11-14 16:37:52 -080051#include <cstdlib>
Austin Schuhe89fa2d2019-08-14 20:24:23 -070052#include <fstream>
Austin Schuh2dd86a92022-09-14 21:19:23 -070053#include <functional>
Austin Schuhe89fa2d2019-08-14 20:24:23 -070054
James Kuszmaul8e62b022022-03-22 09:33:25 -070055#include "flatbuffers/base.h"
56
Austin Schuhe89fa2d2019-08-14 20:24:23 -070057namespace flatbuffers {
58
Austin Schuh2dd86a92022-09-14 21:19:23 -070059namespace {
60
61static bool FileExistsRaw(const char *name) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -070062 std::ifstream ifs(name);
63 return ifs.good();
64}
65
Austin Schuh2dd86a92022-09-14 21:19:23 -070066static bool LoadFileRaw(const char *name, bool binary, std::string *buf) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -070067 if (DirExists(name)) return false;
68 std::ifstream ifs(name, binary ? std::ifstream::binary : std::ifstream::in);
69 if (!ifs.is_open()) return false;
70 if (binary) {
71 // The fastest way to read a file into a string.
72 ifs.seekg(0, std::ios::end);
73 auto size = ifs.tellg();
74 (*buf).resize(static_cast<size_t>(size));
75 ifs.seekg(0, std::ios::beg);
76 ifs.read(&(*buf)[0], (*buf).size());
77 } else {
78 // This is slower, but works correctly on all platforms for text files.
79 std::ostringstream oss;
80 oss << ifs.rdbuf();
81 *buf = oss.str();
82 }
83 return !ifs.bad();
84}
85
Austin Schuh2dd86a92022-09-14 21:19:23 -070086LoadFileFunction g_load_file_function = LoadFileRaw;
87FileExistsFunction g_file_exists_function = FileExistsRaw;
88
89static std::string ToCamelCase(const std::string &input, bool first) {
90 std::string s;
91 for (size_t i = 0; i < input.length(); i++) {
92 if (!i && first)
93 s += CharToUpper(input[i]);
94 else if (input[i] == '_' && i + 1 < input.length())
95 s += CharToUpper(input[++i]);
96 else
97 s += input[i];
98 }
99 return s;
100}
101
102static std::string ToSnakeCase(const std::string &input, bool screaming) {
103 std::string s;
104 for (size_t i = 0; i < input.length(); i++) {
105 if (i == 0) {
106 s += screaming ? CharToUpper(input[i]) : CharToLower(input[i]);
107 } else if (input[i] == '_') {
108 s += '_';
109 } else if (!islower(input[i])) {
110 // Prevent duplicate underscores for Upper_Snake_Case strings
111 // and UPPERCASE strings.
James Kuszmaul3b15b0c2022-11-08 14:03:16 -0800112 if (islower(input[i - 1]) || (isdigit(input[i-1]) && !isdigit(input[i]))) { s += '_'; }
Austin Schuh2dd86a92022-09-14 21:19:23 -0700113 s += screaming ? CharToUpper(input[i]) : CharToLower(input[i]);
114 } else {
115 s += screaming ? CharToUpper(input[i]) : input[i];
116 }
117 }
118 return s;
119}
120
121std::string ToAll(const std::string &input,
122 std::function<char(const char)> transform) {
123 std::string s;
124 for (size_t i = 0; i < input.length(); i++) { s += transform(input[i]); }
125 return s;
126}
127
128std::string CamelToSnake(const std::string &input) {
129 std::string s;
130 for (size_t i = 0; i < input.length(); i++) {
131 if (i == 0) {
132 s += CharToLower(input[i]);
133 } else if (input[i] == '_') {
134 s += '_';
135 } else if (!islower(input[i])) {
136 // Prevent duplicate underscores for Upper_Snake_Case strings
137 // and UPPERCASE strings.
James Kuszmaul3b15b0c2022-11-08 14:03:16 -0800138 if (islower(input[i - 1]) || (isdigit(input[i-1]) && !isdigit(input[i]))) { s += '_'; }
Austin Schuh2dd86a92022-09-14 21:19:23 -0700139 s += CharToLower(input[i]);
140 } else {
141 s += input[i];
142 }
143 }
144 return s;
145}
146
147std::string DasherToSnake(const std::string &input) {
148 std::string s;
149 for (size_t i = 0; i < input.length(); i++) {
150 if (input[i] == '-') {
151 s += "_";
152 } else {
153 s += input[i];
154 }
155 }
156 return s;
157}
158
159std::string ToDasher(const std::string &input) {
160 std::string s;
161 char p = 0;
162 for (size_t i = 0; i < input.length(); i++) {
163 char const &c = input[i];
164 if (c == '_') {
165 if (i > 0 && p != kPathSeparator &&
166 // The following is a special case to ignore digits after a _. This is
167 // because ThisExample3 would be converted to this_example_3 in the
168 // CamelToSnake conversion, and then dasher would do this-example-3,
169 // but it expects this-example3.
170 !(i + 1 < input.length() && isdigit(input[i + 1])))
171 s += "-";
172 } else {
173 s += c;
174 }
175 p = c;
176 }
177 return s;
178}
179
180
181// Converts foo_bar_123baz_456 to foo_bar123_baz456
182std::string SnakeToSnake2(const std::string &s) {
183 if (s.length() <= 1) return s;
184 std::string result;
185 result.reserve(s.size());
186 for (size_t i = 0; i < s.length() - 1; i++) {
187 if (s[i] == '_' && isdigit(s[i + 1])) {
188 continue; // Move the `_` until after the digits.
189 }
190
191 result.push_back(s[i]);
192
193 if (isdigit(s[i]) && isalpha(s[i + 1]) && islower(s[i + 1])) {
194 result.push_back('_');
195 }
196 }
197 result.push_back(s.back());
198
199 return result;
200}
201
202} // namespace
203
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700204
205bool LoadFile(const char *name, bool binary, std::string *buf) {
206 FLATBUFFERS_ASSERT(g_load_file_function);
207 return g_load_file_function(name, binary, buf);
208}
209
210bool FileExists(const char *name) {
211 FLATBUFFERS_ASSERT(g_file_exists_function);
212 return g_file_exists_function(name);
213}
214
James Kuszmaul2eab3342023-09-29 09:10:57 -0700215#ifdef __clang__
216#define NO_MSAN_ATTRIBUTE __attribute__((no_sanitize("memory")))
217#else
218#define NO_MSAN_ATTRIBUTE
219#endif
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700220
James Kuszmaul2eab3342023-09-29 09:10:57 -0700221// For no obvious reason, clang's sanitizer thinks that the mode bits from
222// stat() are uninitialized in some circumstances.
223bool DirExists(const char *name) NO_MSAN_ATTRIBUTE {
224 // clang-format off
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700225 #ifdef _WIN32
226 #define flatbuffers_stat _stat
227 #define FLATBUFFERS_S_IFDIR _S_IFDIR
228 #else
229 #define flatbuffers_stat stat
230 #define FLATBUFFERS_S_IFDIR S_IFDIR
231 #endif
232 // clang-format on
233 struct flatbuffers_stat file_info;
234 if (flatbuffers_stat(name, &file_info) != 0) return false;
235 return (file_info.st_mode & FLATBUFFERS_S_IFDIR) != 0;
236}
237
238LoadFileFunction SetLoadFileFunction(LoadFileFunction load_file_function) {
239 LoadFileFunction previous_function = g_load_file_function;
240 g_load_file_function = load_file_function ? load_file_function : LoadFileRaw;
241 return previous_function;
242}
243
244FileExistsFunction SetFileExistsFunction(
245 FileExistsFunction file_exists_function) {
246 FileExistsFunction previous_function = g_file_exists_function;
247 g_file_exists_function =
248 file_exists_function ? file_exists_function : FileExistsRaw;
249 return previous_function;
250}
251
252bool SaveFile(const char *name, const char *buf, size_t len, bool binary) {
253 std::ofstream ofs(name, binary ? std::ofstream::binary : std::ofstream::out);
254 if (!ofs.is_open()) return false;
255 ofs.write(buf, len);
256 return !ofs.bad();
257}
258
259// We internally store paths in posix format ('/'). Paths supplied
260// by the user should go through PosixPath to ensure correct behavior
261// on Windows when paths are string-compared.
262
263static const char kPathSeparatorWindows = '\\';
264static const char *PathSeparatorSet = "\\/"; // Intentionally no ':'
265
266std::string StripExtension(const std::string &filepath) {
267 size_t i = filepath.find_last_of('.');
268 return i != std::string::npos ? filepath.substr(0, i) : filepath;
269}
270
271std::string GetExtension(const std::string &filepath) {
272 size_t i = filepath.find_last_of('.');
273 return i != std::string::npos ? filepath.substr(i + 1) : "";
274}
275
276std::string StripPath(const std::string &filepath) {
277 size_t i = filepath.find_last_of(PathSeparatorSet);
278 return i != std::string::npos ? filepath.substr(i + 1) : filepath;
279}
280
281std::string StripFileName(const std::string &filepath) {
282 size_t i = filepath.find_last_of(PathSeparatorSet);
283 return i != std::string::npos ? filepath.substr(0, i) : "";
284}
285
Austin Schuh2dd86a92022-09-14 21:19:23 -0700286std::string StripPrefix(const std::string &filepath,
287 const std::string &prefix_to_remove) {
288 if (!strncmp(filepath.c_str(), prefix_to_remove.c_str(),
289 prefix_to_remove.size())) {
290 return filepath.substr(prefix_to_remove.size());
291 }
292 return filepath;
293}
294
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700295std::string ConCatPathFileName(const std::string &path,
296 const std::string &filename) {
297 std::string filepath = path;
298 if (filepath.length()) {
James Kuszmaul8e62b022022-03-22 09:33:25 -0700299 char &filepath_last_character = filepath.back();
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700300 if (filepath_last_character == kPathSeparatorWindows) {
301 filepath_last_character = kPathSeparator;
302 } else if (filepath_last_character != kPathSeparator) {
303 filepath += kPathSeparator;
304 }
305 }
306 filepath += filename;
307 // Ignore './' at the start of filepath.
308 if (filepath[0] == '.' && filepath[1] == kPathSeparator) {
309 filepath.erase(0, 2);
310 }
311 return filepath;
312}
313
314std::string PosixPath(const char *path) {
315 std::string p = path;
316 std::replace(p.begin(), p.end(), '\\', '/');
317 return p;
318}
James Kuszmaul8e62b022022-03-22 09:33:25 -0700319std::string PosixPath(const std::string &path) {
320 return PosixPath(path.c_str());
321}
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700322
323void EnsureDirExists(const std::string &filepath) {
324 auto parent = StripFileName(filepath);
325 if (parent.length()) EnsureDirExists(parent);
326 // clang-format off
327
328 #ifdef _WIN32
329 (void)_mkdir(filepath.c_str());
330 #else
331 mkdir(filepath.c_str(), S_IRWXU|S_IRGRP|S_IXGRP);
332 #endif
333 // clang-format on
334}
335
336std::string AbsolutePath(const std::string &filepath) {
337 // clang-format off
338
339 #ifdef FLATBUFFERS_NO_ABSOLUTE_PATH_RESOLUTION
340 return filepath;
341 #else
Austin Schuh2dd86a92022-09-14 21:19:23 -0700342 #if defined(_WIN32) || defined(__MINGW32__) || defined(__MINGW64__) || defined(__CYGWIN__)
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700343 char abs_path[MAX_PATH];
344 return GetFullPathNameA(filepath.c_str(), MAX_PATH, abs_path, nullptr)
345 #else
Austin Schuh272c6132020-11-14 16:37:52 -0800346 char *abs_path_temp = realpath(filepath.c_str(), nullptr);
347 bool success = abs_path_temp != nullptr;
348 std::string abs_path;
349 if(success) {
350 abs_path = abs_path_temp;
351 free(abs_path_temp);
352 }
353 return success
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700354 #endif
355 ? abs_path
356 : filepath;
357 #endif // FLATBUFFERS_NO_ABSOLUTE_PATH_RESOLUTION
358 // clang-format on
359}
360
James Kuszmaul8e62b022022-03-22 09:33:25 -0700361std::string RelativeToRootPath(const std::string &project,
362 const std::string &filepath) {
363 std::string absolute_project = PosixPath(AbsolutePath(project));
364 if (absolute_project.back() != '/') absolute_project += "/";
365 std::string absolute_filepath = PosixPath(AbsolutePath(filepath));
366
367 // Find the first character where they disagree.
368 // The previous directory is the lowest common ancestor;
369 const char *a = absolute_project.c_str();
370 const char *b = absolute_filepath.c_str();
371 size_t common_prefix_len = 0;
372 while (*a != '\0' && *b != '\0' && *a == *b) {
373 if (*a == '/') common_prefix_len = a - absolute_project.c_str();
374 a++;
375 b++;
376 }
377 // the number of ../ to prepend to b depends on the number of remaining
378 // directories in A.
379 const char *suffix = absolute_project.c_str() + common_prefix_len;
380 size_t num_up = 0;
381 while (*suffix != '\0')
382 if (*suffix++ == '/') num_up++;
383 num_up--; // last one is known to be '/'.
384 std::string result = "//";
385 for (size_t i = 0; i < num_up; i++) result += "../";
386 result += absolute_filepath.substr(common_prefix_len + 1);
387
388 return result;
389}
390
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700391// Locale-independent code.
392#if defined(FLATBUFFERS_LOCALE_INDEPENDENT) && \
393 (FLATBUFFERS_LOCALE_INDEPENDENT > 0)
394
395// clang-format off
396// Allocate locale instance at startup of application.
397ClassicLocale ClassicLocale::instance_;
398
399#ifdef _MSC_VER
400 ClassicLocale::ClassicLocale()
401 : locale_(_create_locale(LC_ALL, "C")) {}
402 ClassicLocale::~ClassicLocale() { _free_locale(locale_); }
403#else
404 ClassicLocale::ClassicLocale()
405 : locale_(newlocale(LC_ALL, "C", nullptr)) {}
406 ClassicLocale::~ClassicLocale() { freelocale(locale_); }
407#endif
408// clang-format on
409
410#endif // !FLATBUFFERS_LOCALE_INDEPENDENT
411
412std::string RemoveStringQuotes(const std::string &s) {
413 auto ch = *s.c_str();
James Kuszmaul8e62b022022-03-22 09:33:25 -0700414 return ((s.size() >= 2) && (ch == '\"' || ch == '\'') && (ch == s.back()))
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700415 ? s.substr(1, s.length() - 2)
416 : s;
417}
418
419bool SetGlobalTestLocale(const char *locale_name, std::string *_value) {
420 const auto the_locale = setlocale(LC_ALL, locale_name);
421 if (!the_locale) return false;
422 if (_value) *_value = std::string(the_locale);
423 return true;
424}
425
426bool ReadEnvironmentVariable(const char *var_name, std::string *_value) {
Austin Schuh272c6132020-11-14 16:37:52 -0800427#ifdef _MSC_VER
428 __pragma(warning(disable : 4996)); // _CRT_SECURE_NO_WARNINGS
429#endif
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700430 auto env_str = std::getenv(var_name);
431 if (!env_str) return false;
432 if (_value) *_value = std::string(env_str);
433 return true;
434}
435
James Kuszmaul8e62b022022-03-22 09:33:25 -0700436std::string ConvertCase(const std::string &input, Case output_case,
437 Case input_case) {
438 if (output_case == Case::kKeep) return input;
439 // The output cases expect snake_case inputs, so if we don't have that input
440 // format, try to convert to snake_case.
441 switch (input_case) {
442 case Case::kLowerCamel:
443 case Case::kUpperCamel:
444 return ConvertCase(CamelToSnake(input), output_case);
445 case Case::kDasher: return ConvertCase(DasherToSnake(input), output_case);
446 case Case::kKeep: printf("WARNING: Converting from kKeep case.\n"); break;
447 default:
448 case Case::kSnake:
449 case Case::kScreamingSnake:
450 case Case::kAllLower:
451 case Case::kAllUpper: break;
452 }
453
454 switch (output_case) {
455 case Case::kUpperCamel: return ToCamelCase(input, true);
456 case Case::kLowerCamel: return ToCamelCase(input, false);
457 case Case::kSnake: return input;
458 case Case::kScreamingSnake: return ToSnakeCase(input, true);
459 case Case::kAllUpper: return ToAll(input, CharToUpper);
460 case Case::kAllLower: return ToAll(input, CharToLower);
461 case Case::kDasher: return ToDasher(input);
Austin Schuh2dd86a92022-09-14 21:19:23 -0700462 case Case::kSnake2: return SnakeToSnake2(input);
James Kuszmaul8e62b022022-03-22 09:33:25 -0700463 default:
464 case Case::kUnknown: return input;
465 }
466}
467
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700468} // namespace flatbuffers