From 154687e0df719c4d07b8dadcd11d629d835d4243 Mon Sep 17 00:00:00 2001 From: JonasBa Date: Tue, 5 Dec 2023 18:49:39 -0500 Subject: [PATCH 1/8] format: install clang-format --- package-lock.json | 23 +++++++++++++++++++++++ package.json | 7 +++++-- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/package-lock.json b/package-lock.json index 7e1976bb..cf87ebf2 100644 --- a/package-lock.json +++ b/package-lock.json @@ -26,6 +26,7 @@ "@typescript-eslint/parser": "^5.36.2", "autocannon": "^7.9.0", "benchmark": "^2.1.4", + "clang-format": "^1.8.0", "cross-env": "^7.0.3", "detect-libc": "^2.0.2", "esbuild": "^0.17.18", @@ -2713,6 +2714,12 @@ "node": ">=8" } }, + "node_modules/async": { + "version": "3.2.5", + "resolved": "https://registry.npmjs.org/async/-/async-3.2.5.tgz", + "integrity": "sha512-baNZyqaaLhyLVKm/DlvdW051MSgO6b8eVfIezl9E5PqWxFgzLm/wQntEW4zOytVburDEr0JlALEpdOFwvErLsg==", + "dev": true + }, "node_modules/asynckit": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", @@ -3257,6 +3264,22 @@ "integrity": "sha512-0TNiGstbQmCFwt4akjjBg5pLRTSyj/PkWQ1ZoO2zntmg9yLqSRxwEa4iCfQLGjqhiqBfOJa7W/E8wfGrTDmlZQ==", "dev": true }, + "node_modules/clang-format": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/clang-format/-/clang-format-1.8.0.tgz", + "integrity": "sha512-pK8gzfu55/lHzIpQ1givIbWfn3eXnU7SfxqIwVgnn5jEM6j4ZJYjpFqFs4iSBPNedzRMmfjYjuQhu657WAXHXw==", + "dev": true, + "dependencies": { + "async": "^3.2.3", + "glob": "^7.0.0", + "resolve": "^1.1.6" + }, + "bin": { + "check-clang-format": "bin/check-clang-format.js", + "clang-format": "index.js", + "git-clang-format": "bin/git-clang-format" + } + }, "node_modules/clean-stack": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/clean-stack/-/clean-stack-2.2.0.tgz", diff --git a/package.json b/package.json index 39c7abea..92a2efac 100644 --- a/package.json +++ b/package.json @@ -31,6 +31,9 @@ "install": "node scripts/check-build.mjs", "clean": "rm -rf ./lib && rm -rf build", "lint": "eslint ./src --ext .ts", + "format": "npm run format:prettier && npm run format:clang", + "format:prettier": "prettier --config ./.prettierrc --write", + "format:clang": "clang-format -i ./**/*.cc", "build": "npm run build:bindings && npm run build:lib", "build:lib:esm": "node ./esbuild.esm.mjs", "build:lib:cjs": "node ./esbuild.cjs.mjs", @@ -59,8 +62,7 @@ "test:rollup:build": "rollup --config ./demo_app/rollup.config.js", "test:rollup:run": "BUNDLER=rollup node ./demo_app/dist/rollup/index.js", "test:rollup": "npm run test:rollup:build && npm run test:rollup:run", - "test": "cross-env SENTRY_PROFILER_BINARY_DIR=./lib jest --config jest.config.ts", - "prettier": "prettier --config ./.prettierrc --write" + "test": "cross-env SENTRY_PROFILER_BINARY_DIR=./lib jest --config jest.config.ts" }, "keywords": [ "profiling", @@ -94,6 +96,7 @@ "@typescript-eslint/parser": "^5.36.2", "autocannon": "^7.9.0", "benchmark": "^2.1.4", + "clang-format": "^1.8.0", "cross-env": "^7.0.3", "detect-libc": "^2.0.2", "esbuild": "^0.17.18", From 06bdbec87bee0413ae81794d030c536855277419 Mon Sep 17 00:00:00 2001 From: JonasBa Date: Tue, 5 Dec 2023 18:50:03 -0500 Subject: [PATCH 2/8] format: format bindings --- bindings/cpu_profiler.cc | 509 +++++++++++++++++++++++---------------- 1 file changed, 305 insertions(+), 204 deletions(-) diff --git a/bindings/cpu_profiler.cc b/bindings/cpu_profiler.cc index 56907b86..56c02acb 100644 --- a/bindings/cpu_profiler.cc +++ b/bindings/cpu_profiler.cc @@ -5,19 +5,19 @@ #include #include +#include #include #include -#include -#include #include +#include #include #define FORMAT_SAMPLED 2 #define FORMAT_RAW 1 -#ifndef PROFILER_FORMAT +#ifndef PROFILER_FORMAT #define PROFILER_FORMAT FORMAT_SAMPLED #endif @@ -29,19 +29,22 @@ static const uint8_t kMaxStackDepth(128); static const float kSamplingFrequency(99.0); // 99 to avoid lockstep sampling static const float kSamplingHz(1 / kSamplingFrequency); static const int kSamplingInterval(kSamplingHz * 1e6); -static const v8::CpuProfilingNamingMode kNamingMode(v8::CpuProfilingNamingMode::kDebugNaming); -static const v8::CpuProfilingLoggingMode kDefaultLoggingMode(v8::CpuProfilingLoggingMode::kEagerLogging); - -// Allow users to override the default logging mode via env variable. This is useful -// because sometimes the flow of the profiled program can be to execute many sequential -// transaction - in that case, it may be preferable to set eager logging to avoid paying the -// high cost of profiling for each individual transaction (one example for this are jest -// tests when run with --runInBand option). -static const char* kEagerLoggingMode = "eager"; -static const char* kLazyLoggingMode = "lazy"; +static const v8::CpuProfilingNamingMode + kNamingMode(v8::CpuProfilingNamingMode::kDebugNaming); +static const v8::CpuProfilingLoggingMode + kDefaultLoggingMode(v8::CpuProfilingLoggingMode::kEagerLogging); + +// Allow users to override the default logging mode via env variable. This is +// useful because sometimes the flow of the profiled program can be to execute +// many sequential transaction - in that case, it may be preferable to set eager +// logging to avoid paying the high cost of profiling for each individual +// transaction (one example for this are jest tests when run with --runInBand +// option). +static const char *kEagerLoggingMode = "eager"; +static const char *kLazyLoggingMode = "lazy"; v8::CpuProfilingLoggingMode GetLoggingMode() { - static const char* logging_mode(getenv("SENTRY_PROFILER_LOGGING_MODE")); + static const char *logging_mode(getenv("SENTRY_PROFILER_LOGGING_MODE")); // most times this wont be set so just bail early if (!logging_mode) { @@ -68,36 +71,42 @@ enum class ProfileStatus { kStopped, }; - class MeasurementsTicker { private: uv_timer_t timer; uint64_t period_ms; - std::unordered_map> heap_listeners; - std::unordered_map> cpu_listeners; - v8::Isolate* isolate; + std::unordered_map> + heap_listeners; + std::unordered_map> + cpu_listeners; + v8::Isolate *isolate; v8::HeapStatistics heap_stats; uv_cpu_info_t cpu_stats; public: - MeasurementsTicker(uv_loop_t* loop) : - period_ms(100), - isolate(v8::Isolate::GetCurrent()) - { + MeasurementsTicker(uv_loop_t *loop) + : period_ms(100), isolate(v8::Isolate::GetCurrent()) { uv_timer_init(loop, &timer); timer.data = this; } - static void ticker(uv_timer_t*); + static void ticker(uv_timer_t *); // Memory listeners void heap_callback(); - void add_heap_listener(std::string& profile_id, const std::function cb); - void remove_heap_listener(std::string& profile_id, const std::function& cb); + void add_heap_listener( + std::string &profile_id, + const std::function cb); + void remove_heap_listener( + std::string &profile_id, + const std::function &cb); // CPU listeners void cpu_callback(); - void add_cpu_listener(std::string& profile_id, const std::function cb); - void remove_cpu_listener(std::string& profile_id, const std::function& cb); + void add_cpu_listener(std::string &profile_id, + const std::function cb); + void remove_cpu_listener(std::string &profile_id, + const std::function &cb); size_t listener_count(); }; @@ -111,12 +120,14 @@ void MeasurementsTicker::heap_callback() { isolate->GetHeapStatistics(&heap_stats); uint64_t ts = uv_hrtime(); - for(auto cb : heap_listeners) { + for (auto cb : heap_listeners) { cb.second(ts, heap_stats); } } -void MeasurementsTicker::add_heap_listener(std::string& profile_id, const std::function cb) { +void MeasurementsTicker::add_heap_listener( + std::string &profile_id, + const std::function cb) { heap_listeners.emplace(profile_id, cb); if (listener_count() == 1) { @@ -125,7 +136,9 @@ void MeasurementsTicker::add_heap_listener(std::string& profile_id, const std::f } } -void MeasurementsTicker::remove_heap_listener(std::string& profile_id, const std::function& cb) { +void MeasurementsTicker::remove_heap_listener( + std::string &profile_id, + const std::function &cb) { heap_listeners.erase(profile_id); if (listener_count() == 0) { @@ -135,7 +148,7 @@ void MeasurementsTicker::remove_heap_listener(std::string& profile_id, const std // CPU tickers void MeasurementsTicker::cpu_callback() { - uv_cpu_info_t* cpu = &cpu_stats; + uv_cpu_info_t *cpu = &cpu_stats; int count; int err = uv_cpu_info(&cpu, &count); @@ -143,7 +156,7 @@ void MeasurementsTicker::cpu_callback() { return; } - if(count < 1) { + if (count < 1) { return; } @@ -152,7 +165,7 @@ void MeasurementsTicker::cpu_callback() { uint64_t idle_total = 0; for (int i = 0; i < count; i++) { - uv_cpu_info_t* core = cpu + i; + uv_cpu_info_t *core = cpu + i; total += core->cpu_times.user; total += core->cpu_times.nice; @@ -167,7 +180,7 @@ void MeasurementsTicker::cpu_callback() { double total_avg = total / count; double rate = 1.0 - idle_avg / total_avg; - if(rate < 0.0 || isinf(rate) || isnan(rate)) { + if (rate < 0.0 || isinf(rate) || isnan(rate)) { rate = 0.0; } @@ -175,22 +188,22 @@ void MeasurementsTicker::cpu_callback() { while (it != cpu_listeners.end()) { if (it->second(ts, rate)) { it = cpu_listeners.erase(it); - } - else { + } else { ++it; } }; - + uv_free_cpu_info(cpu, count); }; -void MeasurementsTicker::ticker(uv_timer_t* handle) { - MeasurementsTicker* self = static_cast(handle->data); +void MeasurementsTicker::ticker(uv_timer_t *handle) { + MeasurementsTicker *self = static_cast(handle->data); self->heap_callback(); self->cpu_callback(); } -void MeasurementsTicker::add_cpu_listener(std::string& profile_id, const std::function cb) { +void MeasurementsTicker::add_cpu_listener( + std::string &profile_id, const std::function cb) { cpu_listeners.emplace(profile_id, cb); if (listener_count() == 1) { @@ -199,7 +212,8 @@ void MeasurementsTicker::add_cpu_listener(std::string& profile_id, const std::fu } } -void MeasurementsTicker::remove_cpu_listener(std::string& profile_id, const std::function& cb) { +void MeasurementsTicker::remove_cpu_listener( + std::string &profile_id, const std::function &cb) { cpu_listeners.erase(profile_id); if (listener_count() == 0) { @@ -209,19 +223,19 @@ void MeasurementsTicker::remove_cpu_listener(std::string& profile_id, const std: class Profiler { public: - std::unordered_map active_profiles; + std::unordered_map active_profiles; MeasurementsTicker measurements_ticker; - v8::CpuProfiler* cpu_profiler; + v8::CpuProfiler *cpu_profiler; - explicit Profiler(const napi_env& env, v8::Isolate* isolate) : - measurements_ticker(uv_default_loop()), - cpu_profiler( - v8::CpuProfiler::New(isolate, kNamingMode, GetLoggingMode())) { + explicit Profiler(const napi_env &env, v8::Isolate *isolate) + : measurements_ticker(uv_default_loop()), + cpu_profiler( + v8::CpuProfiler::New(isolate, kNamingMode, GetLoggingMode())) { napi_add_env_cleanup_hook(env, DeleteInstance, this); } - static void DeleteInstance(void* data); + static void DeleteInstance(void *data); }; class SentryProfile { @@ -236,73 +250,76 @@ class SentryProfile { std::vector cpu_stats_ts; std::vector cpu_stats_usage; - - const std::function memory_sampler_cb; + const std::function memory_sampler_cb; const std::function cpu_sampler_cb; ProfileStatus status = ProfileStatus::kNotStarted; std::string id; public: - explicit SentryProfile(const char* id) : - started_at(uv_hrtime()), - memory_sampler_cb([this](uint64_t ts, v8::HeapStatistics& stats) { - - if ((heap_write_index >= heap_stats_ts.capacity()) || heap_write_index >= heap_stats_usage.capacity()) { - return true; - } - - heap_stats_ts.insert(heap_stats_ts.begin() + heap_write_index, ts - started_at); - heap_stats_usage.insert(heap_stats_usage.begin() + heap_write_index, static_cast(stats.used_heap_size())); - ++heap_write_index; - - return false; - }), - - cpu_sampler_cb([this](uint64_t ts, double rate) { - if (cpu_write_index >= cpu_stats_ts.capacity() || cpu_write_index >= cpu_stats_usage.capacity - ()) { - return true; - } - cpu_stats_ts.insert(cpu_stats_ts.begin() + cpu_write_index, ts - started_at); - cpu_stats_usage.insert(cpu_stats_usage.begin() + cpu_write_index, rate); - ++cpu_write_index; - return false; - }), - - status(ProfileStatus::kNotStarted), - id(id) { + explicit SentryProfile(const char *id) + : started_at(uv_hrtime()), + memory_sampler_cb([this](uint64_t ts, v8::HeapStatistics &stats) { + if ((heap_write_index >= heap_stats_ts.capacity()) || + heap_write_index >= heap_stats_usage.capacity()) { + return true; + } + + heap_stats_ts.insert(heap_stats_ts.begin() + heap_write_index, + ts - started_at); + heap_stats_usage.insert( + heap_stats_usage.begin() + heap_write_index, + static_cast(stats.used_heap_size())); + ++heap_write_index; + + return false; + }), + + cpu_sampler_cb([this](uint64_t ts, double rate) { + if (cpu_write_index >= cpu_stats_ts.capacity() || + cpu_write_index >= cpu_stats_usage.capacity()) { + return true; + } + cpu_stats_ts.insert(cpu_stats_ts.begin() + cpu_write_index, + ts - started_at); + cpu_stats_usage.insert(cpu_stats_usage.begin() + cpu_write_index, + rate); + ++cpu_write_index; + return false; + }), + + status(ProfileStatus::kNotStarted), id(id) { heap_stats_ts.reserve(300); heap_stats_usage.reserve(300); cpu_stats_ts.reserve(300); cpu_stats_usage.reserve(300); } - const std::vector& heap_usage_timestamps()const; - const std::vector& heap_usage_values()const; - const uint16_t& heap_usage_write_index() const; + const std::vector &heap_usage_timestamps() const; + const std::vector &heap_usage_values() const; + const uint16_t &heap_usage_write_index() const; - const std::vector& cpu_usage_timestamps() const; - const std::vector& cpu_usage_values() const; - const uint16_t& cpu_usage_write_index() const; + const std::vector &cpu_usage_timestamps() const; + const std::vector &cpu_usage_values() const; + const uint16_t &cpu_usage_write_index() const; - void Start(Profiler* profiler); - v8::CpuProfile* Stop(Profiler* profiler); + void Start(Profiler *profiler); + v8::CpuProfile *Stop(Profiler *profiler); }; - -void SentryProfile::Start(Profiler* profiler) { - v8::Local profile_title = v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), id.c_str(), v8::NewStringType::kNormal).ToLocalChecked(); +void SentryProfile::Start(Profiler *profiler) { + v8::Local profile_title = + v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), id.c_str(), + v8::NewStringType::kNormal) + .ToLocalChecked(); started_at = uv_hrtime(); // Initialize the CPU Profiler - profiler->cpu_profiler->StartProfiling(profile_title, { - v8::CpuProfilingMode::kCallerLineNumbers, - v8::CpuProfilingOptions::kNoSampleLimit, - kSamplingInterval - }); - + profiler->cpu_profiler->StartProfiling( + profile_title, + {v8::CpuProfilingMode::kCallerLineNumbers, + v8::CpuProfilingOptions::kNoSampleLimit, kSamplingInterval}); // listen for memory sample ticks profiler->measurements_ticker.add_cpu_listener(id, cpu_sampler_cb); @@ -311,7 +328,9 @@ void SentryProfile::Start(Profiler* profiler) { status = ProfileStatus::kStarted; } -static void CleanupSentryProfile(Profiler* profiler, SentryProfile* sentry_profile, const std::string& profile_id) { +static void CleanupSentryProfile(Profiler *profiler, + SentryProfile *sentry_profile, + const std::string &profile_id) { if (sentry_profile == nullptr) { return; } @@ -320,10 +339,10 @@ static void CleanupSentryProfile(Profiler* profiler, SentryProfile* sentry_profi delete sentry_profile; }; -void Profiler::DeleteInstance(void* data) { - Profiler* profiler = static_cast(data); +void Profiler::DeleteInstance(void *data) { + Profiler *profiler = static_cast(data); - for (auto& profile : profiler->active_profiles) { + for (auto &profile : profiler->active_profiles) { CleanupSentryProfile(profiler, profile.second, profile.first); } @@ -331,41 +350,44 @@ void Profiler::DeleteInstance(void* data) { delete profiler; } -v8::CpuProfile* SentryProfile::Stop(Profiler* profiler) { +v8::CpuProfile *SentryProfile::Stop(Profiler *profiler) { // Stop the CPU Profiler - v8::CpuProfile* profile = profiler->cpu_profiler->StopProfiling(v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), id.c_str(), v8::NewStringType::kNormal).ToLocalChecked()); + v8::CpuProfile *profile = profiler->cpu_profiler->StopProfiling( + v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), id.c_str(), + v8::NewStringType::kNormal) + .ToLocalChecked()); // Remove the meemory sampler profiler->measurements_ticker.remove_heap_listener(id, memory_sampler_cb); profiler->measurements_ticker.remove_cpu_listener(id, cpu_sampler_cb); - // If for some reason stopProfiling was called with an invalid profile title or - // if that title had somehow been stopped already, profile will be null. + // If for some reason stopProfiling was called with an invalid profile title + // or if that title had somehow been stopped already, profile will be null. status = ProfileStatus::kStopped; return profile; } // Memory getters -const std::vector& SentryProfile::heap_usage_timestamps() const { +const std::vector &SentryProfile::heap_usage_timestamps() const { return heap_stats_ts; }; -const std::vector& SentryProfile::heap_usage_values() const { +const std::vector &SentryProfile::heap_usage_values() const { return heap_stats_usage; }; -const uint16_t& SentryProfile::heap_usage_write_index() const { +const uint16_t &SentryProfile::heap_usage_write_index() const { return heap_write_index; }; // CPU getters -const std::vector& SentryProfile::cpu_usage_timestamps() const { +const std::vector &SentryProfile::cpu_usage_timestamps() const { return cpu_stats_ts; }; -const std::vector& SentryProfile::cpu_usage_values() const { +const std::vector &SentryProfile::cpu_usage_values() const { return cpu_stats_usage; }; -const uint16_t& SentryProfile::cpu_usage_write_index() const { +const uint16_t &SentryProfile::cpu_usage_write_index() const { return cpu_write_index; }; @@ -378,9 +400,10 @@ static const char kPlatformSeparator = '/'; static const char kSentryPathDelimiter = '.'; static const char kSentryFileDelimiter = ':'; -static const std::string kNodeModulesPath = std::string("node_modules") + kPlatformSeparator; +static const std::string kNodeModulesPath = + std::string("node_modules") + kPlatformSeparator; -static void GetFrameModule(const std::string& abs_path, std::string& module) { +static void GetFrameModule(const std::string &abs_path, std::string &module) { if (abs_path.empty()) { return; } @@ -399,18 +422,21 @@ static void GetFrameModule(const std::string& abs_path, std::string& module) { module = module.substr(node_modules_pos + 13); } - // Replace all path separators with dots except the last one, that one is replaced with a colon + // Replace all path separators with dots except the last one, that one is + // replaced with a colon int match_count = 0; for (int pos = module.length() - 1; pos >= 0; pos--) { // if there is a match and it's not the first character, replace it if (module[pos] == kPlatformSeparator) { - module[pos] = match_count == 0 ? kSentryFileDelimiter : kSentryPathDelimiter; + module[pos] = + match_count == 0 ? kSentryFileDelimiter : kSentryPathDelimiter; match_count++; } } #ifdef _WIN32 - // Strip out C: prefix. On Windows, the drive letter is not part of the module name + // Strip out C: prefix. On Windows, the drive letter is not part of the module + // name if (module[1] == kWinDiskPrefix) { // We will try and strip our the disk prefix. module = module.substr(2, std::string::npos); @@ -430,19 +456,24 @@ static napi_value GetFrameModuleWrapped(napi_env env, napi_callback_info info) { size_t len; assert(napi_get_value_string_utf8(env, argv[0], NULL, 0, &len) == napi_ok); - char* abs_path = (char*)malloc(len + 1); - assert(napi_get_value_string_utf8(env, argv[0], abs_path, len + 1, &len) == napi_ok); + char *abs_path = (char *)malloc(len + 1); + assert(napi_get_value_string_utf8(env, argv[0], abs_path, len + 1, &len) == + napi_ok); std::string module; napi_value napi_module; GetFrameModule(abs_path, module); - assert(napi_create_string_utf8(env, module.c_str(), NAPI_AUTO_LENGTH, &napi_module) == napi_ok); + assert(napi_create_string_utf8(env, module.c_str(), NAPI_AUTO_LENGTH, + &napi_module) == napi_ok); return napi_module; } -napi_value CreateFrameNode(const napi_env& env, const v8::CpuProfileNode& node, std::unordered_map& module_cache, napi_value& resources) { +napi_value +CreateFrameNode(const napi_env &env, const v8::CpuProfileNode &node, + std::unordered_map &module_cache, + napi_value &resources) { napi_value js_node; napi_create_object(env, &js_node); @@ -461,18 +492,20 @@ napi_value CreateFrameNode(const napi_env& env, const v8::CpuProfileNode& node, } napi_value function; - napi_create_string_utf8(env, node.GetFunctionNameStr(), NAPI_AUTO_LENGTH, &function); + napi_create_string_utf8(env, node.GetFunctionNameStr(), NAPI_AUTO_LENGTH, + &function); napi_set_named_property(env, js_node, "function", function); - const char* resource = node.GetScriptResourceNameStr(); + const char *resource = node.GetScriptResourceNameStr(); if (resource != nullptr) { // resource is absolute path, set it on the abs_path property napi_value abs_path_prop; napi_create_string_utf8(env, resource, NAPI_AUTO_LENGTH, &abs_path_prop); napi_set_named_property(env, js_node, "abs_path", abs_path_prop); - // Error stack traces are not relative to root dir, doing our own path normalization - // breaks people's code mapping configs so we need to leave it as is. + // Error stack traces are not relative to root dir, doing our own path + // normalization breaks people's code mapping configs so we need to leave it + // as is. napi_set_named_property(env, js_node, "filename", abs_path_prop); std::string module; @@ -484,10 +517,10 @@ napi_value CreateFrameNode(const napi_env& env, const v8::CpuProfileNode& node, if (module_cache.find(resource_str) != module_cache.end()) { module = module_cache[resource_str]; - } - else { + } else { napi_value resource; - napi_create_string_utf8(env, resource_str.c_str(), NAPI_AUTO_LENGTH, &resource); + napi_create_string_utf8(env, resource_str.c_str(), NAPI_AUTO_LENGTH, + &resource); napi_set_element(env, resources, module_cache.size(), resource); GetFrameModule(resource_str, module); @@ -496,7 +529,8 @@ napi_value CreateFrameNode(const napi_env& env, const v8::CpuProfileNode& node, if (!module.empty()) { napi_value filename_prop; - napi_create_string_utf8(env, module.c_str(), NAPI_AUTO_LENGTH, &filename_prop); + napi_create_string_utf8(env, module.c_str(), NAPI_AUTO_LENGTH, + &filename_prop); napi_set_named_property(env, js_node, "module", filename_prop); } } @@ -504,8 +538,9 @@ napi_value CreateFrameNode(const napi_env& env, const v8::CpuProfileNode& node, return js_node; }; - -napi_value CreateSample(const napi_env& env, const uint32_t stack_id, const int64_t sample_timestamp_us, const uint32_t thread_id) { +napi_value CreateSample(const napi_env &env, const uint32_t stack_id, + const int64_t sample_timestamp_us, + const uint32_t thread_id) { napi_value js_node; napi_create_object(env, &js_node); @@ -514,18 +549,22 @@ napi_value CreateSample(const napi_env& env, const uint32_t stack_id, const int6 napi_set_named_property(env, js_node, "stack_id", stack_id_prop); napi_value thread_id_prop; - napi_create_string_utf8(env, std::to_string(thread_id).c_str(), NAPI_AUTO_LENGTH, &thread_id_prop); + napi_create_string_utf8(env, std::to_string(thread_id).c_str(), + NAPI_AUTO_LENGTH, &thread_id_prop); napi_set_named_property(env, js_node, "thread_id", thread_id_prop); napi_value elapsed_since_start_ns_prop; - napi_create_int64(env, sample_timestamp_us * 1000, &elapsed_since_start_ns_prop); - napi_set_named_property(env, js_node, "elapsed_since_start_ns", elapsed_since_start_ns_prop); + napi_create_int64(env, sample_timestamp_us * 1000, + &elapsed_since_start_ns_prop); + napi_set_named_property(env, js_node, "elapsed_since_start_ns", + elapsed_since_start_ns_prop); return js_node; }; std::string kDelimiter = std::string(";"); -std::string hashCpuProfilerNodeByPath(const v8::CpuProfileNode* node, std::string& path) { +std::string hashCpuProfilerNodeByPath(const v8::CpuProfileNode *node, + std::string &path) { path.clear(); while (node != nullptr) { @@ -536,15 +575,18 @@ std::string hashCpuProfilerNodeByPath(const v8::CpuProfileNode* node, std::strin return path; } -static void GetSamples(const napi_env& env, const v8::CpuProfile* profile, const uint32_t thread_id, napi_value& samples, napi_value& stacks, napi_value& frames, napi_value& resources) { +static void GetSamples(const napi_env &env, const v8::CpuProfile *profile, + const uint32_t thread_id, napi_value &samples, + napi_value &stacks, napi_value &frames, + napi_value &resources) { const int64_t profile_start_time_us = profile->GetStartTime(); const int sampleCount = profile->GetSamplesCount(); uint32_t unique_stack_id = 0; uint32_t unique_frame_id = 0; - // Initialize the lookup tables for stacks and frames, both of these are indexed - // in the sample format we are using to optimize for size. + // Initialize the lookup tables for stacks and frames, both of these are + // indexed in the sample format we are using to optimize for size. std::unordered_map frame_lookup_table; std::unordered_map stack_lookup_table; std::unordered_map module_cache; @@ -557,27 +599,28 @@ static void GetSamples(const napi_env& env, const v8::CpuProfile* profile, const for (int i = 0; i < sampleCount; i++) { uint32_t stack_index = unique_stack_id; - const v8::CpuProfileNode* node = profile->GetSample(i); + const v8::CpuProfileNode *node = profile->GetSample(i); const int64_t sample_timestamp = profile->GetSampleTimestamp(i); - // If a node was only on top of the stack once, then it will only ever + // If a node was only on top of the stack once, then it will only ever // be inserted once and there is no need for hashing. if (node->GetHitCount() > 1) { hashCpuProfilerNodeByPath(node, node_hash); - std::unordered_map::iterator stack_index_cache_hit = stack_lookup_table.find(node_hash); + std::unordered_map::iterator + stack_index_cache_hit = stack_lookup_table.find(node_hash); // If we have a hit, update the stack index, otherwise // insert it into the hash table and continue. if (stack_index_cache_hit == stack_lookup_table.end()) { stack_lookup_table.emplace(node_hash, stack_index); - } - else { + } else { stack_index = stack_index_cache_hit->second; } } - napi_value sample = CreateSample(env, stack_index, sample_timestamp - profile_start_time_us, thread_id); + napi_value sample = CreateSample( + env, stack_index, sample_timestamp - profile_start_time_us, thread_id); if (stack_index != unique_stack_id) { napi_value index; @@ -586,7 +629,8 @@ static void GetSamples(const napi_env& env, const v8::CpuProfile* profile, const continue; } - // A stack is a list of frames ordered from outermost (top) to innermost frame (bottom) + // A stack is a list of frames ordered from outermost (top) to innermost + // frame (bottom) napi_value stack; napi_create_array(env, &stack); @@ -606,11 +650,11 @@ static void GetSamples(const napi_env& env, const v8::CpuProfile* profile, const napi_value depth; napi_create_uint32(env, stack_depth, &depth); napi_set_property(env, stack, depth, frame_id); - napi_set_property(env, frames, frame_id, CreateFrameNode(env, *node, module_cache, resources)); + napi_set_property(env, frames, frame_id, + CreateFrameNode(env, *node, module_cache, resources)); unique_frame_id++; - } - else { + } else { // If it was already indexed, just add it's id to the stack napi_value depth; napi_create_uint32(env, stack_depth, &depth); @@ -637,14 +681,22 @@ static void GetSamples(const napi_env& env, const v8::CpuProfile* profile, const } } -static napi_value TranslateMeasurementsDouble(const napi_env& env, const char* unit, const uint16_t size, const std::vector& values, const std::vector& timestamps) { +static napi_value +TranslateMeasurementsDouble(const napi_env &env, const char *unit, + const uint16_t size, + const std::vector &values, + const std::vector ×tamps) { if (size > values.size() || size > timestamps.size()) { - napi_throw_range_error(env, "NAPI_ERROR", "CPU measurement size is larger than the number of values or timestamps"); + napi_throw_range_error(env, "NAPI_ERROR", + "CPU measurement size is larger than the number of " + "values or timestamps"); return nullptr; } if (values.size() != timestamps.size()) { - napi_throw_range_error(env, "NAPI_ERROR", "CPU measurement entries are corrupt, expected values and timestamps to be of equal length"); + napi_throw_range_error(env, "NAPI_ERROR", + "CPU measurement entries are corrupt, expected " + "values and timestamps to be of equal length"); return nullptr; } @@ -665,8 +717,8 @@ static napi_value TranslateMeasurementsDouble(const napi_env& env, const char* u napi_create_object(env, &entry); napi_value value; - if(napi_create_double(env, values[i], &value) != napi_ok){ - if(napi_create_double(env, 0.0, &value) != napi_ok){ + if (napi_create_double(env, values[i], &value) != napi_ok) { + if (napi_create_double(env, 0.0, &value) != napi_ok) { continue; } } @@ -684,14 +736,21 @@ static napi_value TranslateMeasurementsDouble(const napi_env& env, const char* u return measurement; } -static napi_value TranslateMeasurements(const napi_env& env, const char* unit, const uint16_t size, const std::vector& values, const std::vector& timestamps) { +static napi_value +TranslateMeasurements(const napi_env &env, const char *unit, + const uint16_t size, const std::vector &values, + const std::vector ×tamps) { if (size > values.size() || size > timestamps.size()) { - napi_throw_range_error(env, "NAPI_ERROR", "Memory measurement size is larger than the number of values or timestamps"); + napi_throw_range_error(env, "NAPI_ERROR", + "Memory measurement size is larger than the number " + "of values or timestamps"); return nullptr; } if (values.size() != timestamps.size()) { - napi_throw_range_error(env, "NAPI_ERROR", "Memory measurement entries are corrupt, expected values and timestamps to be of equal length"); + napi_throw_range_error(env, "NAPI_ERROR", + "Memory measurement entries are corrupt, expected " + "values and timestamps to be of equal length"); return nullptr; } @@ -725,7 +784,10 @@ static napi_value TranslateMeasurements(const napi_env& env, const char* unit, c return measurement; } -static napi_value TranslateProfile(const napi_env& env, const v8::CpuProfile* profile, const uint32_t thread_id, bool collect_resources) { +static napi_value TranslateProfile(const napi_env &env, + const v8::CpuProfile *profile, + const uint32_t thread_id, + bool collect_resources) { napi_value js_profile; napi_create_object(env, &js_profile); @@ -736,7 +798,11 @@ static napi_value TranslateProfile(const napi_env& env, const v8::CpuProfile* pr napi_value frames; napi_value resources; - napi_create_string_utf8(env, GetLoggingMode() == v8::CpuProfilingLoggingMode::kEagerLogging ? "eager" : "lazy", NAPI_AUTO_LENGTH, &logging_mode); + napi_create_string_utf8( + env, + GetLoggingMode() == v8::CpuProfilingLoggingMode::kEagerLogging ? "eager" + : "lazy", + NAPI_AUTO_LENGTH, &logging_mode); napi_create_array(env, &samples); napi_create_array(env, &stacks); @@ -746,14 +812,14 @@ static napi_value TranslateProfile(const napi_env& env, const v8::CpuProfile* pr napi_set_named_property(env, js_profile, "samples", samples); napi_set_named_property(env, js_profile, "stacks", stacks); napi_set_named_property(env, js_profile, "frames", frames); - napi_set_named_property(env, js_profile, "profiler_logging_mode", logging_mode); + napi_set_named_property(env, js_profile, "profiler_logging_mode", + logging_mode); GetSamples(env, profile, thread_id, samples, stacks, frames, resources); if (collect_resources) { napi_set_named_property(env, js_profile, "resources", resources); - } - else { + } else { napi_create_array(env, &resources); napi_set_named_property(env, js_profile, "resources", resources); } @@ -771,7 +837,9 @@ static napi_value StartProfiling(napi_env env, napi_callback_info info) { assert(napi_typeof(env, argv[0], &callbacktype0) == napi_ok); if (callbacktype0 != napi_string) { - napi_throw_error(env, "NAPI_ERROR", "TypeError: StartProfiling expects a string as first argument."); + napi_throw_error( + env, "NAPI_ERROR", + "TypeError: StartProfiling expects a string as first argument."); napi_value napi_null; assert(napi_get_null(env, &napi_null) == napi_ok); @@ -781,11 +849,14 @@ static napi_value StartProfiling(napi_env env, napi_callback_info info) { size_t len; assert(napi_get_value_string_utf8(env, argv[0], NULL, 0, &len) == napi_ok); - char* title = (char*)malloc(len + 1); - assert(napi_get_value_string_utf8(env, argv[0], title, len + 1, &len) == napi_ok); + char *title = (char *)malloc(len + 1); + assert(napi_get_value_string_utf8(env, argv[0], title, len + 1, &len) == + napi_ok); if (len < 1) { - napi_throw_error(env, "NAPI_ERROR", "StartProfiling expects a non-empty string as first argument, got an empty string."); + napi_throw_error(env, "NAPI_ERROR", + "StartProfiling expects a non-empty string as first " + "argument, got an empty string."); napi_value napi_null; assert(napi_get_null(env, &napi_null) == napi_ok); @@ -793,14 +864,15 @@ static napi_value StartProfiling(napi_env env, napi_callback_info info) { return napi_null; } - v8::Isolate* isolate = v8::Isolate::GetCurrent(); + v8::Isolate *isolate = v8::Isolate::GetCurrent(); assert(isolate != 0); - Profiler* profiler; - assert(napi_get_instance_data(env, (void**)&profiler) == napi_ok); + Profiler *profiler; + assert(napi_get_instance_data(env, (void **)&profiler) == napi_ok); if (!profiler) { - napi_throw_error(env, "NAPI_ERROR", "StartProfiling: Profiler is not initialized."); + napi_throw_error(env, "NAPI_ERROR", + "StartProfiling: Profiler is not initialized."); napi_value napi_null; assert(napi_get_null(env, &napi_null) == napi_ok); @@ -816,7 +888,7 @@ static napi_value StartProfiling(napi_env env, napi_callback_info info) { CleanupSentryProfile(profiler, existing_profile->second, profile_id); } - SentryProfile* sentry_profile = new SentryProfile(title); + SentryProfile *sentry_profile = new SentryProfile(title); sentry_profile->Start(profiler); profiler->active_profiles.emplace(profile_id, sentry_profile); @@ -836,7 +908,8 @@ static napi_value StopProfiling(napi_env env, napi_callback_info info) { assert(napi_get_cb_info(env, info, &argc, argv, NULL, NULL) == napi_ok); if (argc < 2) { - napi_throw_error(env, "NAPI_ERROR", "StopProfiling expects at least two arguments."); + napi_throw_error(env, "NAPI_ERROR", + "StopProfiling expects at least two arguments."); napi_value napi_null; assert(napi_get_null(env, &napi_null) == napi_ok); @@ -849,7 +922,8 @@ static napi_value StopProfiling(napi_env env, napi_callback_info info) { assert(napi_typeof(env, argv[0], &callbacktype0) == napi_ok); if (callbacktype0 != napi_string) { - napi_throw_error(env, "NAPI_ERROR", "StopProfiling expects a string as first argument."); + napi_throw_error(env, "NAPI_ERROR", + "StopProfiling expects a string as first argument."); napi_value napi_null; assert(napi_get_null(env, &napi_null) == napi_ok); @@ -862,7 +936,9 @@ static napi_value StopProfiling(napi_env env, napi_callback_info info) { assert(napi_typeof(env, argv[1], &callbacktype1) == napi_ok); if (callbacktype1 != napi_number) { - napi_throw_error(env, "NAPI_ERROR", "StopProfiling expects a thread_id integer as second argument."); + napi_throw_error( + env, "NAPI_ERROR", + "StopProfiling expects a thread_id integer as second argument."); napi_value napi_null; assert(napi_get_null(env, &napi_null) == napi_ok); @@ -873,11 +949,13 @@ static napi_value StopProfiling(napi_env env, napi_callback_info info) { size_t len; assert(napi_get_value_string_utf8(env, argv[0], NULL, 0, &len) == napi_ok); - char* title = (char*)malloc(len + 1); - assert(napi_get_value_string_utf8(env, argv[0], title, len + 1, &len) == napi_ok); + char *title = (char *)malloc(len + 1); + assert(napi_get_value_string_utf8(env, argv[0], title, len + 1, &len) == + napi_ok); if (len < 1) { - napi_throw_error(env, "NAPI_ERROR", "StopProfiling expects a string as first argument."); + napi_throw_error(env, "NAPI_ERROR", + "StopProfiling expects a string as first argument."); napi_value napi_null; assert(napi_get_null(env, &napi_null) == napi_ok); @@ -889,13 +967,13 @@ static napi_value StopProfiling(napi_env env, napi_callback_info info) { int64_t thread_id; assert(napi_get_value_int64(env, argv[1], &thread_id) == napi_ok); - // Get profiler from instance data - Profiler* profiler; - assert(napi_get_instance_data(env, (void**)&profiler) == napi_ok); + Profiler *profiler; + assert(napi_get_instance_data(env, (void **)&profiler) == napi_ok); if (!profiler) { - napi_throw_error(env, "NAPI_ERROR", "StopProfiling: Profiler is not initialized."); + napi_throw_error(env, "NAPI_ERROR", + "StopProfiling: Profiler is not initialized."); napi_value napi_null; assert(napi_get_null(env, &napi_null) == napi_ok); @@ -913,10 +991,10 @@ static napi_value StopProfiling(napi_env env, napi_callback_info info) { return napi_null; } - v8::CpuProfile* cpu_profile = profile->second->Stop(profiler); + v8::CpuProfile *cpu_profile = profile->second->Stop(profiler); - // If for some reason stopProfiling was called with an invalid profile title or - // if that title had somehow been stopped already, profile will be null. + // If for some reason stopProfiling was called with an invalid profile title + // or if that title had somehow been stopped already, profile will be null. if (!cpu_profile) { CleanupSentryProfile(profiler, profile->second, profile_id); @@ -925,33 +1003,41 @@ static napi_value StopProfiling(napi_env env, napi_callback_info info) { return napi_null; }; - napi_valuetype callbacktype3; assert(napi_typeof(env, argv[2], &callbacktype3) == napi_ok); bool collect_resources; napi_get_value_bool(env, argv[2], &collect_resources); - napi_value js_profile = TranslateProfile(env, cpu_profile, thread_id, collect_resources); + napi_value js_profile = + TranslateProfile(env, cpu_profile, thread_id, collect_resources); napi_value measurements; napi_create_object(env, &measurements); - if(profile->second->heap_usage_write_index() > 0){ - static const char* memory_unit = "byte"; - napi_value heap_usage_measurements = TranslateMeasurements(env, memory_unit, profile->second->heap_usage_write_index(), profile->second->heap_usage_values(), profile->second->heap_usage_timestamps()); + if (profile->second->heap_usage_write_index() > 0) { + static const char *memory_unit = "byte"; + napi_value heap_usage_measurements = TranslateMeasurements( + env, memory_unit, profile->second->heap_usage_write_index(), + profile->second->heap_usage_values(), + profile->second->heap_usage_timestamps()); if (heap_usage_measurements != nullptr) { - napi_set_named_property(env, measurements, "memory_footprint", heap_usage_measurements); + napi_set_named_property(env, measurements, "memory_footprint", + heap_usage_measurements); }; }; - if(profile->second->cpu_usage_write_index() > 0){ - static const char* cpu_unit = "percent"; - napi_value cpu_usage_measurements = TranslateMeasurementsDouble(env, cpu_unit, profile->second->cpu_usage_write_index(), profile->second->cpu_usage_values(), profile->second->cpu_usage_timestamps()); + if (profile->second->cpu_usage_write_index() > 0) { + static const char *cpu_unit = "percent"; + napi_value cpu_usage_measurements = TranslateMeasurementsDouble( + env, cpu_unit, profile->second->cpu_usage_write_index(), + profile->second->cpu_usage_values(), + profile->second->cpu_usage_timestamps()); if (cpu_usage_measurements != nullptr) { - napi_set_named_property(env, measurements, "cpu_usage", cpu_usage_measurements); + napi_set_named_property(env, measurements, "cpu_usage", + cpu_usage_measurements); }; }; @@ -964,14 +1050,15 @@ static napi_value StopProfiling(napi_env env, napi_callback_info info) { }; napi_value Init(napi_env env, napi_value exports) { - v8::Isolate* isolate = v8::Isolate::GetCurrent(); + v8::Isolate *isolate = v8::Isolate::GetCurrent(); if (isolate == nullptr) { - napi_throw_error(env, nullptr, "Failed to initialize Sentry profiler: isolate is null."); + napi_throw_error(env, nullptr, + "Failed to initialize Sentry profiler: isolate is null."); return NULL; } - Profiler* profiler = new Profiler(env, isolate); + Profiler *profiler = new Profiler(env, isolate); if (napi_set_instance_data(env, profiler, NULL, NULL) != napi_ok) { napi_throw_error(env, nullptr, "Failed to set instance data for profiler."); @@ -979,41 +1066,55 @@ napi_value Init(napi_env env, napi_value exports) { } napi_value external; - if (napi_create_external(env, profiler, nullptr, nullptr, &external) != napi_ok) { - napi_throw_error(env, nullptr, "Failed to create external for profiler instance."); + if (napi_create_external(env, profiler, nullptr, nullptr, &external) != + napi_ok) { + napi_throw_error(env, nullptr, + "Failed to create external for profiler instance."); return NULL; } napi_value start_profiling; - if (napi_create_function(env, "startProfiling", NAPI_AUTO_LENGTH, StartProfiling, external, &start_profiling) != napi_ok) { + if (napi_create_function(env, "startProfiling", NAPI_AUTO_LENGTH, + StartProfiling, external, + &start_profiling) != napi_ok) { napi_throw_error(env, nullptr, "Failed to create startProfiling function."); return NULL; } - if (napi_set_named_property(env, exports, "startProfiling", start_profiling) != napi_ok) { - napi_throw_error(env, nullptr, "Failed to set startProfiling property on exports."); + if (napi_set_named_property(env, exports, "startProfiling", + start_profiling) != napi_ok) { + napi_throw_error(env, nullptr, + "Failed to set startProfiling property on exports."); return NULL; } napi_value stop_profiling; - if (napi_create_function(env, "stopProfiling", NAPI_AUTO_LENGTH, StopProfiling, external, &stop_profiling) != napi_ok) { + if (napi_create_function(env, "stopProfiling", NAPI_AUTO_LENGTH, + StopProfiling, external, + &stop_profiling) != napi_ok) { napi_throw_error(env, nullptr, "Failed to create stopProfiling function."); return NULL; } - if (napi_set_named_property(env, exports, "stopProfiling", stop_profiling) != napi_ok) { - napi_throw_error(env, nullptr, "Failed to set stopProfiling property on exports."); + if (napi_set_named_property(env, exports, "stopProfiling", stop_profiling) != + napi_ok) { + napi_throw_error(env, nullptr, + "Failed to set stopProfiling property on exports."); return NULL; } napi_value get_frame_module; - if (napi_create_function(env, "getFrameModule", NAPI_AUTO_LENGTH, GetFrameModuleWrapped, external, &get_frame_module) != napi_ok) { + if (napi_create_function(env, "getFrameModule", NAPI_AUTO_LENGTH, + GetFrameModuleWrapped, external, + &get_frame_module) != napi_ok) { napi_throw_error(env, nullptr, "Failed to create getFrameModule function."); return NULL; } - if (napi_set_named_property(env, exports, "getFrameModule", get_frame_module) != napi_ok) { - napi_throw_error(env, nullptr, "Failed to set getFrameModule property on exports."); + if (napi_set_named_property(env, exports, "getFrameModule", + get_frame_module) != napi_ok) { + napi_throw_error(env, nullptr, + "Failed to set getFrameModule property on exports."); return NULL; } From 76aa575efe46fa7f3c1c89cd9fd6e3efd03b5760 Mon Sep 17 00:00:00 2001 From: JonasBa Date: Tue, 5 Dec 2023 18:54:02 -0500 Subject: [PATCH 3/8] format: format bindings --- .github/workflows/ci.yml | 1 + package.json | 1 + 2 files changed, 2 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c213ab1c..1b909fa1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,6 +13,7 @@ jobs: - uses: actions/setup-node@v2 - run: npm ci - run: npm run lint + - run: npm run format:clang:check build-test-matrix: strategy: fail-fast: false diff --git a/package.json b/package.json index 92a2efac..dd28859c 100644 --- a/package.json +++ b/package.json @@ -34,6 +34,7 @@ "format": "npm run format:prettier && npm run format:clang", "format:prettier": "prettier --config ./.prettierrc --write", "format:clang": "clang-format -i ./**/*.cc", + "format:clang:check": "check-clang-format -i ./**/*.cc", "build": "npm run build:bindings && npm run build:lib", "build:lib:esm": "node ./esbuild.esm.mjs", "build:lib:cjs": "node ./esbuild.cjs.mjs", From 8b46c805325e35846f8800f5049af95e6f8d86ca Mon Sep 17 00:00:00 2001 From: JonasBa Date: Tue, 5 Dec 2023 19:28:09 -0500 Subject: [PATCH 4/8] format: export file --- .clang-format | 250 ++++++++++++++++++++++++++++++++++++++++++++++++++ package.json | 5 +- 2 files changed, 253 insertions(+), 2 deletions(-) create mode 100644 .clang-format diff --git a/.clang-format b/.clang-format new file mode 100644 index 00000000..b9f78775 --- /dev/null +++ b/.clang-format @@ -0,0 +1,250 @@ +--- +Language: Cpp +# BasedOnStyle: Google +AccessModifierOffset: -1 +AlignAfterOpenBracket: Align +AlignArrayOfStructures: None +AlignConsecutiveAssignments: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + PadOperators: true +AlignConsecutiveBitFields: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + PadOperators: false +AlignConsecutiveDeclarations: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + PadOperators: false +AlignConsecutiveMacros: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + PadOperators: false +AlignEscapedNewlines: Left +AlignOperands: Align +AlignTrailingComments: true +AllowAllArgumentsOnNextLine: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowShortEnumsOnASingleLine: true +AllowShortBlocksOnASingleLine: Never +AllowShortCaseLabelsOnASingleLine: false +AllowShortFunctionsOnASingleLine: All +AllowShortLambdasOnASingleLine: All +AllowShortIfStatementsOnASingleLine: WithoutElse +AllowShortLoopsOnASingleLine: true +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: true +AlwaysBreakTemplateDeclarations: Yes +AttributeMacros: + - __capability +BinPackArguments: true +BinPackParameters: true +BraceWrapping: + AfterCaseLabel: false + AfterClass: false + AfterControlStatement: Never + AfterEnum: false + AfterFunction: false + AfterNamespace: false + AfterObjCDeclaration: false + AfterStruct: false + AfterUnion: false + AfterExternBlock: false + BeforeCatch: false + BeforeElse: false + BeforeLambdaBody: false + BeforeWhile: false + IndentBraces: false + SplitEmptyFunction: true + SplitEmptyRecord: true + SplitEmptyNamespace: true +BreakBeforeBinaryOperators: None +BreakBeforeConceptDeclarations: Always +BreakBeforeBraces: Attach +BreakBeforeInheritanceComma: false +BreakInheritanceList: BeforeColon +BreakBeforeTernaryOperators: true +BreakConstructorInitializersBeforeComma: false +BreakConstructorInitializers: BeforeColon +BreakAfterJavaFieldAnnotations: false +BreakStringLiterals: true +ColumnLimit: 80 +CommentPragmas: '^ IWYU pragma:' +QualifierAlignment: Leave +CompactNamespaces: false +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: true +DeriveLineEnding: true +DerivePointerAlignment: true +DisableFormat: false +EmptyLineAfterAccessModifier: Never +EmptyLineBeforeAccessModifier: LogicalBlock +ExperimentalAutoDetectBinPacking: false +PackConstructorInitializers: NextLine +BasedOnStyle: '' +ConstructorInitializerAllOnOneLineOrOnePerLine: false +AllowAllConstructorInitializersOnNextLine: true +FixNamespaceComments: true +ForEachMacros: + - foreach + - Q_FOREACH + - BOOST_FOREACH +IfMacros: + - KJ_IF_MAYBE +IncludeBlocks: Regroup +IncludeCategories: + - Regex: '^' + Priority: 2 + SortPriority: 0 + CaseSensitive: false + - Regex: '^<.*\.h>' + Priority: 1 + SortPriority: 0 + CaseSensitive: false + - Regex: '^<.*' + Priority: 2 + SortPriority: 0 + CaseSensitive: false + - Regex: '.*' + Priority: 3 + SortPriority: 0 + CaseSensitive: false +IncludeIsMainRegex: '([-_](test|unittest))?$' +IncludeIsMainSourceRegex: '' +IndentAccessModifiers: false +IndentCaseLabels: true +IndentCaseBlocks: false +IndentGotoLabels: true +IndentPPDirectives: None +IndentExternBlock: AfterExternBlock +IndentRequiresClause: true +IndentWidth: 2 +IndentWrappedFunctionNames: false +InsertBraces: false +InsertTrailingCommas: None +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLinesAtTheStartOfBlocks: false +LambdaBodyIndentation: Signature +MacroBlockBegin: '' +MacroBlockEnd: '' +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: None +ObjCBinPackProtocolList: Never +ObjCBlockIndentWidth: 2 +ObjCBreakBeforeNestedBlockParam: true +ObjCSpaceAfterProperty: false +ObjCSpaceBeforeProtocolList: true +PenaltyBreakAssignment: 2 +PenaltyBreakBeforeFirstCallParameter: 1 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakOpenParenthesis: 0 +PenaltyBreakString: 1000 +PenaltyBreakTemplateDeclaration: 10 +PenaltyExcessCharacter: 1000000 +PenaltyReturnTypeOnItsOwnLine: 200 +PenaltyIndentedWhitespace: 0 +PointerAlignment: Left +PPIndentWidth: -1 +RawStringFormats: + - Language: Cpp + Delimiters: + - cc + - CC + - cpp + - Cpp + - CPP + - 'c++' + - 'C++' + CanonicalDelimiter: '' + BasedOnStyle: google + - Language: TextProto + Delimiters: + - pb + - PB + - proto + - PROTO + EnclosingFunctions: + - EqualsProto + - EquivToProto + - PARSE_PARTIAL_TEXT_PROTO + - PARSE_TEST_PROTO + - PARSE_TEXT_PROTO + - ParseTextOrDie + - ParseTextProtoOrDie + - ParseTestProto + - ParsePartialTestProto + CanonicalDelimiter: pb + BasedOnStyle: google +ReferenceAlignment: Pointer +ReflowComments: true +RemoveBracesLLVM: false +RequiresClausePosition: OwnLine +SeparateDefinitionBlocks: Leave +ShortNamespaceLines: 1 +SortIncludes: CaseSensitive +SortJavaStaticImport: Before +SortUsingDeclarations: true +SpaceAfterCStyleCast: false +SpaceAfterLogicalNot: false +SpaceAfterTemplateKeyword: true +SpaceBeforeAssignmentOperators: true +SpaceBeforeCaseColon: false +SpaceBeforeCpp11BracedList: false +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeParens: ControlStatements +SpaceBeforeParensOptions: + AfterControlStatements: true + AfterForeachMacros: true + AfterFunctionDefinitionName: false + AfterFunctionDeclarationName: false + AfterIfMacros: true + AfterOverloadedOperator: false + AfterRequiresInClause: false + AfterRequiresInExpression: false + BeforeNonEmptyParentheses: false +SpaceAroundPointerQualifiers: Default +SpaceBeforeRangeBasedForLoopColon: true +SpaceInEmptyBlock: false +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 2 +SpacesInAngles: Never +SpacesInConditionalStatement: false +SpacesInContainerLiterals: true +SpacesInCStyleCastParentheses: false +SpacesInLineCommentPrefix: + Minimum: 1 + Maximum: -1 +SpacesInParentheses: false +SpacesInSquareBrackets: false +SpaceBeforeSquareBrackets: false +BitFieldColonSpacing: Both +Standard: Auto +StatementAttributeLikeMacros: + - Q_EMIT +StatementMacros: + - Q_UNUSED + - QT_REQUIRE_VERSION +TabWidth: 8 +UseCRLF: false +UseTab: Never +WhitespaceSensitiveMacros: + - STRINGIZE + - PP_STRINGIZE + - BOOST_PP_STRINGIZE + - NS_SWIFT_NAME + - CF_SWIFT_NAME +... + diff --git a/package.json b/package.json index dd28859c..80e0f862 100644 --- a/package.json +++ b/package.json @@ -33,8 +33,9 @@ "lint": "eslint ./src --ext .ts", "format": "npm run format:prettier && npm run format:clang", "format:prettier": "prettier --config ./.prettierrc --write", - "format:clang": "clang-format -i ./**/*.cc", - "format:clang:check": "check-clang-format -i ./**/*.cc", + "format:clang": "clang-format --style=file -i ./**/*.cc ", + "format:clang:export": "clang-format --style=google -dump-config > .clang-format", + "format:clang:check": "./node_modules/.bin/", "build": "npm run build:bindings && npm run build:lib", "build:lib:esm": "node ./esbuild.esm.mjs", "build:lib:cjs": "node ./esbuild.cjs.mjs", From f435fb66e04b7f65f4a7b625b854dde957825c8a Mon Sep 17 00:00:00 2001 From: JonasBa Date: Tue, 5 Dec 2023 19:29:23 -0500 Subject: [PATCH 5/8] format: run bin --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 80e0f862..ec4a09af 100644 --- a/package.json +++ b/package.json @@ -35,7 +35,7 @@ "format:prettier": "prettier --config ./.prettierrc --write", "format:clang": "clang-format --style=file -i ./**/*.cc ", "format:clang:export": "clang-format --style=google -dump-config > .clang-format", - "format:clang:check": "./node_modules/.bin/", + "format:clang:check": "./node_modules/.bin/check-clang-format --style=file", "build": "npm run build:bindings && npm run build:lib", "build:lib:esm": "node ./esbuild.esm.mjs", "build:lib:cjs": "node ./esbuild.cjs.mjs", From fd24ea93419549d54354a188ee7e6a5bc486c9dc Mon Sep 17 00:00:00 2001 From: JonasBa Date: Tue, 5 Dec 2023 19:31:43 -0500 Subject: [PATCH 6/8] format: run bin --- .github/workflows/ci.yml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1b909fa1..de2483e6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,7 +13,11 @@ jobs: - uses: actions/setup-node@v2 - run: npm ci - run: npm run lint - - run: npm run format:clang:check + - run: | + git config clangFormat.binary node_modules/.bin/clang-format + git config clangFormat.style file + npm run format:clang:check + build-test-matrix: strategy: fail-fast: false From 64811c2bf3272faf83ea7c65ba923460226f166b Mon Sep 17 00:00:00 2001 From: JonasBa Date: Tue, 5 Dec 2023 20:43:36 -0500 Subject: [PATCH 7/8] format: use node modules bin --- package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index ec4a09af..567ba2d5 100644 --- a/package.json +++ b/package.json @@ -33,8 +33,8 @@ "lint": "eslint ./src --ext .ts", "format": "npm run format:prettier && npm run format:clang", "format:prettier": "prettier --config ./.prettierrc --write", - "format:clang": "clang-format --style=file -i ./**/*.cc ", - "format:clang:export": "clang-format --style=google -dump-config > .clang-format", + "format:clang": "./node_modules/.bin/clang-format --style=file -i ./**/*.cc ", + "format:clang:export": "./node_modules/.bin/clang-format --style=google -dump-config > .clang-format", "format:clang:check": "./node_modules/.bin/check-clang-format --style=file", "build": "npm run build:bindings && npm run build:lib", "build:lib:esm": "node ./esbuild.esm.mjs", From e75ec69eadf1409ad4d2a1550484e6c3c7be4782 Mon Sep 17 00:00:00 2001 From: JonasBa Date: Thu, 7 Dec 2023 09:32:25 -0500 Subject: [PATCH 8/8] clang-format cleanup template --- .clang-format | 252 +------------------------------------------------- 1 file changed, 2 insertions(+), 250 deletions(-) diff --git a/.clang-format b/.clang-format index b9f78775..2bd8588a 100644 --- a/.clang-format +++ b/.clang-format @@ -1,250 +1,2 @@ ---- -Language: Cpp -# BasedOnStyle: Google -AccessModifierOffset: -1 -AlignAfterOpenBracket: Align -AlignArrayOfStructures: None -AlignConsecutiveAssignments: - Enabled: false - AcrossEmptyLines: false - AcrossComments: false - AlignCompound: false - PadOperators: true -AlignConsecutiveBitFields: - Enabled: false - AcrossEmptyLines: false - AcrossComments: false - AlignCompound: false - PadOperators: false -AlignConsecutiveDeclarations: - Enabled: false - AcrossEmptyLines: false - AcrossComments: false - AlignCompound: false - PadOperators: false -AlignConsecutiveMacros: - Enabled: false - AcrossEmptyLines: false - AcrossComments: false - AlignCompound: false - PadOperators: false -AlignEscapedNewlines: Left -AlignOperands: Align -AlignTrailingComments: true -AllowAllArgumentsOnNextLine: true -AllowAllParametersOfDeclarationOnNextLine: true -AllowShortEnumsOnASingleLine: true -AllowShortBlocksOnASingleLine: Never -AllowShortCaseLabelsOnASingleLine: false -AllowShortFunctionsOnASingleLine: All -AllowShortLambdasOnASingleLine: All -AllowShortIfStatementsOnASingleLine: WithoutElse -AllowShortLoopsOnASingleLine: true -AlwaysBreakAfterDefinitionReturnType: None -AlwaysBreakAfterReturnType: None -AlwaysBreakBeforeMultilineStrings: true -AlwaysBreakTemplateDeclarations: Yes -AttributeMacros: - - __capability -BinPackArguments: true -BinPackParameters: true -BraceWrapping: - AfterCaseLabel: false - AfterClass: false - AfterControlStatement: Never - AfterEnum: false - AfterFunction: false - AfterNamespace: false - AfterObjCDeclaration: false - AfterStruct: false - AfterUnion: false - AfterExternBlock: false - BeforeCatch: false - BeforeElse: false - BeforeLambdaBody: false - BeforeWhile: false - IndentBraces: false - SplitEmptyFunction: true - SplitEmptyRecord: true - SplitEmptyNamespace: true -BreakBeforeBinaryOperators: None -BreakBeforeConceptDeclarations: Always -BreakBeforeBraces: Attach -BreakBeforeInheritanceComma: false -BreakInheritanceList: BeforeColon -BreakBeforeTernaryOperators: true -BreakConstructorInitializersBeforeComma: false -BreakConstructorInitializers: BeforeColon -BreakAfterJavaFieldAnnotations: false -BreakStringLiterals: true -ColumnLimit: 80 -CommentPragmas: '^ IWYU pragma:' -QualifierAlignment: Leave -CompactNamespaces: false -ConstructorInitializerIndentWidth: 4 -ContinuationIndentWidth: 4 -Cpp11BracedListStyle: true -DeriveLineEnding: true -DerivePointerAlignment: true -DisableFormat: false -EmptyLineAfterAccessModifier: Never -EmptyLineBeforeAccessModifier: LogicalBlock -ExperimentalAutoDetectBinPacking: false -PackConstructorInitializers: NextLine -BasedOnStyle: '' -ConstructorInitializerAllOnOneLineOrOnePerLine: false -AllowAllConstructorInitializersOnNextLine: true -FixNamespaceComments: true -ForEachMacros: - - foreach - - Q_FOREACH - - BOOST_FOREACH -IfMacros: - - KJ_IF_MAYBE -IncludeBlocks: Regroup -IncludeCategories: - - Regex: '^' - Priority: 2 - SortPriority: 0 - CaseSensitive: false - - Regex: '^<.*\.h>' - Priority: 1 - SortPriority: 0 - CaseSensitive: false - - Regex: '^<.*' - Priority: 2 - SortPriority: 0 - CaseSensitive: false - - Regex: '.*' - Priority: 3 - SortPriority: 0 - CaseSensitive: false -IncludeIsMainRegex: '([-_](test|unittest))?$' -IncludeIsMainSourceRegex: '' -IndentAccessModifiers: false -IndentCaseLabels: true -IndentCaseBlocks: false -IndentGotoLabels: true -IndentPPDirectives: None -IndentExternBlock: AfterExternBlock -IndentRequiresClause: true -IndentWidth: 2 -IndentWrappedFunctionNames: false -InsertBraces: false -InsertTrailingCommas: None -JavaScriptQuotes: Leave -JavaScriptWrapImports: true -KeepEmptyLinesAtTheStartOfBlocks: false -LambdaBodyIndentation: Signature -MacroBlockBegin: '' -MacroBlockEnd: '' -MaxEmptyLinesToKeep: 1 -NamespaceIndentation: None -ObjCBinPackProtocolList: Never -ObjCBlockIndentWidth: 2 -ObjCBreakBeforeNestedBlockParam: true -ObjCSpaceAfterProperty: false -ObjCSpaceBeforeProtocolList: true -PenaltyBreakAssignment: 2 -PenaltyBreakBeforeFirstCallParameter: 1 -PenaltyBreakComment: 300 -PenaltyBreakFirstLessLess: 120 -PenaltyBreakOpenParenthesis: 0 -PenaltyBreakString: 1000 -PenaltyBreakTemplateDeclaration: 10 -PenaltyExcessCharacter: 1000000 -PenaltyReturnTypeOnItsOwnLine: 200 -PenaltyIndentedWhitespace: 0 -PointerAlignment: Left -PPIndentWidth: -1 -RawStringFormats: - - Language: Cpp - Delimiters: - - cc - - CC - - cpp - - Cpp - - CPP - - 'c++' - - 'C++' - CanonicalDelimiter: '' - BasedOnStyle: google - - Language: TextProto - Delimiters: - - pb - - PB - - proto - - PROTO - EnclosingFunctions: - - EqualsProto - - EquivToProto - - PARSE_PARTIAL_TEXT_PROTO - - PARSE_TEST_PROTO - - PARSE_TEXT_PROTO - - ParseTextOrDie - - ParseTextProtoOrDie - - ParseTestProto - - ParsePartialTestProto - CanonicalDelimiter: pb - BasedOnStyle: google -ReferenceAlignment: Pointer -ReflowComments: true -RemoveBracesLLVM: false -RequiresClausePosition: OwnLine -SeparateDefinitionBlocks: Leave -ShortNamespaceLines: 1 -SortIncludes: CaseSensitive -SortJavaStaticImport: Before -SortUsingDeclarations: true -SpaceAfterCStyleCast: false -SpaceAfterLogicalNot: false -SpaceAfterTemplateKeyword: true -SpaceBeforeAssignmentOperators: true -SpaceBeforeCaseColon: false -SpaceBeforeCpp11BracedList: false -SpaceBeforeCtorInitializerColon: true -SpaceBeforeInheritanceColon: true -SpaceBeforeParens: ControlStatements -SpaceBeforeParensOptions: - AfterControlStatements: true - AfterForeachMacros: true - AfterFunctionDefinitionName: false - AfterFunctionDeclarationName: false - AfterIfMacros: true - AfterOverloadedOperator: false - AfterRequiresInClause: false - AfterRequiresInExpression: false - BeforeNonEmptyParentheses: false -SpaceAroundPointerQualifiers: Default -SpaceBeforeRangeBasedForLoopColon: true -SpaceInEmptyBlock: false -SpaceInEmptyParentheses: false -SpacesBeforeTrailingComments: 2 -SpacesInAngles: Never -SpacesInConditionalStatement: false -SpacesInContainerLiterals: true -SpacesInCStyleCastParentheses: false -SpacesInLineCommentPrefix: - Minimum: 1 - Maximum: -1 -SpacesInParentheses: false -SpacesInSquareBrackets: false -SpaceBeforeSquareBrackets: false -BitFieldColonSpacing: Both -Standard: Auto -StatementAttributeLikeMacros: - - Q_EMIT -StatementMacros: - - Q_UNUSED - - QT_REQUIRE_VERSION -TabWidth: 8 -UseCRLF: false -UseTab: Never -WhitespaceSensitiveMacros: - - STRINGIZE - - PP_STRINGIZE - - BOOST_PP_STRINGIZE - - NS_SWIFT_NAME - - CF_SWIFT_NAME -... - +Language: Cpp +BasedOnStyle: Google