VoidBuildSystem CI / build-and-test-gcc16 (push) Failing after 8s
VoidBuildSystem CI / sanitizers-gcc16 (push) Failing after 6s
VoidBuildSystem CI / fuzz-clang (push) Failing after 6s
VoidBuildSystem CI / signing-openssl-gcc16 (push) Failing after 11s
VoidBuildSystem CI / wine-windows-gcc16 (push) Failing after 48s
1846 lines
79 KiB
C++
1846 lines
79 KiB
C++
#include <Void/Build/BootstrapConfig.hpp>
|
|
#include <Void/Build/Editor/CompDb.hpp>
|
|
|
|
#include <Void/Build/Package/Archive.hpp>
|
|
#include <Void/Build/Platform/FileOps.hpp>
|
|
#include <Void/Build/Util/Json.hpp>
|
|
#include <Void/Build/Util/Sha256.hpp>
|
|
#include <Void/Data/StrictJson.hpp>
|
|
#include <Void/System/Path.hpp>
|
|
#include <Void/System/Types.hpp>
|
|
|
|
#include <algorithm>
|
|
#include <format>
|
|
#include <ranges>
|
|
|
|
namespace Void::Build::Editor {
|
|
namespace {
|
|
|
|
using JsonVal = Void::Json::Strict::Value;
|
|
|
|
Void::Result::Error make_error(std::string msg) {
|
|
return Void::System::make_system_error(Void::System::SystemErrorCode::invalid_argument,
|
|
std::move(msg));
|
|
}
|
|
|
|
std::string sanitize_profile_dir(std::string_view name) {
|
|
std::string out;
|
|
out.reserve(name.size());
|
|
for (const char c : name) {
|
|
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') ||
|
|
c == '_' || c == '-' || c == '.') {
|
|
out.push_back(c);
|
|
} else {
|
|
out.push_back('_');
|
|
}
|
|
}
|
|
return out;
|
|
}
|
|
|
|
std::string_view status_name(GenerationStatus s) {
|
|
switch (s) {
|
|
case GenerationStatus::Valid:
|
|
return "valid";
|
|
case GenerationStatus::Stale:
|
|
return "stale";
|
|
case GenerationStatus::Invalid:
|
|
return "invalid";
|
|
}
|
|
return "invalid";
|
|
}
|
|
|
|
std::string c_standard_flag(CStandard standard) {
|
|
switch (standard) {
|
|
case CStandard::Default:
|
|
return {};
|
|
case CStandard::C11:
|
|
return "-std=c11";
|
|
case CStandard::C17:
|
|
return "-std=c17";
|
|
case CStandard::C23:
|
|
return "-std=c23";
|
|
}
|
|
return {};
|
|
}
|
|
|
|
std::string cxx_standard_flag(CxxStandard standard) {
|
|
switch (standard) {
|
|
case CxxStandard::Default:
|
|
return {};
|
|
case CxxStandard::Cxx17:
|
|
return "-std=c++17";
|
|
case CxxStandard::Cxx20:
|
|
return "-std=c++20";
|
|
case CxxStandard::Cxx23:
|
|
return "-std=c++23";
|
|
case CxxStandard::Cxx26:
|
|
return "-std=c++26";
|
|
}
|
|
return {};
|
|
}
|
|
|
|
std::string sanitizer_flag(Sanitizer s) {
|
|
switch (s) {
|
|
case Sanitizer::Address:
|
|
return "address";
|
|
case Sanitizer::Undefined:
|
|
return "undefined";
|
|
case Sanitizer::Thread:
|
|
return "thread";
|
|
case Sanitizer::Memory:
|
|
return "memory";
|
|
case Sanitizer::Leak:
|
|
return "leak";
|
|
}
|
|
return {};
|
|
}
|
|
|
|
const JsonVal *find_key(const JsonVal::Object &obj, const std::string &k) {
|
|
const auto it = obj.find(k);
|
|
return it == obj.end() ? nullptr : &it->second;
|
|
}
|
|
|
|
std::string get_str(const JsonVal::Object &obj, const std::string &k) {
|
|
const auto *v = find_key(obj, k);
|
|
if (!v) {
|
|
return {};
|
|
}
|
|
const auto *s = std::get_if<std::string>(&v->value);
|
|
return s ? *s : std::string{};
|
|
}
|
|
|
|
std::int64_t get_i64(const JsonVal::Object &obj, const std::string &k, std::int64_t def = 0) {
|
|
const auto *v = find_key(obj, k);
|
|
if (!v) {
|
|
return def;
|
|
}
|
|
const auto *i = std::get_if<std::int64_t>(&v->value);
|
|
return i ? *i : def;
|
|
}
|
|
|
|
bool get_bool(const JsonVal::Object &obj, const std::string &k, bool def = false) {
|
|
const auto *v = find_key(obj, k);
|
|
if (!v) {
|
|
return def;
|
|
}
|
|
const auto *b = std::get_if<bool>(&v->value);
|
|
return b ? *b : def;
|
|
}
|
|
|
|
std::filesystem::path selection_file_path(const std::filesystem::path &project_root) {
|
|
return project_root / ".vbs" / "editor_selection.json";
|
|
}
|
|
|
|
std::filesystem::path selection_lock_path(const std::filesystem::path &project_root) {
|
|
return project_root / ".vbs" / "editor_selection.lock";
|
|
}
|
|
|
|
std::string serialize_selection(const SelectionState &st) {
|
|
using Util::json_quote;
|
|
return "{\"schema_version\":1,\"ticket\":" + std::to_string(st.ticket) +
|
|
",\"selected_profile\":" + json_quote(st.selected_profile) +
|
|
",\"selected_build_root\":" + json_quote(st.selected_build_root.string()) +
|
|
",\"selected_generation_id\":" + json_quote(st.selected_generation_id) +
|
|
",\"selected_compdb_path\":" + json_quote(st.selected_compdb_path.string()) +
|
|
",\"managed_root_alias_active\":" +
|
|
std::string{st.managed_root_alias_active ? "true" : "false"} +
|
|
",\"root_alias_warning\":" + json_quote(st.root_alias_warning) + "}\n";
|
|
}
|
|
|
|
std::optional<SelectionState> load_selection_locked(const std::filesystem::path &project_root) {
|
|
auto text = Void::FileSystem::read_file(selection_file_path(project_root));
|
|
if (!text) {
|
|
return std::nullopt;
|
|
}
|
|
auto parsed = Void::Json::Strict::parse(*text);
|
|
if (!parsed) {
|
|
return std::nullopt;
|
|
}
|
|
const auto *obj = std::get_if<JsonVal::Object>(&parsed->value);
|
|
if (!obj) {
|
|
return std::nullopt;
|
|
}
|
|
SelectionState st;
|
|
st.ticket = static_cast<std::uint64_t>(get_i64(*obj, "ticket", 0));
|
|
st.selected_profile = get_str(*obj, "selected_profile");
|
|
st.selected_build_root = get_str(*obj, "selected_build_root");
|
|
st.selected_generation_id = get_str(*obj, "selected_generation_id");
|
|
st.selected_compdb_path = get_str(*obj, "selected_compdb_path");
|
|
st.managed_root_alias_active = get_bool(*obj, "managed_root_alias_active", false);
|
|
st.root_alias_warning = get_str(*obj, "root_alias_warning");
|
|
return st;
|
|
}
|
|
|
|
// Updates `<project_root>/compile_commands.json` ONLY if it does not exist or is already
|
|
// a VBS-managed symlink. Preserves any unrelated user-owned file!
|
|
Void::Result::Result<bool, Void::Result::Error>
|
|
update_managed_root_alias(const std::filesystem::path &project_root,
|
|
const std::filesystem::path &build_root,
|
|
const std::filesystem::path &target_compdb, std::string &warning_out) {
|
|
const auto root_alias = project_root / "compile_commands.json";
|
|
auto meta = Platform::stat_lstat(root_alias);
|
|
if (!meta) {
|
|
return std::unexpected{meta.error()};
|
|
}
|
|
|
|
if (meta->exists) {
|
|
if (!meta->is_symlink) {
|
|
warning_out = "preserved existing user-owned project-root compile_commands.json";
|
|
return false;
|
|
}
|
|
// Check if symlink points into build_root or is recorded as managed.
|
|
std::filesystem::path target_p{meta->symlink_target};
|
|
if (!target_p.is_absolute()) {
|
|
target_p = (project_root / target_p).lexically_normal();
|
|
}
|
|
std::error_code ec;
|
|
const auto canon_build = std::filesystem::weakly_canonical(build_root, ec);
|
|
if (!Platform::path_is_within(canon_build, target_p)) {
|
|
warning_out =
|
|
"preserved existing non-VBS symlink at project-root compile_commands.json";
|
|
return false;
|
|
}
|
|
}
|
|
|
|
auto swapped = Platform::atomic_swap_symlink(root_alias, target_compdb);
|
|
if (!swapped) {
|
|
return std::unexpected{swapped.error()};
|
|
}
|
|
warning_out.clear();
|
|
return true;
|
|
}
|
|
|
|
std::string escape_xml_attr(std::string_view sv) {
|
|
std::string out;
|
|
out.reserve(sv.size());
|
|
for (const char c : sv) {
|
|
switch (c) {
|
|
case '&':
|
|
out += "&";
|
|
break;
|
|
case '<':
|
|
out += "<";
|
|
break;
|
|
case '>':
|
|
out += ">";
|
|
break;
|
|
case '"':
|
|
out += """;
|
|
break;
|
|
case '\'':
|
|
out += "'";
|
|
break;
|
|
default:
|
|
out.push_back(c);
|
|
break;
|
|
}
|
|
}
|
|
return out;
|
|
}
|
|
|
|
std::string workspace_var_path(const std::filesystem::path &project_root,
|
|
const std::filesystem::path &target, std::string_view prefix_var) {
|
|
const auto norm_root = project_root.lexically_normal();
|
|
const auto norm_target = target.lexically_normal();
|
|
if (!norm_root.empty() && Platform::path_is_within(norm_root, norm_target)) {
|
|
const auto rel = norm_target.lexically_relative(norm_root);
|
|
if (!rel.empty() && rel != ".") {
|
|
return std::string{prefix_var} + "/" + rel.generic_string();
|
|
}
|
|
return std::string{prefix_var};
|
|
}
|
|
return norm_target.string();
|
|
}
|
|
|
|
} // namespace
|
|
|
|
std::vector<EditorCommandEntry> project_editor_commands(const Graph::BuildGraph &graph) {
|
|
std::vector<EditorCommandEntry> entries;
|
|
std::error_code ec;
|
|
|
|
// Identify enabled targets so disabled targets are omitted, while ALL enabled targets
|
|
// are included even if a build only executed a subset.
|
|
std::set<std::string> enabled_targets;
|
|
for (const auto &t : graph.targets) {
|
|
if (t.enabled) {
|
|
enabled_targets.insert(t.name);
|
|
}
|
|
}
|
|
|
|
for (const auto &act : graph.actions) {
|
|
if (act.kind != Graph::ActionKind::Compile) {
|
|
continue;
|
|
}
|
|
if (!enabled_targets.contains(act.target_name)) {
|
|
continue;
|
|
}
|
|
|
|
// Reconstruct structured logical argv directly from typed operands —
|
|
// NEVER regex/string-replace arbitrary flags or macro definitions!
|
|
EditorCommandEntry entry;
|
|
entry.directory = graph.project_root;
|
|
entry.file = act.logical_source_file;
|
|
entry.output = act.logical_output_file;
|
|
entry.target_name = act.target_name;
|
|
|
|
entry.arguments.push_back(act.executable.string());
|
|
if (!graph.toolchain.sysroot.empty()) {
|
|
entry.arguments.push_back("--sysroot=" + graph.toolchain.sysroot);
|
|
}
|
|
if (act.is_c_source) {
|
|
if (const auto std_flag = c_standard_flag(act.c_standard); !std_flag.empty()) {
|
|
entry.arguments.push_back(std_flag);
|
|
}
|
|
} else {
|
|
if (const auto std_flag = cxx_standard_flag(act.cxx_standard); !std_flag.empty()) {
|
|
entry.arguments.push_back(std_flag);
|
|
}
|
|
}
|
|
if (act.position_independent) {
|
|
entry.arguments.push_back("-fPIC");
|
|
}
|
|
if (act.lto == LtoMode::Full) {
|
|
entry.arguments.push_back("-flto");
|
|
} else if (act.lto == LtoMode::Thin) {
|
|
entry.arguments.push_back("-flto=thin");
|
|
}
|
|
if (!act.sanitizers.empty()) {
|
|
std::string list;
|
|
for (std::size_t i = 0; i < act.sanitizers.size(); ++i) {
|
|
if (i > 0) {
|
|
list += ',';
|
|
}
|
|
list += sanitizer_flag(act.sanitizers[i]);
|
|
}
|
|
entry.arguments.push_back("-fsanitize=" + list);
|
|
entry.arguments.push_back("-fno-omit-frame-pointer");
|
|
}
|
|
if (act.precompiled_header && !act.is_c_source) {
|
|
entry.arguments.push_back("-include");
|
|
entry.arguments.push_back(act.precompiled_header->string());
|
|
}
|
|
for (const auto &[inc_path, is_system] : act.logical_include_dirs) {
|
|
entry.arguments.push_back(is_system ? "-isystem" : "-I");
|
|
entry.arguments.push_back(inc_path.string());
|
|
}
|
|
for (const auto &def : act.defines) {
|
|
entry.arguments.push_back("-D" + def);
|
|
}
|
|
for (const auto &opt : act.compile_options) {
|
|
entry.arguments.push_back(opt);
|
|
}
|
|
entry.arguments.push_back("-c");
|
|
entry.arguments.push_back(act.logical_source_file.string());
|
|
entry.arguments.push_back("-o");
|
|
entry.arguments.push_back(act.logical_output_file.string());
|
|
|
|
// Check generated prerequisites readiness (Plan 09/10).
|
|
for (const auto &dep_id : act.dependencies) {
|
|
const auto dit = graph.action_index_by_id.find(dep_id);
|
|
if (dit == graph.action_index_by_id.end()) {
|
|
continue;
|
|
}
|
|
const auto &producer = graph.actions[dit->second];
|
|
if (producer.kind == Graph::ActionKind::Custom ||
|
|
producer.kind == Graph::ActionKind::PrecompiledHeader) {
|
|
for (const auto &out : producer.declared_outputs) {
|
|
if (!std::filesystem::exists(out, ec)) {
|
|
entry.missing_generated_prerequisites.push_back(out);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
entries.push_back(std::move(entry));
|
|
}
|
|
|
|
return entries;
|
|
}
|
|
|
|
std::vector<EditorCommandEntry> project_build_descriptor_commands(
|
|
const std::filesystem::path &project_root, const std::filesystem::path &build_root,
|
|
const std::filesystem::path &sdk_include_dir, const std::filesystem::path &host_cxx_compiler,
|
|
const std::vector<std::filesystem::path> &extra_build_sources) {
|
|
std::vector<EditorCommandEntry> entries;
|
|
if (sdk_include_dir.empty() || host_cxx_compiler.empty()) {
|
|
return entries;
|
|
}
|
|
|
|
std::error_code ec;
|
|
const auto raw_canon = std::filesystem::weakly_canonical(project_root, ec);
|
|
const auto canon_root = (ec ? project_root : raw_canon).lexically_normal();
|
|
const auto desc_obj_root = build_root / ".vbs" / "editor-desc";
|
|
|
|
std::vector<std::filesystem::path> candidates;
|
|
std::set<std::filesystem::path> seen;
|
|
auto push_if_file = [&](const std::filesystem::path &p) {
|
|
const auto norm = (p.is_absolute() ? p : (canon_root / p)).lexically_normal();
|
|
if (std::filesystem::is_regular_file(norm, ec) && seen.insert(norm).second) {
|
|
candidates.push_back(norm);
|
|
}
|
|
};
|
|
|
|
push_if_file("build.cpp");
|
|
push_if_file("build.profiles.cpp");
|
|
const auto support_dir = canon_root / "build-support";
|
|
if (std::filesystem::is_directory(support_dir, ec)) {
|
|
std::vector<std::filesystem::path> support_files;
|
|
for (const auto &ent : std::filesystem::recursive_directory_iterator(support_dir, ec)) {
|
|
if (!ent.is_regular_file(ec)) {
|
|
continue;
|
|
}
|
|
const auto ext = ent.path().extension().string();
|
|
if (ext == ".cpp" || ext == ".cc" || ext == ".cxx") {
|
|
support_files.push_back(ent.path().lexically_normal());
|
|
}
|
|
}
|
|
std::ranges::sort(support_files);
|
|
for (const auto &sf : support_files) {
|
|
push_if_file(sf);
|
|
}
|
|
}
|
|
for (const auto &extra : extra_build_sources) {
|
|
push_if_file(extra);
|
|
}
|
|
|
|
const bool has_support = std::filesystem::is_directory(support_dir, ec);
|
|
for (const auto &src : candidates) {
|
|
const std::string tag = Util::sha256_hex(src.string()).substr(0, 12);
|
|
const auto out_obj = desc_obj_root / (src.filename().string() + "_" + tag + ".o");
|
|
EditorCommandEntry entry;
|
|
entry.directory = canon_root;
|
|
entry.file = src;
|
|
entry.output = out_obj;
|
|
entry.target_name = "__vbs_build_description";
|
|
entry.arguments = {host_cxx_compiler.string(), "-std=c++26", "-I",
|
|
sdk_include_dir.lexically_normal().string()};
|
|
if (has_support) {
|
|
entry.arguments.push_back("-I");
|
|
entry.arguments.push_back(support_dir.string());
|
|
}
|
|
entry.arguments.push_back("-c");
|
|
entry.arguments.push_back(src.string());
|
|
entry.arguments.push_back("-o");
|
|
entry.arguments.push_back(out_obj.string());
|
|
entries.push_back(std::move(entry));
|
|
}
|
|
return entries;
|
|
}
|
|
|
|
std::string format_compile_commands_json(const std::vector<EditorCommandEntry> &entries) {
|
|
using Util::json_array;
|
|
using Util::json_quote;
|
|
|
|
std::string out{"[\n"};
|
|
for (std::size_t i = 0; i < entries.size(); ++i) {
|
|
const auto &e = entries[i];
|
|
out += " {\"directory\":" + json_quote(e.directory.string()) +
|
|
",\"file\":" + json_quote(e.file.string()) +
|
|
",\"output\":" + json_quote(e.output.string()) +
|
|
",\"arguments\":" + json_array(e.arguments, json_quote) + "}";
|
|
if (i + 1 < entries.size()) {
|
|
out += ',';
|
|
}
|
|
out += '\n';
|
|
}
|
|
out += "]\n";
|
|
return out;
|
|
}
|
|
|
|
Void::Result::Result<std::uint64_t, Void::Result::Error>
|
|
reserve_selection_ticket(const std::filesystem::path &project_root,
|
|
const std::filesystem::path &build_root, std::string_view profile_name) {
|
|
auto lock = Platform::FileLock::acquire(selection_lock_path(project_root),
|
|
Platform::LockMode::Exclusive);
|
|
if (!lock) {
|
|
return std::unexpected{lock.error()};
|
|
}
|
|
SelectionState st = load_selection_locked(project_root).value_or(SelectionState{});
|
|
st.ticket += 1;
|
|
// Record reservation ticket monotonically without pointing to an unvalidated generation yet.
|
|
if (st.selected_build_root.empty()) {
|
|
st.selected_build_root = build_root;
|
|
}
|
|
if (st.selected_profile.empty()) {
|
|
st.selected_profile = std::string{profile_name};
|
|
}
|
|
auto wrote = Platform::atomic_write_file(selection_file_path(project_root),
|
|
serialize_selection(st), true);
|
|
if (!wrote) {
|
|
return std::unexpected{wrote.error()};
|
|
}
|
|
return st.ticket;
|
|
}
|
|
|
|
Void::Result::Result<EditorGeneration, Void::Result::Error>
|
|
publish_profile_compdb(const Graph::BuildGraph &graph, const PublishOptions &options) {
|
|
auto entries = project_editor_commands(graph);
|
|
if (!options.sdk_include_dir.empty()) {
|
|
auto desc_entries = project_build_descriptor_commands(
|
|
options.project_root, options.build_root, options.sdk_include_dir,
|
|
graph.toolchain.cxx_compiler, options.extra_build_sources);
|
|
for (auto &de : desc_entries) {
|
|
const bool already = std::ranges::any_of(entries, [&](const EditorCommandEntry &ex) {
|
|
return ex.file.lexically_normal() == de.file.lexically_normal();
|
|
});
|
|
if (!already) {
|
|
entries.push_back(std::move(de));
|
|
}
|
|
}
|
|
}
|
|
const std::string compdb_json = format_compile_commands_json(entries);
|
|
const std::string gen_id =
|
|
Util::sha256_hex(graph.profile_identity + "\n" + compdb_json).substr(0, 16);
|
|
|
|
const auto profile_dir =
|
|
options.build_root / "profiles" / sanitize_profile_dir(graph.profile.name);
|
|
const auto gen_dir = profile_dir / "editor" / "generations" / gen_id;
|
|
const auto gen_compdb = gen_dir / "compile_commands.json";
|
|
const auto profile_compdb = profile_dir / "compile_commands.json";
|
|
const auto status_file = profile_dir / "editor" / "status.json";
|
|
|
|
EditorGeneration gen;
|
|
gen.generation_id = gen_id;
|
|
gen.profile_name = graph.profile.name;
|
|
gen.profile_identity = graph.profile_identity;
|
|
gen.status = GenerationStatus::Valid;
|
|
gen.compdb_path = gen_compdb;
|
|
gen.entry_count = entries.size();
|
|
|
|
for (const auto &e : entries) {
|
|
for (const auto &missing : e.missing_generated_prerequisites) {
|
|
gen.readiness_warnings.push_back(std::format("target '{}' missing generated input '{}'",
|
|
e.target_name, missing.string()));
|
|
}
|
|
}
|
|
|
|
// Avoid needless rewrite when identical immutable generation bytes already exist.
|
|
bool bytes_changed = true;
|
|
if (auto existing = Void::FileSystem::read_file(gen_compdb);
|
|
existing && *existing == compdb_json) {
|
|
bytes_changed = false;
|
|
}
|
|
if (bytes_changed) {
|
|
if (auto w = Platform::atomic_write_file(gen_compdb, compdb_json, true); !w) {
|
|
return std::unexpected{w.error()};
|
|
}
|
|
}
|
|
|
|
// Atomically update per-profile compile_commands.json pointer.
|
|
if (auto sw = Platform::atomic_swap_symlink(profile_compdb, gen_compdb); !sw) {
|
|
return std::unexpected{sw.error()};
|
|
}
|
|
|
|
// Write per-profile status record atomically.
|
|
const std::string status_json =
|
|
"{\"schema_version\":1,\"profile\":" + Util::json_quote(graph.profile.name) +
|
|
",\"generation_id\":" + Util::json_quote(gen_id) +
|
|
",\"status\":\"valid\",\"diagnostic\":\"\"" +
|
|
",\"compdb_path\":" + Util::json_quote(gen_compdb.string()) +
|
|
",\"entry_count\":" + std::to_string(entries.size()) +
|
|
",\"readiness_warnings\":" + Util::json_array(gen.readiness_warnings, Util::json_quote) +
|
|
"}\n";
|
|
if (auto sw = Platform::atomic_write_file(status_file, status_json, true); !sw) {
|
|
return std::unexpected{sw.error()};
|
|
}
|
|
|
|
// Coordinate project-level editor selection under short exclusive lock with ticket/revision
|
|
// check!
|
|
auto lock = Platform::FileLock::acquire(selection_lock_path(options.project_root),
|
|
Platform::LockMode::Exclusive);
|
|
if (!lock) {
|
|
return std::unexpected{lock.error()};
|
|
}
|
|
|
|
SelectionState st = load_selection_locked(options.project_root).value_or(SelectionState{});
|
|
bool should_select = false;
|
|
if (options.update_selection) {
|
|
const std::uint64_t my_ticket = options.reserved_ticket.value_or(st.ticket + 1);
|
|
// Reject stale late completions whose reserved ticket was superseded by a newer request!
|
|
if (my_ticket >= st.ticket) {
|
|
st.ticket = my_ticket;
|
|
should_select = true;
|
|
}
|
|
} else if (st.selected_profile == graph.profile.name &&
|
|
st.selected_build_root == options.build_root) {
|
|
// Watchers refresh the ALREADY-SELECTED profile without stealing selection!
|
|
should_select = true;
|
|
}
|
|
|
|
if (should_select) {
|
|
st.selected_profile = graph.profile.name;
|
|
st.selected_build_root = options.build_root;
|
|
st.selected_generation_id = gen_id;
|
|
st.selected_compdb_path = gen_compdb;
|
|
|
|
const auto build_root_compdb = options.build_root / "compile_commands.json";
|
|
if (auto sw = Platform::atomic_swap_symlink(build_root_compdb, gen_compdb); !sw) {
|
|
return std::unexpected{sw.error()};
|
|
}
|
|
if (options.manage_project_root_alias) {
|
|
std::string warn;
|
|
auto alias_res = update_managed_root_alias(options.project_root, options.build_root,
|
|
gen_compdb, warn);
|
|
if (!alias_res) {
|
|
return std::unexpected{alias_res.error()};
|
|
}
|
|
st.managed_root_alias_active = *alias_res;
|
|
st.root_alias_warning = std::move(warn);
|
|
}
|
|
if (auto w = Platform::atomic_write_file(selection_file_path(options.project_root),
|
|
serialize_selection(st), true);
|
|
!w) {
|
|
return std::unexpected{w.error()};
|
|
}
|
|
}
|
|
|
|
return gen;
|
|
}
|
|
|
|
Void::Result::Result<void, Void::Result::Error>
|
|
mark_profile_stale(const std::filesystem::path &build_root, std::string_view profile_name,
|
|
GenerationStatus status, std::string_view diagnostic) {
|
|
const auto profile_dir = build_root / "profiles" / sanitize_profile_dir(profile_name);
|
|
const auto status_file = profile_dir / "editor" / "status.json";
|
|
|
|
// Preserve previous valid generation ID/path if present so editors see clearly stale DB.
|
|
std::string prev_gen;
|
|
std::string prev_path;
|
|
if (auto existing = Void::FileSystem::read_file(status_file); existing) {
|
|
if (auto parsed = Void::Json::Strict::parse(*existing); parsed) {
|
|
if (const auto *obj = std::get_if<JsonVal::Object>(&parsed->value)) {
|
|
prev_gen = get_str(*obj, "generation_id");
|
|
prev_path = get_str(*obj, "compdb_path");
|
|
}
|
|
}
|
|
}
|
|
|
|
const std::string json = "{\"schema_version\":1,\"profile\":" + Util::json_quote(profile_name) +
|
|
",\"generation_id\":" + Util::json_quote(prev_gen) +
|
|
",\"status\":" + Util::json_quote(status_name(status)) +
|
|
",\"diagnostic\":" + Util::json_quote(diagnostic) +
|
|
",\"compdb_path\":" + Util::json_quote(prev_path) + "}\n";
|
|
return Platform::atomic_write_file(status_file, json, true);
|
|
}
|
|
|
|
Void::Result::Result<SelectionState, Void::Result::Error>
|
|
select_editor_profile(const std::filesystem::path &project_root,
|
|
const std::filesystem::path &build_root, std::string_view profile_name,
|
|
bool manage_project_root_alias) {
|
|
const auto profile_dir = build_root / "profiles" / sanitize_profile_dir(profile_name);
|
|
const auto status_file = profile_dir / "editor" / "status.json";
|
|
auto text = Void::FileSystem::read_file(status_file);
|
|
if (!text) {
|
|
return std::unexpected{make_error(
|
|
std::format("no published compilation database for profile '{}'", profile_name))};
|
|
}
|
|
auto parsed = Void::Json::Strict::parse(*text);
|
|
if (!parsed) {
|
|
return std::unexpected{make_error("corrupt editor status metadata")};
|
|
}
|
|
const auto *obj = std::get_if<JsonVal::Object>(&parsed->value);
|
|
if (!obj) {
|
|
return std::unexpected{make_error("invalid editor status metadata")};
|
|
}
|
|
const auto gen_id = get_str(*obj, "generation_id");
|
|
const auto compdb_str = get_str(*obj, "compdb_path");
|
|
if (compdb_str.empty() || !std::filesystem::exists(compdb_str)) {
|
|
return std::unexpected{make_error(std::format(
|
|
"profile '{}' has no valid compilation database generation", profile_name))};
|
|
}
|
|
|
|
auto lock = Platform::FileLock::acquire(selection_lock_path(project_root),
|
|
Platform::LockMode::Exclusive);
|
|
if (!lock) {
|
|
return std::unexpected{lock.error()};
|
|
}
|
|
|
|
SelectionState st = load_selection_locked(project_root).value_or(SelectionState{});
|
|
st.ticket += 1;
|
|
st.selected_profile = std::string{profile_name};
|
|
st.selected_build_root = build_root;
|
|
st.selected_generation_id = gen_id;
|
|
st.selected_compdb_path = compdb_str;
|
|
|
|
if (auto sw = Platform::atomic_swap_symlink(build_root / "compile_commands.json",
|
|
st.selected_compdb_path);
|
|
!sw) {
|
|
return std::unexpected{sw.error()};
|
|
}
|
|
if (manage_project_root_alias) {
|
|
std::string warn;
|
|
auto alias_res =
|
|
update_managed_root_alias(project_root, build_root, st.selected_compdb_path, warn);
|
|
if (!alias_res) {
|
|
return std::unexpected{alias_res.error()};
|
|
}
|
|
st.managed_root_alias_active = *alias_res;
|
|
st.root_alias_warning = std::move(warn);
|
|
}
|
|
if (auto w = Platform::atomic_write_file(selection_file_path(project_root),
|
|
serialize_selection(st), true);
|
|
!w) {
|
|
return std::unexpected{w.error()};
|
|
}
|
|
return st;
|
|
}
|
|
|
|
Void::Result::Result<std::optional<SelectionState>, Void::Result::Error>
|
|
read_selection_state(const std::filesystem::path &project_root) {
|
|
auto lock =
|
|
Platform::FileLock::acquire(selection_lock_path(project_root), Platform::LockMode::Shared);
|
|
if (!lock) {
|
|
return std::unexpected{lock.error()};
|
|
}
|
|
return load_selection_locked(project_root);
|
|
}
|
|
|
|
Void::Result::Result<void, Void::Result::Error>
|
|
recover_editor_pointers(const std::filesystem::path &project_root) {
|
|
auto lock = Platform::FileLock::acquire(selection_lock_path(project_root),
|
|
Platform::LockMode::Exclusive);
|
|
if (!lock) {
|
|
return std::unexpected{lock.error()};
|
|
}
|
|
auto st = load_selection_locked(project_root);
|
|
if (!st || st->selected_compdb_path.empty() ||
|
|
!std::filesystem::exists(st->selected_compdb_path)) {
|
|
return {};
|
|
}
|
|
if (!st->selected_build_root.empty()) {
|
|
(void)Platform::atomic_swap_symlink(st->selected_build_root / "compile_commands.json",
|
|
st->selected_compdb_path);
|
|
}
|
|
if (st->managed_root_alias_active) {
|
|
std::string warn;
|
|
(void)update_managed_root_alias(project_root, st->selected_build_root,
|
|
st->selected_compdb_path, warn);
|
|
}
|
|
return {};
|
|
}
|
|
|
|
Void::Result::Result<IdeKind, Void::Result::Error> parse_ide_kind(std::string_view name) {
|
|
if (name == "all" || name == "All") {
|
|
return IdeKind::All;
|
|
}
|
|
if (name == "clangd" || name == "Clangd") {
|
|
return IdeKind::Clangd;
|
|
}
|
|
if (name == "vscode" || name == "VsCode") {
|
|
return IdeKind::VsCode;
|
|
}
|
|
if (name == "clion" || name == "CLion") {
|
|
return IdeKind::CLion;
|
|
}
|
|
if (name == "zed" || name == "Zed") {
|
|
return IdeKind::Zed;
|
|
}
|
|
return std::unexpected{make_error(
|
|
std::format("unknown IDE kind '{}' (expected: all, clangd, vscode, clion, zed)", name))};
|
|
}
|
|
|
|
std::string_view ide_kind_name(IdeKind kind) {
|
|
switch (kind) {
|
|
case IdeKind::Clangd:
|
|
return "clangd";
|
|
case IdeKind::VsCode:
|
|
return "vscode";
|
|
case IdeKind::CLion:
|
|
return "clion";
|
|
case IdeKind::Zed:
|
|
return "zed";
|
|
case IdeKind::All:
|
|
return "all";
|
|
}
|
|
return "all";
|
|
}
|
|
|
|
namespace {
|
|
Void::Result::Result<void, Void::Result::Error>
|
|
emit_cmake_file_api(const Graph::BuildGraph &graph, const std::filesystem::path &project_root,
|
|
const std::filesystem::path &build_root);
|
|
} // namespace
|
|
|
|
Void::Result::Result<IdeConfigReport, Void::Result::Error>
|
|
generate_ide_configs(const Graph::BuildGraph &graph, const IdeConfigOptions &options) {
|
|
using Util::json_array;
|
|
using Util::json_quote;
|
|
|
|
const auto proj_root =
|
|
(options.project_root.empty() ? graph.project_root : options.project_root)
|
|
.lexically_normal();
|
|
const auto build_root =
|
|
(options.build_root.empty() ? graph.profile_build_dir.parent_path().parent_path()
|
|
: options.build_root)
|
|
.lexically_normal();
|
|
const auto vbs_bin =
|
|
options.vbs_executable.empty() ? std::string{"vbs"} : options.vbs_executable.string();
|
|
|
|
std::filesystem::path compdb_dir = build_root;
|
|
if (!options.compdb_path.empty()) {
|
|
compdb_dir =
|
|
options.compdb_path.has_parent_path() ? options.compdb_path.parent_path() : compdb_dir;
|
|
}
|
|
compdb_dir = compdb_dir.lexically_normal();
|
|
std::string compdb_rel_or_abs = compdb_dir.string();
|
|
if (Platform::path_is_within(proj_root, compdb_dir)) {
|
|
const auto rel = compdb_dir.lexically_relative(proj_root);
|
|
compdb_rel_or_abs = rel.empty() ? "." : rel.generic_string();
|
|
}
|
|
|
|
IdeConfigReport report;
|
|
std::error_code ec;
|
|
auto write_ide_file =
|
|
[&](const std::filesystem::path &path,
|
|
std::string_view content) -> Void::Result::Result<void, Void::Result::Error> {
|
|
if (!options.force &&
|
|
(std::filesystem::exists(path, ec) || std::filesystem::is_symlink(path, ec))) {
|
|
report.skipped_existing_files.push_back(path);
|
|
return {};
|
|
}
|
|
auto w = Platform::atomic_write_file(path, content, false);
|
|
if (!w) {
|
|
return std::unexpected{w.error()};
|
|
}
|
|
report.written_files.push_back(path);
|
|
return {};
|
|
};
|
|
|
|
// CMake File API metadata is always regenerated: it is IDE/build metadata owned by VBS.
|
|
if (auto emitted = emit_cmake_file_api(graph, proj_root, build_root); !emitted) {
|
|
return std::unexpected{emitted.error()};
|
|
}
|
|
|
|
const bool want_all = (options.editor == IdeKind::All);
|
|
|
|
// 1. .clangd configuration (GCC-16 flag sanitization + CompilationDatabase pointer).
|
|
if (want_all || options.editor == IdeKind::Clangd) {
|
|
std::string yaml = "# Generated by VoidBuildSystem (`vbs ide generate`). Re-run with "
|
|
"`--force` to update.\n"
|
|
"CompileFlags:\n"
|
|
" CompilationDatabase: " +
|
|
json_quote(compdb_rel_or_abs) +
|
|
"\n"
|
|
" Remove:\n"
|
|
" - -freflection\n"
|
|
" - -fmodules\n"
|
|
" - -fmodules-ts\n"
|
|
" - \"-fmodule-mapper=*\"\n"
|
|
" - \"-frandom-seed=*\"\n"
|
|
" - \"-fdeps-format=*\"\n"
|
|
" - \"-fdeps-file=*\"\n"
|
|
" - \"-fdeps-target=*\"\n";
|
|
if (auto r = write_ide_file(proj_root / ".clangd", yaml); !r) {
|
|
return std::unexpected{r.error()};
|
|
}
|
|
}
|
|
|
|
struct RunnableTarget {
|
|
std::string name;
|
|
bool is_test{false};
|
|
std::filesystem::path program;
|
|
};
|
|
std::vector<RunnableTarget> runnables;
|
|
std::vector<std::string> buildable_targets;
|
|
for (const auto &t : graph.targets) {
|
|
if (!t.enabled) {
|
|
continue;
|
|
}
|
|
if (t.kind == TargetKind::Executable || t.kind == TargetKind::Test ||
|
|
t.kind == TargetKind::StaticLibrary || t.kind == TargetKind::SharedLibrary) {
|
|
buildable_targets.push_back(t.name);
|
|
}
|
|
if ((t.kind == TargetKind::Executable || t.kind == TargetKind::Test) &&
|
|
!t.primary_outputs.empty()) {
|
|
runnables.push_back({t.name, t.kind == TargetKind::Test, t.primary_outputs.front()});
|
|
}
|
|
}
|
|
|
|
// 2. VS Code / Cursor / Antigravity (.vscode/tasks.json, launch.json, settings.json).
|
|
if (want_all || options.editor == IdeKind::VsCode) {
|
|
auto make_vs_task = [&](const std::string &label, const std::vector<std::string> &args,
|
|
const std::string &group, bool is_default) {
|
|
std::string t = " {\n";
|
|
t += " \"label\": " + json_quote(label) + ",\n";
|
|
t += " \"type\": \"process\",\n";
|
|
t += " \"command\": " + json_quote(vbs_bin) + ",\n";
|
|
t += " \"args\": " + json_array(args, json_quote) + ",\n";
|
|
t += " \"options\": {\"cwd\": \"${workspaceFolder}\"},\n";
|
|
if (!group.empty()) {
|
|
if (is_default) {
|
|
t += " \"group\": {\"kind\": " + json_quote(group) +
|
|
", \"isDefault\": true},\n";
|
|
} else {
|
|
t += " \"group\": " + json_quote(group) + ",\n";
|
|
}
|
|
}
|
|
t += " \"problemMatcher\": [\"$gcc\"]\n";
|
|
t += " }";
|
|
return t;
|
|
};
|
|
|
|
std::vector<std::string> vs_tasks;
|
|
vs_tasks.push_back(make_vs_task("vbs: build (" + graph.profile.name + ")",
|
|
{"build", "--profile", graph.profile.name}, "build", true));
|
|
vs_tasks.push_back(make_vs_task("vbs: test (" + graph.profile.name + ")",
|
|
{"test", "--profile", graph.profile.name}, "test", true));
|
|
vs_tasks.push_back(make_vs_task("vbs: clean", {"clean"}, "", false));
|
|
vs_tasks.push_back(make_vs_task("vbs: refresh compile_commands.json",
|
|
{"compdb", "export", "--profile", graph.profile.name}, "",
|
|
false));
|
|
vs_tasks.push_back(
|
|
make_vs_task("vbs: install",
|
|
{"install", "--profile", graph.profile.name, "--prefix",
|
|
(options.build_root / "install").string(), "--bundle-dependencies",
|
|
"--archive", (options.build_root / "install" / "installer.tar").string()},
|
|
"", false));
|
|
vs_tasks.push_back(make_vs_task(
|
|
"vbs: package installer",
|
|
{"install", "--profile", graph.profile.name, "--prefix",
|
|
(options.build_root / "install").string(), "--bundle-dependencies", "--archive",
|
|
(options.build_root / "install" / "installer.sh").string(), "--archive-format", "sh"},
|
|
"", false));
|
|
for (const auto &tname : buildable_targets) {
|
|
vs_tasks.push_back(make_vs_task(
|
|
"vbs: build " + tname,
|
|
{"build", "--profile", graph.profile.name, "--target", tname}, "build", false));
|
|
}
|
|
for (const auto &rt : runnables) {
|
|
if (rt.is_test) {
|
|
vs_tasks.push_back(make_vs_task(
|
|
"vbs: test " + rt.name,
|
|
{"test", "--profile", graph.profile.name, "--target", rt.name}, "test", false));
|
|
}
|
|
}
|
|
|
|
std::string tasks_json = "{\n \"version\": \"2.0.0\",\n \"tasks\": [\n";
|
|
for (std::size_t i = 0; i < vs_tasks.size(); ++i) {
|
|
tasks_json += vs_tasks[i];
|
|
if (i + 1 < vs_tasks.size()) {
|
|
tasks_json += ',';
|
|
}
|
|
tasks_json += '\n';
|
|
}
|
|
tasks_json += " ]\n}\n";
|
|
if (auto r = write_ide_file(proj_root / ".vscode" / "tasks.json", tasks_json); !r) {
|
|
return std::unexpected{r.error()};
|
|
}
|
|
|
|
std::string launch_json = "{\n \"version\": \"0.2.0\",\n \"configurations\": [\n";
|
|
for (std::size_t i = 0; i < runnables.size(); ++i) {
|
|
const auto &rt = runnables[i];
|
|
const std::string prog =
|
|
workspace_var_path(proj_root, rt.program, "${workspaceFolder}");
|
|
launch_json += " {\n";
|
|
launch_json += " \"name\": " + json_quote("Debug " + rt.name + " (vbs)") + ",\n";
|
|
launch_json += " \"type\": \"cppdbg\",\n";
|
|
launch_json += " \"request\": \"launch\",\n";
|
|
launch_json += " \"program\": " + json_quote(prog) + ",\n";
|
|
launch_json += " \"args\": [],\n";
|
|
launch_json += " \"stopAtEntry\": false,\n";
|
|
launch_json += " \"cwd\": \"${workspaceFolder}\",\n";
|
|
launch_json += " \"MIMode\": \"gdb\",\n";
|
|
launch_json += " \"preLaunchTask\": " + json_quote("vbs: build " + rt.name) + "\n";
|
|
launch_json += " }";
|
|
if (i + 1 < runnables.size()) {
|
|
launch_json += ',';
|
|
}
|
|
launch_json += '\n';
|
|
}
|
|
launch_json += " ]\n}\n";
|
|
if (auto r = write_ide_file(proj_root / ".vscode" / "launch.json", launch_json); !r) {
|
|
return std::unexpected{r.error()};
|
|
}
|
|
|
|
const std::filesystem::path compdb_file = options.compdb_path.empty()
|
|
? (compdb_dir / "compile_commands.json")
|
|
: options.compdb_path;
|
|
const std::string vs_compdb =
|
|
workspace_var_path(proj_root, compdb_file, "${workspaceFolder}");
|
|
const std::string vs_compdb_dir =
|
|
workspace_var_path(proj_root, compdb_dir, "${workspaceFolder}");
|
|
std::string settings_json =
|
|
"{\n"
|
|
" \"C_Cpp.default.compileCommands\": " +
|
|
json_quote(vs_compdb) +
|
|
",\n"
|
|
" \"C_Cpp.intelliSenseEngine\": \"disabled\",\n"
|
|
" \"clangd.arguments\": " +
|
|
json_array(std::vector<std::string>{"--compile-commands-dir=" + vs_compdb_dir,
|
|
"--header-insertion=never"},
|
|
json_quote) +
|
|
",\n"
|
|
" \"files.exclude\": {\n"
|
|
" \"**/.vbs\": true\n"
|
|
" }\n"
|
|
"}\n";
|
|
if (auto r = write_ide_file(proj_root / ".vscode" / "settings.json", settings_json); !r) {
|
|
return std::unexpected{r.error()};
|
|
}
|
|
}
|
|
|
|
// 3. Zed (.zed/tasks.json, .zed/debug.json).
|
|
if (want_all || options.editor == IdeKind::Zed) {
|
|
auto make_zed_task = [&](const std::string &label, const std::vector<std::string> &args) {
|
|
return " {\"label\": " + json_quote(label) + ", \"command\": " + json_quote(vbs_bin) +
|
|
", \"args\": " + json_array(args, json_quote) +
|
|
", \"cwd\": \"$ZED_WORKTREE_ROOT\"}";
|
|
};
|
|
std::vector<std::string> ztasks;
|
|
ztasks.push_back(make_zed_task("vbs: build", {"build", "--profile", graph.profile.name}));
|
|
ztasks.push_back(make_zed_task("vbs: test", {"test", "--profile", graph.profile.name}));
|
|
ztasks.push_back(make_zed_task("vbs: clean", {"clean"}));
|
|
ztasks.push_back(make_zed_task(
|
|
"vbs: install", {"install", "--profile", graph.profile.name, "--prefix",
|
|
(options.build_root / "install").string(), "--bundle-dependencies"}));
|
|
for (const auto &rt : runnables) {
|
|
ztasks.push_back(
|
|
make_zed_task("vbs: build " + rt.name,
|
|
{"build", "--profile", graph.profile.name, "--target", rt.name}));
|
|
if (rt.is_test) {
|
|
ztasks.push_back(
|
|
make_zed_task("vbs: test " + rt.name,
|
|
{"test", "--profile", graph.profile.name, "--target", rt.name}));
|
|
}
|
|
}
|
|
std::string ztasks_json = "[\n";
|
|
for (std::size_t i = 0; i < ztasks.size(); ++i) {
|
|
ztasks_json += ztasks[i];
|
|
if (i + 1 < ztasks.size()) {
|
|
ztasks_json += ',';
|
|
}
|
|
ztasks_json += '\n';
|
|
}
|
|
ztasks_json += "]\n";
|
|
if (auto r = write_ide_file(proj_root / ".zed" / "tasks.json", ztasks_json); !r) {
|
|
return std::unexpected{r.error()};
|
|
}
|
|
|
|
std::string zdebug_json = "[\n";
|
|
for (std::size_t i = 0; i < runnables.size(); ++i) {
|
|
const auto &rt = runnables[i];
|
|
const std::string prog =
|
|
workspace_var_path(proj_root, rt.program, "$ZED_WORKTREE_ROOT");
|
|
zdebug_json += " {\n";
|
|
zdebug_json += " \"label\": " + json_quote("Debug " + rt.name + " (vbs)") + ",\n";
|
|
zdebug_json += " \"adapter\": \"CodeLLDB\",\n";
|
|
zdebug_json += " \"request\": \"launch\",\n";
|
|
zdebug_json += " \"program\": " + json_quote(prog) + ",\n";
|
|
zdebug_json += " \"cwd\": \"$ZED_WORKTREE_ROOT\"\n";
|
|
zdebug_json += " }";
|
|
if (i + 1 < runnables.size()) {
|
|
zdebug_json += ',';
|
|
}
|
|
zdebug_json += '\n';
|
|
}
|
|
zdebug_json += "]\n";
|
|
if (auto r = write_ide_file(proj_root / ".zed" / "debug.json", zdebug_json); !r) {
|
|
return std::unexpected{r.error()};
|
|
}
|
|
}
|
|
|
|
// 4. CLion Custom Build Targets (.idea/customTargets.xml).
|
|
if (want_all || options.editor == IdeKind::CLion) {
|
|
const std::string vbs_xml = escape_xml_attr(vbs_bin);
|
|
const std::string prof_xml = escape_xml_attr(graph.profile.name);
|
|
std::string xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
|
|
"<project version=\"4\">\n"
|
|
" <component name=\"CLionExternalBuildManager\">\n"
|
|
" <target id=\"vbs-build\" name=\"vbs build\" defaultType=\"TOOL\">\n"
|
|
" <configuration id=\"vbs-build-cfg\" name=\"" +
|
|
prof_xml +
|
|
"\">\n"
|
|
" <build type=\"TOOL\">\n"
|
|
" <tool name=\"vbs build\" program=\"" +
|
|
vbs_xml + "\" arguments=\"build --profile " + prof_xml +
|
|
"\" workingDir=\"$PROJECT_DIR$\" />\n"
|
|
" </build>\n"
|
|
" <clean type=\"TOOL\">\n"
|
|
" <tool name=\"vbs clean\" program=\"" +
|
|
vbs_xml +
|
|
"\" arguments=\"clean\" workingDir=\"$PROJECT_DIR$\" />\n"
|
|
" </clean>\n"
|
|
" </configuration>\n"
|
|
" </target>\n"
|
|
" </component>\n"
|
|
"</project>\n";
|
|
if (auto r = write_ide_file(proj_root / ".idea" / "customTargets.xml", xml); !r) {
|
|
return std::unexpected{r.error()};
|
|
}
|
|
}
|
|
|
|
return report;
|
|
}
|
|
|
|
Void::Result::Result<CompdbQueryResult, Void::Result::Error>
|
|
query_compdb_entries(const std::filesystem::path &compdb_path, const CompdbQuery &query) {
|
|
constexpr std::size_t kMaxArguments = 256;
|
|
constexpr std::size_t kMaxArgumentBytes = 1024;
|
|
|
|
auto text = Void::FileSystem::read_file(compdb_path);
|
|
if (!text) {
|
|
return std::unexpected{text.error()};
|
|
}
|
|
auto parsed = Void::Json::Strict::parse(*text);
|
|
if (!parsed) {
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::io_error,
|
|
std::format("compilation database '{}' is not valid JSON", compdb_path.string()))};
|
|
}
|
|
const auto *entries = std::get_if<Void::Json::Strict::Value::Array>(&parsed->value);
|
|
if (!entries) {
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::io_error, "compilation database must be a JSON array")};
|
|
}
|
|
|
|
CompdbQueryResult result;
|
|
result.compdb_path = compdb_path;
|
|
for (const auto &entry : *entries) {
|
|
const auto *object = std::get_if<Void::Json::Strict::Value::Object>(&entry.value);
|
|
if (!object) {
|
|
continue;
|
|
}
|
|
const auto file_it = object->find("file");
|
|
if (file_it == object->end()) {
|
|
continue;
|
|
}
|
|
const auto *file = std::get_if<std::string>(&file_it->second.value);
|
|
if (file == nullptr) {
|
|
continue;
|
|
}
|
|
if (!query.file_filter.empty() && !std::string_view{*file}.ends_with(query.file_filter)) {
|
|
continue;
|
|
}
|
|
++result.total;
|
|
if (result.entries.size() >= query.limit) {
|
|
continue;
|
|
}
|
|
CompdbEntry projected;
|
|
projected.file = *file;
|
|
const auto read = [&](std::string_view name, std::string &out) {
|
|
if (const auto it = object->find(std::string{name}); it != object->end()) {
|
|
if (const auto *value = std::get_if<std::string>(&it->second.value)) {
|
|
out = *value;
|
|
}
|
|
}
|
|
};
|
|
read("directory", projected.directory);
|
|
read("output", projected.output);
|
|
read("command", projected.command);
|
|
if (const auto it = object->find("arguments"); it != object->end()) {
|
|
if (const auto *arguments =
|
|
std::get_if<Void::Json::Strict::Value::Array>(&it->second.value)) {
|
|
for (const auto &argument : *arguments) {
|
|
const auto *value = std::get_if<std::string>(&argument.value);
|
|
if (value == nullptr) {
|
|
continue;
|
|
}
|
|
if (projected.arguments.size() >= kMaxArguments) {
|
|
break;
|
|
}
|
|
projected.arguments.push_back(value->size() > kMaxArgumentBytes
|
|
? value->substr(0, kMaxArgumentBytes)
|
|
: *value);
|
|
}
|
|
}
|
|
}
|
|
result.entries.push_back(std::move(projected));
|
|
}
|
|
return result;
|
|
}
|
|
|
|
namespace {
|
|
|
|
Void::Result::Result<IdePluginReport, Void::Result::Error>
|
|
export_ide_plugin_assets(const IdePluginOptions &options) {
|
|
using Util::json_array;
|
|
using Util::json_quote;
|
|
|
|
std::error_code ec;
|
|
const auto output = options.output_dir.lexically_normal();
|
|
std::filesystem::create_directories(output, ec);
|
|
if (ec) {
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::io_error,
|
|
std::format("cannot create plugin directory '{}': {}", output.string(), ec.message()))};
|
|
}
|
|
|
|
IdePluginReport report;
|
|
const auto write_asset =
|
|
[&](const std::filesystem::path &path,
|
|
std::string_view content) -> Void::Result::Result<void, Void::Result::Error> {
|
|
if (!options.force && std::filesystem::exists(path, ec)) {
|
|
report.skipped_existing_files.push_back(path);
|
|
return {};
|
|
}
|
|
auto written = Platform::atomic_write_file(path, content, false);
|
|
if (!written) {
|
|
return std::unexpected{written.error()};
|
|
}
|
|
report.written_files.push_back(path);
|
|
return {};
|
|
};
|
|
|
|
const std::string project = options.project_root.lexically_normal().string();
|
|
const std::string build = options.build_root.lexically_normal().string();
|
|
|
|
struct PluginCommand {
|
|
std::string id;
|
|
std::string title;
|
|
std::vector<std::string> args;
|
|
};
|
|
const std::vector<PluginCommand> commands = {
|
|
{"vbs.build", "VBS: Build", {"build"}},
|
|
{"vbs.test", "VBS: Test", {"test"}},
|
|
{"vbs.install", "VBS: Install", {"install", "--prefix", "build/install"}},
|
|
{"vbs.package",
|
|
"VBS: Package (installer)",
|
|
{"install", "--prefix", "build/install", "--archive", "build/install/installer.sh",
|
|
"--archive-format", "sh"}},
|
|
{"vbs.daemonStart", "VBS: Start Daemon", {"daemon", "run"}},
|
|
{"vbs.daemonStatus", "VBS: Daemon Status", {"daemon", "status"}},
|
|
};
|
|
|
|
const std::string package_json =
|
|
"{\n"
|
|
" \"name\": \"vbs-tools\",\n"
|
|
" \"displayName\": \"VoidBuildSystem\",\n"
|
|
" \"description\": \"Build, test, install and package with VoidBuildSystem.\",\n"
|
|
" \"version\": \"0.1.0\",\n"
|
|
" \"publisher\": \"void\",\n"
|
|
" \"license\": \"MIT\",\n"
|
|
" \"engines\": {\"vscode\": \"^1.80.0\"},\n"
|
|
" \"categories\": [\"Other\"],\n"
|
|
" \"activationEvents\": [],\n"
|
|
" \"main\": \"./extension.js\",\n"
|
|
" \"scripts\": {\"test\": \"node test/extension.test.js\"},\n"
|
|
" \"contributes\": {\n \"commands\": " +
|
|
json_array(commands,
|
|
[](const PluginCommand &command) {
|
|
return "{\"command\":" + json_quote(command.id) +
|
|
",\"title\":" + json_quote(command.title) + '}';
|
|
}) +
|
|
"\n }\n}\n";
|
|
|
|
std::string extension_js =
|
|
"// Generated by `vbs ide plugin`. Requires the `vbs` executable in PATH or VBS_BIN.\n"
|
|
"const vscode = require('vscode');\n"
|
|
"const vbs = process.env.VBS_BIN || \"vbs\";\n\n"
|
|
"function projectArgs() {\n"
|
|
" const folders = vscode.workspace.workspaceFolders;\n"
|
|
" return folders && folders.length ? ['--project', folders[0].uri.fsPath] : [];\n"
|
|
"}\n\n"
|
|
"function runTerminal(name, args) {\n"
|
|
" const terminal = vscode.window.createTerminal({ name });\n"
|
|
" terminal.show(true);\n"
|
|
" const full = [...args, ...projectArgs()];\n"
|
|
" terminal.sendText([vbs, ...full].map((a) => (a.includes(' ') ? `'${a}'` : a)).join(' "
|
|
"'));\n"
|
|
"}\n\n"
|
|
"const commands = [\n";
|
|
for (const auto &command : commands) {
|
|
extension_js += " [" + json_quote(command.id) + ", " + json_quote(command.title) + ", " +
|
|
json_array(command.args, json_quote) + "],\n";
|
|
}
|
|
extension_js += "];\n\n"
|
|
"function activate(context) {\n"
|
|
" for (const [id, title, args] of commands) {\n"
|
|
" context.subscriptions.push(vscode.commands.registerCommand(id, () => "
|
|
"runTerminal(title, args)));\n"
|
|
" }\n"
|
|
"}\n\n"
|
|
"function deactivate() {}\n\n"
|
|
"module.exports = { activate, deactivate };\n";
|
|
|
|
// Executes the extension against a mocked VS Code API (`npm test`).
|
|
const std::string vscode_test_js =
|
|
std::string{} +
|
|
R"js(// Generated by `vbs ide plugin`: runs extension.js against a mocked VS Code API.
|
|
const Module = require('module');
|
|
const registered = new Map();
|
|
const terminals = [];
|
|
const workspace = '/tmp/vbs-workspace';
|
|
const vscodeMock = {
|
|
window: {
|
|
createTerminal: ({ name }) => ({
|
|
name,
|
|
show() {},
|
|
sendText(text) { terminals.push({ name, text }); },
|
|
}),
|
|
},
|
|
commands: {
|
|
registerCommand: (id, fn) => { registered.set(id, fn); return { dispose() {} }; },
|
|
},
|
|
workspace: { workspaceFolders: [{ uri: { fsPath: workspace } }] },
|
|
};
|
|
const originalLoad = Module._load;
|
|
Module._load = function (request) {
|
|
if (request === 'vscode') return vscodeMock;
|
|
return originalLoad.apply(this, arguments);
|
|
};
|
|
const extension = require('../extension.js');
|
|
extension.activate({ subscriptions: [] });
|
|
for (const [, fn] of registered) fn();
|
|
)js" +
|
|
"const expectedCommands = " + std::to_string(commands.size()) + ";\n" +
|
|
R"js(if (registered.size !== expectedCommands)
|
|
throw new Error('expected ' + expectedCommands + ' commands, got ' + registered.size);
|
|
if (terminals.length !== registered.size) throw new Error('every command must open a terminal');
|
|
const build = terminals.find((t) => t.name === 'VBS: Build');
|
|
if (!build) throw new Error('build command missing');
|
|
if (!build.text.includes('build')) throw new Error('build args missing: ' + build.text);
|
|
if (!build.text.includes('--project ' + workspace))
|
|
throw new Error('workspace project not injected: ' + build.text);
|
|
const install = terminals.find((t) => t.name === 'VBS: Install');
|
|
if (!install || !install.text.includes('--prefix')) throw new Error('install prefix missing');
|
|
extension.deactivate();
|
|
console.log('extension tests passed: ' + terminals.length + ' commands');
|
|
)js";
|
|
|
|
const std::string readme = std::format(
|
|
"# VoidBuildSystem editor extension\n\n"
|
|
"Generated by `vbs ide plugin` for the project at `{}`.\n\n"
|
|
"## Commands\n\n{}\n\n"
|
|
"## Install\n\n"
|
|
"```sh\ncd {} && npm install -g @vscode/vsce && vsce package\n"
|
|
"code --install-extension vbs-tools-0.1.0.vsix\n```\n\n"
|
|
"Set `VBS_BIN` if `vbs` is not on `PATH`.\n",
|
|
project,
|
|
[&] {
|
|
std::string list;
|
|
for (const auto &command : commands) {
|
|
list += "- `" + command.title + "` (`" + command.id + "`)\n";
|
|
}
|
|
return list;
|
|
}(),
|
|
output.string());
|
|
|
|
if (options.editor == IdeKind::Zed) {
|
|
std::string zed_tasks = "[\n";
|
|
for (std::size_t i = 0; i < commands.size(); ++i) {
|
|
const auto &command = commands[i];
|
|
if (i > 0) {
|
|
zed_tasks += ",\n";
|
|
}
|
|
zed_tasks += " {\"label\":" + json_quote(command.title) +
|
|
",\"command\":\"vbs\",\"args\":" + json_array(command.args, json_quote) +
|
|
",\"use_new_terminal\":false,\"allow_concurrent_runs\":false}";
|
|
}
|
|
zed_tasks += "\n]\n";
|
|
const std::string zed_manifest =
|
|
"id = \"vbs\"\n"
|
|
"name = \"VoidBuildSystem\"\n"
|
|
"description = \"Zed task assets for VoidBuildSystem (VBS).\"\n"
|
|
"version = \"0.1.0\"\n"
|
|
"schema_version = 1\n"
|
|
"authors = [\"Void contributors\"]\n"
|
|
"repository = \"https://git.faumaray.com/Void/VbsZed\"\n";
|
|
const std::string zed_readme =
|
|
"# VbsZed\n\nZed task assets for VoidBuildSystem, generated by `vbs ide plugin "
|
|
"--editor zed`.\n\nCopy `tasks.json` to `.zed/tasks.json` in your project (or install "
|
|
"this extension) and run the tasks from Zed's task menu. Set `VBS_BIN` if `vbs` is not "
|
|
"on `PATH`.\n";
|
|
|
|
for (const auto &[name, content] :
|
|
std::vector<std::pair<std::string, std::string>>{{"extension.toml", zed_manifest},
|
|
{"tasks.json", zed_tasks},
|
|
{"README.md", zed_readme}}) {
|
|
if (auto written = write_asset(output / name, content); !written) {
|
|
return std::unexpected{written.error()};
|
|
}
|
|
}
|
|
return report;
|
|
}
|
|
if (options.editor == IdeKind::CLion) {
|
|
const std::string plugin_xml =
|
|
"<idea-plugin>\n"
|
|
" <id>com.faumaray.vbs</id>\n"
|
|
" <name>VoidBuildSystem</name>\n"
|
|
" <vendor>Void</vendor>\n"
|
|
" <description>Build, test, install and package with VoidBuildSystem "
|
|
"(VBS).</description>\n"
|
|
" <depends>com.intellij.modules.platform</depends>\n"
|
|
" <depends>com.intellij.modules.cidr.lang</depends>\n"
|
|
" <actions>\n"
|
|
" <action id=\"Vbs.Build\" class=\"com.faumaray.vbs.BuildAction\"\n"
|
|
" text=\"VBS: Build\" description=\"Run vbs build in the project root\">\n"
|
|
" <add-to-group group-id=\"ToolsMenu\" anchor=\"first\"/>\n"
|
|
" </action>\n"
|
|
" <action id=\"Vbs.Install\" class=\"com.faumaray.vbs.InstallAction\"\n"
|
|
" text=\"VBS: Install\" description=\"Stage an install prefix\">\n"
|
|
" <add-to-group group-id=\"ToolsMenu\" anchor=\"after\" "
|
|
"relative-to-action=\"Vbs.Build\"/>\n"
|
|
" </action>\n"
|
|
" </actions>\n"
|
|
"</idea-plugin>\n";
|
|
const std::string gradle =
|
|
"plugins {\n"
|
|
" kotlin(\"jvm\") version \"2.0.21\"\n"
|
|
" id(\"org.jetbrains.intellij.platform\") version \"2.1.0\"\n"
|
|
"}\n\n"
|
|
"group = \"com.faumaray\"\n"
|
|
"version = \"0.1.0\"\n\n"
|
|
"repositories {\n"
|
|
" mavenCentral()\n"
|
|
" intellijPlatform { defaultRepositories() }\n"
|
|
"}\n\n"
|
|
"dependencies {\n"
|
|
" intellijPlatform { create(\"CL\", \"2024.2\") }\n"
|
|
"}\n\n"
|
|
"intellijPlatform {\n"
|
|
" pluginConfiguration { ideaVersion { sinceBuild = \"242\" } }\n"
|
|
"}\n";
|
|
const std::string action_kt =
|
|
"package com.faumaray.vbs\n\n"
|
|
"import com.intellij.execution.configurations.GeneralCommandLine\n"
|
|
"import com.intellij.execution.process.OSProcessHandler\n"
|
|
"import com.intellij.openapi.actionSystem.AnAction\n"
|
|
"import com.intellij.openapi.actionSystem.AnActionEvent\n"
|
|
"import com.intellij.openapi.project.Project\n\n"
|
|
"private fun runVbs(project: Project, title: String, args: List<String>) {\n"
|
|
" val command = GeneralCommandLine(listOf(System.getenv(\"VBS_BIN\") ?: \"vbs\") + "
|
|
"args)\n"
|
|
" .withWorkDirectory(project.basePath)\n"
|
|
" val handler = OSProcessHandler(command)\n"
|
|
" handler.startNotify()\n"
|
|
" println(\"[$title] ${command.commandLineString}\")\n"
|
|
"}\n\n"
|
|
"class BuildAction : AnAction(\"VBS: Build\") {\n"
|
|
" override fun actionPerformed(event: AnActionEvent) {\n"
|
|
" event.project?.let { runVbs(it, \"build\", listOf(\"build\")) }\n"
|
|
" }\n"
|
|
"}\n\n"
|
|
"class InstallAction : AnAction(\"VBS: Install\") {\n"
|
|
" override fun actionPerformed(event: AnActionEvent) {\n"
|
|
" event.project?.let {\n"
|
|
" runVbs(it, \"install\", listOf(\"install\", \"--prefix\", "
|
|
"\"build/install\"))\n"
|
|
" }\n"
|
|
" }\n"
|
|
"}\n";
|
|
const std::string clion_readme =
|
|
"# VbsCLion\n\nCLion (JetBrains) plugin assets for VoidBuildSystem, generated by "
|
|
"`vbs ide plugin --editor clion`.\n\nCLion can also read the CMake File API document "
|
|
"emitted by `vbs ide generate`, so this plugin is complementary: it adds Tools-menu "
|
|
"actions for `vbs build` and `vbs install`.\n\n```sh\n./gradlew "
|
|
"buildPlugin\n```\n\nSet "
|
|
"`VBS_BIN` if `vbs` is not on `PATH`.\n";
|
|
|
|
for (const auto &[name, content] : std::vector<std::pair<std::string, std::string>>{
|
|
{"src/main/resources/META-INF/plugin.xml", plugin_xml},
|
|
{"build.gradle.kts", gradle},
|
|
{"src/main/kotlin/com/faumaray/vbs/VbsActions.kt", action_kt},
|
|
{"README.md", clion_readme}}) {
|
|
if (auto written = write_asset(output / name, content); !written) {
|
|
return std::unexpected{written.error()};
|
|
}
|
|
}
|
|
return report;
|
|
}
|
|
if (options.editor != IdeKind::VsCode) {
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::unsupported,
|
|
"editor plugin assets are generated for vscode, zed and clion only")};
|
|
}
|
|
|
|
for (const auto &[name, content] : std::vector<std::pair<std::string, std::string>>{
|
|
{"package.json", package_json},
|
|
{"extension.js", extension_js},
|
|
{"test/extension.test.js", vscode_test_js},
|
|
{"README.md", readme}}) {
|
|
if (auto written = write_asset(output / name, content); !written) {
|
|
return std::unexpected{written.error()};
|
|
}
|
|
}
|
|
|
|
// Optional VSIX package: a ZIP that `code --install-extension` accepts.
|
|
if (options.vsix_path) {
|
|
const std::string vsix_manifest =
|
|
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
|
|
"<PackageManifest Version=\"2.0.0\" "
|
|
"xmlns=\"http://schemas.microsoft.com/developer/vsx-schema/2011\">\n"
|
|
" <Metadata>\n"
|
|
" <Identity Language=\"en-US\" Id=\"vbs-tools\" Version=\"0.1.0\" "
|
|
"Publisher=\"void\" />\n"
|
|
" <DisplayName>VoidBuildSystem</DisplayName>\n"
|
|
" <Description xml:space=\"preserve\">Build, test, install and package with "
|
|
"VoidBuildSystem.</Description>\n"
|
|
" <Tags>vbs</Tags>\n"
|
|
" <Categories>Other</Categories>\n"
|
|
" <GalleryFlags>Public</GalleryFlags>\n"
|
|
" </Metadata>\n"
|
|
" <Installation>\n"
|
|
" <InstallationTarget Id=\"Microsoft.VisualStudio.Code\" />\n"
|
|
" </Installation>\n"
|
|
" <Dependencies />\n"
|
|
" <Assets>\n"
|
|
" <Asset Type=\"Microsoft.VisualStudio.Code.Manifest\" "
|
|
"Path=\"extension/package.json\" Addressable=\"true\" />\n"
|
|
" </Assets>\n"
|
|
"</PackageManifest>\n";
|
|
const std::string content_types =
|
|
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
|
|
"<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">\n"
|
|
" <Default Extension=\".json\" ContentType=\"application/json\" />\n"
|
|
" <Default Extension=\".js\" ContentType=\"application/javascript\" />\n"
|
|
" <Default Extension=\".md\" ContentType=\"text/markdown\" />\n"
|
|
" <Default Extension=\".vsixmanifest\" ContentType=\"text/xml\" />\n"
|
|
" <Default Extension=\".xml\" ContentType=\"text/xml\" />\n"
|
|
"</Types>\n";
|
|
const auto manifest_path = output / ".vsix" / "extension.vsixmanifest";
|
|
const auto types_path = output / ".vsix" / "[Content_Types].xml";
|
|
if (auto written = Platform::atomic_write_file(manifest_path, vsix_manifest, true);
|
|
!written) {
|
|
return std::unexpected{written.error()};
|
|
}
|
|
if (auto written = Platform::atomic_write_file(types_path, content_types, true); !written) {
|
|
return std::unexpected{written.error()};
|
|
}
|
|
std::vector<Package::ArchiveEntrySpec> vsix_entries{
|
|
{"extension.vsixmanifest", manifest_path, 0644u},
|
|
{"[Content_Types].xml", types_path, 0644u}};
|
|
for (const auto &name :
|
|
{"package.json", "extension.js", "README.md", "test/extension.test.js"}) {
|
|
vsix_entries.push_back({std::string{"extension/"} + name, output / name, 0644u});
|
|
}
|
|
if (options.vsix_path->has_parent_path()) {
|
|
std::filesystem::create_directories(options.vsix_path->parent_path(), ec);
|
|
}
|
|
if (auto zipped = Package::create_stored_zip(*options.vsix_path, vsix_entries); !zipped) {
|
|
return std::unexpected{zipped.error()};
|
|
}
|
|
std::filesystem::remove_all(output / ".vsix", ec);
|
|
}
|
|
return report;
|
|
}
|
|
|
|
std::string file_api_target_type(TargetKind kind) {
|
|
switch (kind) {
|
|
case TargetKind::Executable:
|
|
case TargetKind::Test:
|
|
return "EXECUTABLE";
|
|
case TargetKind::StaticLibrary:
|
|
return "STATIC_LIBRARY";
|
|
case TargetKind::SharedLibrary:
|
|
return "SHARED_LIBRARY";
|
|
case TargetKind::HeaderOnly:
|
|
return "INTERFACE_LIBRARY";
|
|
case TargetKind::ObjectLibrary:
|
|
return "OBJECT_LIBRARY";
|
|
case TargetKind::CustomAction:
|
|
return "UTILITY";
|
|
}
|
|
return "UTILITY";
|
|
}
|
|
|
|
std::string safe_file_token(std::string_view text) {
|
|
std::string out;
|
|
for (const char c : text) {
|
|
out.push_back(
|
|
(std::isalnum(static_cast<unsigned char>(c)) != 0 || c == '.' || c == '_' || c == '-')
|
|
? c
|
|
: '_');
|
|
}
|
|
return out.empty() ? std::string{"project"} : out;
|
|
}
|
|
|
|
// Emits a CMake File API (codemodel-v2) reply tree so CMake-aware IDEs can consume VBS
|
|
// projects. The reply directory is entirely VBS-owned and regenerated on every run.
|
|
Void::Result::Result<void, Void::Result::Error>
|
|
emit_cmake_file_api(const Graph::BuildGraph &graph, const std::filesystem::path &project_root,
|
|
const std::filesystem::path &build_root) {
|
|
using Util::json_array;
|
|
using Util::json_quote;
|
|
|
|
const auto reply_dir = build_root / ".cmake" / "api" / "v1" / "reply";
|
|
std::error_code ec;
|
|
std::filesystem::remove_all(reply_dir, ec);
|
|
std::filesystem::create_directories(reply_dir, ec);
|
|
if (ec) {
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::io_error,
|
|
std::format("cannot create CMake File API reply directory '{}': {}", reply_dir.string(),
|
|
ec.message()))};
|
|
}
|
|
|
|
auto write_reply =
|
|
[&](const std::string &file_name,
|
|
std::string_view content) -> Void::Result::Result<void, Void::Result::Error> {
|
|
if (auto written = Platform::atomic_write_file(reply_dir / file_name, content, false);
|
|
!written) {
|
|
return std::unexpected{written.error()};
|
|
}
|
|
return {};
|
|
};
|
|
|
|
const std::string version_block = "{\"major\":2,\"minor\":0}";
|
|
std::vector<std::string> target_json_files;
|
|
std::vector<std::string> target_ids;
|
|
|
|
for (const auto &target : graph.targets) {
|
|
std::string compile_groups = "[";
|
|
bool first_group = true;
|
|
for (const auto &action : graph.actions) {
|
|
if (action.target_name != target.name) {
|
|
continue;
|
|
}
|
|
if (action.kind != Graph::ActionKind::Compile &&
|
|
action.kind != Graph::ActionKind::PrecompiledHeader &&
|
|
action.kind != Graph::ActionKind::HeaderUnit) {
|
|
continue;
|
|
}
|
|
std::vector<std::size_t> source_indexes;
|
|
const auto source_it =
|
|
std::ranges::find(target.expanded_sources, action.logical_source_file);
|
|
if (source_it != target.expanded_sources.end()) {
|
|
source_indexes.push_back(static_cast<std::size_t>(
|
|
std::distance(target.expanded_sources.begin(), source_it)));
|
|
}
|
|
if (!first_group) {
|
|
compile_groups += ',';
|
|
}
|
|
first_group = false;
|
|
compile_groups += "{\"sourceIndexes\":" + json_array(source_indexes, [](std::size_t i) {
|
|
return std::to_string(i);
|
|
});
|
|
compile_groups += ",\"language\":" + json_quote(action.is_c_source ? "C" : "CXX");
|
|
compile_groups += ",\"compileCommandFragments\":" +
|
|
json_array(action.arguments, [](const std::string &argument) {
|
|
return "{\"fragment\":" + Util::json_quote(argument) + '}';
|
|
});
|
|
compile_groups +=
|
|
",\"defines\":" + json_array(action.defines, [](const std::string &d) {
|
|
return "{\"define\":" + Util::json_quote(d) + '}';
|
|
});
|
|
compile_groups +=
|
|
",\"includes\":" +
|
|
json_array(action.physical_include_dirs, [](const auto &include) {
|
|
return "{\"path\":" + Util::json_quote(include.first.string()) + '}';
|
|
});
|
|
compile_groups += '}';
|
|
}
|
|
compile_groups += ']';
|
|
|
|
std::string target_json =
|
|
"{\"kind\":\"target\",\"version\":" + version_block +
|
|
",\"name\":" + json_quote(target.name) +
|
|
",\"type\":" + json_quote(file_api_target_type(target.kind)) + ",\"artifacts\":" +
|
|
json_array(target.primary_outputs,
|
|
[](const std::filesystem::path &p) {
|
|
return "{\"path\":" + Util::json_quote(p.string()) + '}';
|
|
}) +
|
|
",\"nameOnDisk\":" +
|
|
json_quote(target.primary_outputs.empty()
|
|
? std::string{}
|
|
: target.primary_outputs.front().filename().string()) +
|
|
",\"paths\":{\"source\":" + json_quote(graph.project_root.string()) +
|
|
",\"build\":" + json_quote(graph.profile_build_dir.string()) + "},\"sources\":" +
|
|
json_array(target.expanded_sources,
|
|
[](const std::filesystem::path &p) {
|
|
return "{\"path\":" + Util::json_quote(p.string()) + '}';
|
|
}) +
|
|
",\"compileGroups\":" + compile_groups + '}';
|
|
|
|
const std::string file_name = "target-" + safe_file_token(target.name) + "-" +
|
|
Util::sha256_hex(target_json).substr(0, 16) + ".json";
|
|
if (auto written = write_reply(file_name, target_json); !written) {
|
|
return written;
|
|
}
|
|
target_json_files.push_back(file_name);
|
|
target_ids.push_back(target.name);
|
|
}
|
|
|
|
std::string target_refs;
|
|
for (std::size_t i = 0; i < target_json_files.size(); ++i) {
|
|
if (i > 0) {
|
|
target_refs += ',';
|
|
}
|
|
target_refs += "{\"directoryIndex\":0,\"id\":" + json_quote(":" + target_ids[i]) +
|
|
",\"jsonFile\":" + json_quote(target_json_files[i]) +
|
|
",\"name\":" + json_quote(target_ids[i]) +
|
|
",\"projectIndex\":0,\"targetIndex\":" + std::to_string(i) + '}';
|
|
}
|
|
const std::string directory_json =
|
|
"{\"kind\":\"directory\",\"version\":" + version_block +
|
|
",\"paths\":{\"build\":" + json_quote(build_root.string()) +
|
|
",\"source\":" + json_quote(project_root.string()) +
|
|
"},\"projectIndexes\":[0],\"targetIndexes\":" +
|
|
json_array(std::views::iota(std::size_t{0}, target_json_files.size()),
|
|
[](std::size_t i) { return std::to_string(i); }) +
|
|
'}';
|
|
const std::string directory_file =
|
|
"directory-.-" + Util::sha256_hex(directory_json).substr(0, 16) + ".json";
|
|
if (auto written = write_reply(directory_file, directory_json); !written) {
|
|
return written;
|
|
}
|
|
|
|
const std::string codemodel_json =
|
|
"{\"kind\":\"codemodel\",\"version\":" + version_block +
|
|
",\"paths\":{\"source\":" + json_quote(project_root.string()) +
|
|
",\"build\":" + json_quote(build_root.string()) +
|
|
"},\"configurations\":[{\"name\":" + json_quote(graph.profile.name) +
|
|
",\"projects\":[{\"name\":" + json_quote(project_root.filename().string()) +
|
|
",\"targetIndexes\":" +
|
|
json_array(std::views::iota(std::size_t{0}, target_json_files.size()),
|
|
[](std::size_t i) { return std::to_string(i); }) +
|
|
"}],\"directories\":[{\"source\":" + json_quote(project_root.string()) +
|
|
",\"build\":" + json_quote(build_root.string()) +
|
|
",\"jsonFile\":" + json_quote(directory_file) +
|
|
",\"projectIndexes\":[0],\"targetIndexes\":" +
|
|
json_array(std::views::iota(std::size_t{0}, target_json_files.size()),
|
|
[](std::size_t i) { return std::to_string(i); }) +
|
|
"}],\"targets\":[" + target_refs + "]}]}";
|
|
const std::string codemodel_file =
|
|
"codemodel-v2-" + Util::sha256_hex(codemodel_json).substr(0, 16) + ".json";
|
|
if (auto written = write_reply(codemodel_file, codemodel_json); !written) {
|
|
return written;
|
|
}
|
|
|
|
// cmakeFiles-v1: configure inputs/outputs, so IDEs can track project files.
|
|
std::vector<std::string> configure_inputs{json_quote(project_root.string())};
|
|
for (const auto &candidate : {"build.cpp", "build.profiles.cpp", "workspace.cpp"}) {
|
|
const auto path = project_root / candidate;
|
|
std::error_code file_ec;
|
|
if (std::filesystem::is_regular_file(path, file_ec)) {
|
|
configure_inputs.push_back(json_quote(path.string()));
|
|
}
|
|
}
|
|
const std::string cmake_files_json =
|
|
"{\"kind\":\"cmakeFiles\",\"version\":" + version_block +
|
|
",\"paths\":{\"source\":" + json_quote(project_root.string()) +
|
|
",\"build\":" + json_quote(build_root.string()) + "},\"inputs\":" +
|
|
json_array(configure_inputs,
|
|
[](const std::string &entry) { return "{\"path\":" + entry + '}'; }) +
|
|
",\"outputs\":[{\"path\":" + json_quote((build_root / "compile_commands.json").string()) +
|
|
"}]}";
|
|
const std::string cmake_files_file =
|
|
"cmakeFiles-v1-" + Util::sha256_hex(cmake_files_json).substr(0, 16) + ".json";
|
|
if (auto written = write_reply(cmake_files_file, cmake_files_json); !written) {
|
|
return written;
|
|
}
|
|
|
|
// toolchains-v1: compiler identity for C and CXX.
|
|
std::vector<std::string> toolchain_files;
|
|
for (const auto &[language, compiler, extensions] :
|
|
std::vector<std::tuple<std::string, std::filesystem::path, std::vector<std::string>>>{
|
|
{"CXX",
|
|
graph.toolchain.cxx_compiler,
|
|
{".cpp", ".cc", ".cxx", ".c++", ".mpp", ".cppm", ".ixx"}},
|
|
{"C", graph.toolchain.c_compiler, {".c"}}}) {
|
|
const std::string toolchain_json =
|
|
"{\"kind\":\"toolchain\",\"version\":" + version_block +
|
|
",\"language\":" + json_quote(language) +
|
|
",\"compiler\":{\"id\":" + json_quote(compiler_name(graph.toolchain.family)) +
|
|
",\"path\":" + json_quote(compiler.string()) +
|
|
"},\"sourceFileExtensions\":" + json_array(extensions, json_quote) +
|
|
",\"implicit\":{\"includeDirectories\":[],\"linkDirectories\":[],"
|
|
"\"linkFrameworkDirectories\":[],\"linkLibraries\":[]}}";
|
|
const std::string toolchain_file =
|
|
"toolchains-v1-" + Util::sha256_hex(toolchain_json).substr(0, 16) + ".json";
|
|
if (auto written = write_reply(toolchain_file, toolchain_json); !written) {
|
|
return written;
|
|
}
|
|
toolchain_files.push_back(toolchain_file);
|
|
}
|
|
|
|
// cache-v2: the effective configuration values an IDE shows in its settings.
|
|
const std::vector<std::pair<std::string, std::string>> cache_entries{
|
|
{"CMAKE_BUILD_TYPE", graph.profile.name},
|
|
{"CMAKE_C_COMPILER", graph.toolchain.c_compiler.string()},
|
|
{"CMAKE_CXX_COMPILER", graph.toolchain.cxx_compiler.string()},
|
|
{"CMAKE_GENERATOR", "VBS"},
|
|
{"VBS_PROFILE", graph.profile.name},
|
|
{"VBS_PROJECT_ROOT", project_root.string()},
|
|
};
|
|
std::string cache_json = "{\"kind\":\"cache\",\"version\":" + version_block + ",\"entries\":[";
|
|
for (std::size_t i = 0; i < cache_entries.size(); ++i) {
|
|
if (i > 0) {
|
|
cache_json += ',';
|
|
}
|
|
const auto &[name, value] = cache_entries[i];
|
|
cache_json +=
|
|
"{\"name\":" + json_quote(name) +
|
|
",\"properties\":[{\"name\":\"HELPSTRING\","
|
|
"\"value\":\"\"},{\"name\":\"TYPE\",\"value\":\"STRING\"},{\"name\":\"VALUE\","
|
|
"\"value\":" +
|
|
json_quote(value) + "}],\"type\":\"STRING\",\"value\":" + json_quote(value) + '}';
|
|
}
|
|
cache_json += "]}";
|
|
const std::string cache_file =
|
|
"cache-v2-" + Util::sha256_hex(cache_json).substr(0, 16) + ".json";
|
|
if (auto written = write_reply(cache_file, cache_json); !written) {
|
|
return written;
|
|
}
|
|
|
|
const std::string index_json =
|
|
"{\"cmake\":{\"generator\":{\"multiConfig\":false},\"version\":{\"major\":0,"
|
|
"\"minor\":1,\"patch\":0,\"string\":\"" +
|
|
std::string{Bootstrap::version} +
|
|
"\"}},\"reply\":{\"cache-v2\":{\"jsonFile\":" + json_quote(cache_file) +
|
|
",\"kind\":\"cache\",\"version\":" + version_block +
|
|
"},\"cmakeFiles-v1\":{\"jsonFile\":" + json_quote(cmake_files_file) +
|
|
",\"kind\":\"cmakeFiles\",\"version\":" + version_block +
|
|
"},\"codemodel-v2\":{\"jsonFile\":" + json_quote(codemodel_file) +
|
|
",\"kind\":\"codemodel\",\"version\":" + version_block +
|
|
"},\"toolchains-v1\":{\"jsonFile\":" +
|
|
(toolchain_files.empty() ? std::string{"\"\""} : json_quote(toolchain_files.front())) +
|
|
",\"kind\":\"toolchain\",\"version\":" + version_block + "}}}";
|
|
const std::string index_file = "index-" + Util::sha256_hex(index_json).substr(0, 16) + ".json";
|
|
return write_reply(index_file, index_json);
|
|
}
|
|
|
|
} // namespace
|
|
|
|
std::string format_ide_query_json(const Graph::BuildGraph &graph,
|
|
const std::filesystem::path &compdb_path,
|
|
const std::filesystem::path &sdk_include_dir) {
|
|
using Util::json_array;
|
|
using Util::json_quote;
|
|
|
|
const auto build_root = graph.profile_build_dir.parent_path().parent_path().lexically_normal();
|
|
std::string out = "{";
|
|
out += "\"schema_version\":1";
|
|
out += ",\"project_root\":" + json_quote(graph.project_root.string());
|
|
out += ",\"build_root\":" + json_quote(build_root.string());
|
|
out += ",\"profile\":" + json_quote(graph.profile.name);
|
|
out += ",\"profile_identity\":" + json_quote(graph.profile_identity);
|
|
out += ",\"compiler_family\":" + json_quote(compiler_name(graph.toolchain.family));
|
|
out += ",\"c_compiler\":" + json_quote(graph.toolchain.c_compiler.string());
|
|
out += ",\"cxx_compiler\":" + json_quote(graph.toolchain.cxx_compiler.string());
|
|
out += ",\"sdk_include_dir\":" + json_quote(sdk_include_dir.string());
|
|
out += ",\"compdb_path\":" + json_quote(compdb_path.string());
|
|
out += ",\"targets\":[";
|
|
for (std::size_t i = 0; i < graph.targets.size(); ++i) {
|
|
const auto &t = graph.targets[i];
|
|
if (i > 0) {
|
|
out += ',';
|
|
}
|
|
const bool is_exec = (t.kind == TargetKind::Executable);
|
|
const bool is_test = (t.kind == TargetKind::Test);
|
|
out += "{\"name\":" + json_quote(t.name);
|
|
out += ",\"kind\":" + json_quote(target_kind_name(t.kind));
|
|
out += ",\"enabled\":" + std::string{t.enabled ? "true" : "false"};
|
|
out += ",\"is_executable\":" + std::string{is_exec ? "true" : "false"};
|
|
out += ",\"is_test\":" + std::string{is_test ? "true" : "false"};
|
|
out += ",\"sources\":" + json_array(t.expanded_sources, [](const std::filesystem::path &p) {
|
|
return json_quote(p.string());
|
|
});
|
|
out += ",\"primary_outputs\":" +
|
|
json_array(t.primary_outputs,
|
|
[](const std::filesystem::path &p) { return json_quote(p.string()); });
|
|
out += ",\"runtime_shared_libraries\":" +
|
|
json_array(t.runtime_shared_libraries,
|
|
[](const std::filesystem::path &p) { return json_quote(p.string()); });
|
|
out += '}';
|
|
}
|
|
out += "]}\n";
|
|
return out;
|
|
}
|
|
|
|
Void::Result::Result<IdePluginReport, Void::Result::Error>
|
|
generate_ide_plugin_assets(const IdePluginOptions &options) {
|
|
return export_ide_plugin_assets(options);
|
|
}
|
|
|
|
} // namespace Void::Build::Editor
|