-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathInstallCommand.cpp
More file actions
4750 lines (4134 loc) · 155 KB
/
Copy pathInstallCommand.cpp
File metadata and controls
4750 lines (4134 loc) · 155 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
*
* @file InstallCommand.cpp
* @author Gaspard Kirira
*
* Copyright 2025, Gaspard Kirira. All rights reserved.
* https://github.com/vixcpp/vix
* Use of this source code is governed by a MIT license
* that can be found in the License file.
*
* Vix.cpp
*
*/
#include <vix/cli/commands/InstallCommand.hpp>
#include <vix/cli/commands/RegistryCommand.hpp>
#include <vix/cli/commands/run/detail/RunnableExecutableResolver.hpp>
#include <vix/cli/app/AppManifest.hpp>
#include <vix/cli/modules/ModuleGraph.hpp>
#include <vix/cli/modules/ModuleManifest.hpp>
#include <vix/cli/modules/DependencyOwnership.hpp>
#include <vix/cli/modules/DependencyConstraints.hpp>
#include <vix/cli/util/Ui.hpp>
#include <vix/cli/util/Shell.hpp>
#include <vix/cli/util/Hash.hpp>
#include <vix/cli/Style.hpp>
#include <vix/process/Process.hpp>
#include <vix/utils/Env.hpp>
#include <vix/cli/util/Semver.hpp>
#include <vix/cli/util/GitProgress.hpp>
#include <vix/cli/util/ProjectMutation.hpp>
#include <nlohmann/json.hpp>
#include <algorithm>
#include <chrono>
#include <ctime>
#include <cctype>
#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <optional>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
#include <queue>
#include <unordered_map>
#include <unordered_set>
#include <mutex>
#ifdef _WIN32
#include <io.h>
#else
#include <unistd.h>
#endif
namespace fs = std::filesystem;
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#endif
using json = nlohmann::json;
namespace vix::commands
{
using namespace vix::cli::style;
namespace
{
struct ParsedArgs
{
bool globalMode{false};
std::string globalSpec;
std::string gitSpec;
std::string gitName;
std::string gitTag;
std::string gitBranch;
std::string gitRev;
std::string gitTarget;
std::string gitSubdirectory;
std::string gitInclude;
std::string module;
bool gitHeaderOnly{false};
bool allowPrerelease{false};
bool yes{false};
};
struct PkgSpec
{
std::string ns;
std::string name;
std::string requestedVersion;
std::string resolvedVersion;
std::string id() const
{
return ns + "/" + name;
}
};
static void split_compact_git_revision(struct ParsedArgs &parsed);
struct DepResolved
{
std::string id;
std::string version;
std::string repo;
std::string tag;
std::string commit;
std::string hash;
std::string hashAlgorithm;
int hashVersion{0};
std::string source{"registry"};
std::string requested;
std::string subdirectory;
bool headerOnly{false};
std::vector<std::string> includes;
std::vector<std::pair<std::string, std::string>> cmakeOptions;
std::string type;
std::string include{"include"};
std::vector<std::string> dependencies;
std::vector<std::string> cmakeTargets;
json extensions;
fs::path checkout;
fs::path linkDir;
};
static std::string home_dir()
{
#ifdef _WIN32
const char *home = vix::utils::vix_getenv("USERPROFILE");
#else
const char *home = vix::utils::vix_getenv("HOME");
#endif
return home ? std::string(home) : std::string();
}
static fs::path vix_root()
{
const std::string h = home_dir();
if (h.empty())
return fs::path(".vix");
return fs::path(h) / ".vix";
}
static fs::path registry_dir()
{
return vix_root() / "registry" / "index";
}
static fs::path registry_index_dir()
{
return registry_dir() / "index";
}
static fs::path store_git_dir()
{
return vix_root() / "store" / "git";
}
static fs::path git_cache_dir()
{
return vix_root() / "cache" / "git";
}
static fs::path lock_path()
{
return fs::current_path() / "vix.lock";
}
static fs::path project_vix_dir()
{
return fs::current_path() / ".vix";
}
static fs::path project_deps_dir()
{
return project_vix_dir() / "deps";
}
static fs::path project_deps_cmake()
{
return project_vix_dir() / "vix_deps.cmake";
}
static fs::path global_root_dir()
{
if (const char *p = vix::utils::vix_getenv("VIX_GLOBAL_PREFIX"); p && *p)
return fs::path(p);
return vix_root() / "global";
}
static fs::path global_pkgs_dir()
{
return global_root_dir() / "packages";
}
static fs::path global_manifest_path()
{
return global_root_dir() / "installed.json";
}
static fs::path global_bin_dir()
{
return global_root_dir() / "bin";
}
static fs::path global_build_dir()
{
return global_root_dir() / "build";
}
static fs::path global_tmp_dir()
{
return global_root_dir() / "tmp";
}
static std::string trim_copy(std::string s)
{
auto isws = [](unsigned char c)
{ return std::isspace(c) != 0; };
while (!s.empty() && isws(static_cast<unsigned char>(s.front())))
s.erase(s.begin());
while (!s.empty() && isws(static_cast<unsigned char>(s.back())))
s.pop_back();
return s;
}
static std::string format_elapsed(std::chrono::steady_clock::duration d)
{
const auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(d).count();
if (ms < 1000)
return std::to_string(ms) + "ms";
if (ms < 10000)
{
const auto seconds = ms / 1000;
const auto tenths = (ms % 1000) / 100;
return std::to_string(seconds) + "." + std::to_string(tenths) + "s";
}
return std::to_string((ms + 500) / 1000) + "s";
}
static json read_json_or_throw(const fs::path &p)
{
std::ifstream in(p);
if (!in)
throw std::runtime_error("cannot open: " + p.string());
json j;
in >> j;
return j;
}
static void write_json_or_throw(const fs::path &p, const json &j)
{
std::error_code ec;
fs::create_directories(p.parent_path(), ec);
const fs::path tmp = p.string() + ".tmp";
{
std::ofstream out(tmp);
if (!out)
throw std::runtime_error("cannot write: " + tmp.string());
out << j.dump(2) << "\n";
}
fs::rename(tmp, p, ec);
if (ec)
{
ec.clear();
fs::remove(p, ec);
ec.clear();
fs::rename(tmp, p, ec);
if (ec)
throw std::runtime_error("cannot replace: " + p.string() + ": " + ec.message());
}
}
static std::string sanitize_id_dot(const std::string &id)
{
std::string s = id;
for (char &c : s)
{
if (c == '/')
c = '.';
}
return s;
}
static std::string cmake_safe_target(const std::string &id)
{
std::string out = "vix__";
for (char c : id)
{
if (std::isalnum(static_cast<unsigned char>(c)))
out.push_back(c);
else
out += "__";
}
return out;
}
static std::string cmake_alias_target(const std::string &id)
{
const auto slash = id.find('/');
if (slash == std::string::npos)
return id;
return id.substr(0, slash) + "::" + id.substr(slash + 1);
}
static bool starts_with_local(const std::string &s, const std::string &prefix);
static bool is_supported_git_url(const std::string &url);
static std::vector<std::string> cmake_dependency_aliases(const DepResolved &dep)
{
std::vector<std::string> aliases;
aliases.reserve(dep.dependencies.size());
for (const std::string &id : dep.dependencies)
{
const std::string alias = cmake_alias_target(id);
if (!alias.empty())
aliases.push_back(alias);
}
std::sort(aliases.begin(), aliases.end());
aliases.erase(std::unique(aliases.begin(), aliases.end()), aliases.end());
return aliases;
}
static fs::path store_checkout_path(const std::string &id, const std::string &commit)
{
return store_git_dir() / sanitize_id_dot(id) / commit;
}
static fs::path git_cache_checkout_path(const std::string &url, const std::string &commit);
static int install_project_dependencies(bool lockAlreadyHeld = false);
static fs::path entry_path(const std::string &ns, const std::string &name)
{
return registry_index_dir() / (ns + "." + name + ".json");
}
static bool parse_pkg_spec(const std::string &raw_in, PkgSpec &out)
{
const std::string raw = trim_copy(raw_in);
const auto slash = raw.find('/');
if (slash == std::string::npos)
return false;
if (!raw.empty() && raw[0] == '@')
{
if (slash <= 1)
return false;
out.ns = trim_copy(raw.substr(1, slash - 1));
}
else
{
out.ns = trim_copy(raw.substr(0, slash));
}
const auto at_version = raw.find('@', slash + 1);
if (at_version == std::string::npos)
{
out.name = trim_copy(raw.substr(slash + 1));
out.requestedVersion.clear();
}
else
{
out.name = trim_copy(raw.substr(slash + 1, at_version - (slash + 1)));
out.requestedVersion = trim_copy(raw.substr(at_version + 1));
}
out.resolvedVersion.clear();
if (out.ns.empty() || out.name.empty())
return false;
if (at_version != std::string::npos && out.requestedVersion.empty())
return false;
return true;
}
static int resolve_version_v1(const json &entry, PkgSpec &spec)
{
if (!entry.contains("versions") || !entry["versions"].is_object())
{
vix::cli::util::err_line(
std::cerr,
"invalid registry entry: missing versions for " + spec.id());
return 1;
}
std::vector<std::string> versions;
versions.reserve(entry["versions"].size());
for (auto it = entry["versions"].begin(); it != entry["versions"].end(); ++it)
versions.push_back(it.key());
if (versions.empty())
{
vix::cli::util::err_line(
std::cerr,
"no versions available for: " + spec.id());
return 1;
}
if (spec.requestedVersion.empty())
{
spec.resolvedVersion = vix::cli::util::semver::findLatest(versions);
return 0;
}
const auto resolved =
vix::cli::util::semver::resolveMaxSatisfying(
versions,
spec.requestedVersion);
if (!resolved.has_value())
{
vix::cli::util::err_line(
std::cerr,
"no version matches range: " + spec.id() + "@" + spec.requestedVersion);
return 1;
}
spec.resolvedVersion = *resolved;
return 0;
}
static int ensure_registry_present()
{
if (fs::exists(registry_dir()) && fs::exists(registry_index_dir()))
return 0;
vix::cli::util::err_line(std::cerr, "registry not synced");
vix::cli::util::warn_line(std::cerr, "Run: vix registry sync");
return 1;
}
static vix::process::ProcessOutput run_process(
const std::string &program,
std::vector<std::string> args,
const fs::path &cwd);
static bool install_progress_is_tty()
{
#ifdef _WIN32
if (_isatty(_fileno(stdout)) == 0)
return false;
#else
if (::isatty(STDOUT_FILENO) == 0)
return false;
#endif
const char *term = std::getenv("TERM");
return (!term || std::string_view(term) != "dumb") && std::getenv("NO_COLOR") == nullptr;
}
class GitInstallProgress
{
public:
GitInstallProgress(std::string dependency, std::size_t packageIndex, std::size_t packageCount)
: dependency_(std::move(dependency)), packageIndex_(packageIndex), packageCount_(packageCount), started_(std::chrono::steady_clock::now()), tty_(install_progress_is_tty()), parser_([this](const auto &event)
{ render(event); }) {}
void push(std::string_view chunk) { parser_.push(chunk); }
// A clone can spend a long time establishing the transport before Git
// reports object progress. This is a real phase, not synthetic byte
// progress, so make it visible immediately.
void phase(std::string_view name)
{
vix::cli::util::GitProgressEvent event;
event.phase = std::string(name);
render(event);
}
void finish()
{
parser_.finish();
if (visible_)
{
std::cout << "\r\033[2K" << std::flush;
visible_ = false;
}
}
private:
void render(const vix::cli::util::GitProgressEvent &event)
{
// CI output must remain useful without terminal control sequences.
const auto now = std::chrono::steady_clock::now();
// The first measurable Git event is deliberately not delayed. The
// old delay made a real remote operation look hung.
if (visible_ && event.phase == lastPhase_ && now - lastRender_ < std::chrono::milliseconds(100))
return;
std::ostringstream line;
line << " " << CYAN << "•" << RESET << " " << CYAN << BOLD << dependency_ << RESET;
if (packageCount_ > 1)
line << " " << GRAY << "(" << (packageIndex_ + 1) << "/" << packageCount_ << " packages)" << RESET;
line << " " << GRAY << event.phase;
if (event.percent)
line << " " << *event.percent << "%";
if (!event.transferred.empty())
line << " " << event.transferred;
if (!event.speed.empty())
line << " " << event.speed;
line << RESET;
if (tty_)
std::cout << "\r\033[2K" << line.str() << std::flush;
else
std::cout << dependency_ << ": " << event.phase
<< (event.percent ? std::string(" ") + std::to_string(*event.percent) + "%" : "") << "\n"
<< std::flush;
visible_ = true;
lastRender_ = now;
lastPhase_ = event.phase;
}
std::string dependency_;
std::size_t packageIndex_{};
std::size_t packageCount_{};
std::chrono::steady_clock::time_point started_, lastRender_{};
bool tty_{false}, visible_{false};
std::string lastPhase_;
vix::cli::util::GitProgressParser parser_;
};
static vix::process::ProcessOutput run_git_clone_streamed(
std::vector<std::string> args, const fs::path &cwd, const std::string &dependency,
std::size_t packageIndex = 0, std::size_t packageCount = 1)
{
GitInstallProgress progress(dependency, packageIndex, packageCount);
progress.phase("connecting");
vix::process::Command command("git");
command.args(std::move(args));
command.search_in_path(true);
if (!cwd.empty())
command.cwd(cwd.string());
const auto result = vix::process::output_streamed(std::move(command), {{}, [&progress](std::string_view chunk)
{ progress.push(chunk); }});
progress.finish();
if (result)
return result.value();
vix::process::ProcessOutput output;
output.exit_code = 127;
output.stderr_text = result.error().message();
return output;
}
static int clone_checkout(
const std::string &repoUrl,
const std::string &idDot,
const std::string &commit,
std::string &outDir)
{
fs::create_directories(store_git_dir());
const fs::path dst = store_git_dir() / idDot / commit;
outDir = dst.string();
if (fs::exists(dst))
return 0;
fs::create_directories(dst.parent_path());
const auto clone = run_git_clone_streamed(
{"clone", "--progress", "-q", repoUrl, dst.string()},
{}, idDot);
if (!clone.success())
return clone.exit_code == 0 ? 1 : clone.exit_code;
const auto checkout = run_process(
"git",
{"-c", "advice.detachedHead=false", "checkout", "-q", commit},
dst);
if (!checkout.success())
return checkout.exit_code == 0 ? 1 : checkout.exit_code;
return 0;
}
static void remove_all_if_exists(const fs::path &p)
{
std::error_code ec;
const auto status = fs::symlink_status(p, ec);
if (ec)
return;
if (status.type() == fs::file_type::not_found)
return;
fs::remove_all(p, ec);
}
static void ensure_symlink_or_copy_dir(const fs::path &src, const fs::path &dst)
{
std::error_code ec;
remove_all_if_exists(dst);
#ifdef _WIN32
fs::create_directories(dst, ec);
fs::copy(
src,
dst,
fs::copy_options::recursive |
fs::copy_options::copy_symlinks |
fs::copy_options::overwrite_existing,
ec);
if (ec)
throw std::runtime_error("failed to copy dependency: " + dst.string());
#else
fs::create_directories(dst.parent_path(), ec);
fs::create_directory_symlink(src, dst, ec);
if (ec)
{
ec.clear();
fs::create_directories(dst, ec);
fs::copy(
src,
dst,
fs::copy_options::recursive |
fs::copy_options::copy_symlinks |
fs::copy_options::overwrite_existing,
ec);
if (ec)
throw std::runtime_error("failed to link/copy dependency: " + dst.string());
}
#endif
}
static std::string next_arg_value(const std::vector<std::string> &args, std::size_t &i, const std::string &flag)
{
if (i + 1 >= args.size())
throw std::runtime_error("missing value for " + flag);
++i;
return args[i];
}
static ParsedArgs parse_args(const std::vector<std::string> &args)
{
ParsedArgs parsed;
for (std::size_t i = 0; i < args.size(); ++i)
{
const std::string &arg = args[i];
if (arg == "-g" || arg == "--global")
{
parsed.globalMode = true;
if (i + 1 < args.size())
{
parsed.globalSpec = args[i + 1];
++i;
}
}
else if (arg == "--yes" || arg == "-y")
{
parsed.yes = true;
}
else if (arg == "--name")
parsed.gitName = next_arg_value(args, i, arg);
else if (arg == "--tag")
parsed.gitTag = next_arg_value(args, i, arg);
else if (arg == "--branch")
parsed.gitBranch = next_arg_value(args, i, arg);
else if (arg == "--rev" || arg == "--commit")
parsed.gitRev = next_arg_value(args, i, arg);
else if (arg == "--target")
parsed.gitTarget = next_arg_value(args, i, arg);
else if (arg == "--subdirectory" || arg == "--subdir")
parsed.gitSubdirectory = next_arg_value(args, i, arg);
else if (arg == "--include")
parsed.gitInclude = next_arg_value(args, i, arg);
else if (arg == "--module" || arg == "-m")
parsed.module = next_arg_value(args, i, arg);
else if (arg == "--header-only" || arg == "--headers")
parsed.gitHeaderOnly = true;
else if (arg == "--pre" || arg == "--prerelease")
parsed.allowPrerelease = true;
else if (starts_with_local(arg, "--name="))
parsed.gitName = arg.substr(std::string("--name=").size());
else if (starts_with_local(arg, "--tag="))
parsed.gitTag = arg.substr(std::string("--tag=").size());
else if (starts_with_local(arg, "--branch="))
parsed.gitBranch = arg.substr(std::string("--branch=").size());
else if (starts_with_local(arg, "--rev="))
parsed.gitRev = arg.substr(std::string("--rev=").size());
else if (starts_with_local(arg, "--target="))
parsed.gitTarget = arg.substr(std::string("--target=").size());
else if (starts_with_local(arg, "--subdirectory="))
parsed.gitSubdirectory = arg.substr(std::string("--subdirectory=").size());
else if (starts_with_local(arg, "--include="))
parsed.gitInclude = arg.substr(std::string("--include=").size());
else if (starts_with_local(arg, "--module="))
parsed.module = arg.substr(std::string("--module=").size());
else if (parsed.globalMode && parsed.globalSpec.empty())
{
parsed.globalSpec = arg;
}
else if (parsed.gitSpec.empty() && is_supported_git_url(arg))
{
parsed.gitSpec = arg;
}
}
split_compact_git_revision(parsed);
return parsed;
}
static vix::process::ProcessOutput run_process(
const std::string &program,
std::vector<std::string> args,
const fs::path &cwd = {})
{
vix::process::Command command(program);
command.args(std::move(args));
command.search_in_path(true);
command.stdout_mode(vix::process::PipeMode::Pipe);
command.stderr_mode(vix::process::PipeMode::Pipe);
if (!cwd.empty())
command.cwd(cwd.string());
const auto result = vix::process::output(std::move(command));
if (result)
return result.value();
vix::process::ProcessOutput output;
output.exit_code = 127;
output.stderr_text = result.error().message();
return output;
}
static bool git_checkout_is_clean(const fs::path &checkout)
{
const auto output = run_process(
"git",
{"status", "--porcelain", "--untracked-files=no"},
checkout);
return output.success() && trim_copy(output.stdout_text).empty();
}
static bool git_checkout_head_matches(const fs::path &checkout, const std::string &commit)
{
if (commit.empty())
return true;
const auto output = run_process("git", {"rev-parse", "HEAD"}, checkout);
return output.success() && trim_copy(output.stdout_text) == commit;
}
static bool lock_hash_metadata_is_current(const DepResolved &dep)
{
return dep.hashAlgorithm == vix::cli::util::PACKAGE_HASH_ALGORITHM &&
dep.hashVersion == vix::cli::util::PACKAGE_HASH_VERSION;
}
enum class RegistryLockValidation
{
Match,
Missing,
Mismatch,
};
static RegistryLockValidation validate_locked_registry_metadata(
const DepResolved &dep,
std::string &reason)
{
reason.clear();
if (dep.source == "git")
{
reason = "Git dependencies do not have registry metadata.";
return RegistryLockValidation::Mismatch;
}
PkgSpec spec;
if (!parse_pkg_spec(dep.id, spec))
{
reason = "invalid package id in vix.lock: " + dep.id;
return RegistryLockValidation::Mismatch;
}
const fs::path p = entry_path(spec.ns, spec.name);
if (!fs::exists(p))
{
reason = "registry metadata not available for " + dep.id;
return RegistryLockValidation::Missing;
}
json entry;
try
{
entry = read_json_or_throw(p);
}
catch (const std::exception &ex)
{
reason = std::string("cannot read registry metadata for ") + dep.id + ": " + ex.what();
return RegistryLockValidation::Mismatch;
}
const std::string registryId = entry.value("id", dep.id);
if (registryId != dep.id)
{
reason = "registry metadata id changed for " + dep.id;
return RegistryLockValidation::Mismatch;
}
if (!entry.contains("repo") || !entry["repo"].is_object() ||
!entry["repo"].contains("url") || !entry["repo"]["url"].is_string())
{
reason = "registry metadata is missing repo.url for " + dep.id;
return RegistryLockValidation::Mismatch;
}
const std::string registryRepo = entry["repo"]["url"].get<std::string>();
if (registryRepo != dep.repo)
{
reason = "registry metadata repo changed for " + dep.id;
return RegistryLockValidation::Mismatch;
}
if (!entry.contains("versions") || !entry["versions"].is_object())
{
reason = "registry metadata is missing versions for " + dep.id;
return RegistryLockValidation::Mismatch;
}
const json &versions = entry["versions"];
if (!versions.contains(dep.version) || !versions[dep.version].is_object())
{
reason = "registry metadata no longer contains " + dep.id + "@" + dep.version;
return RegistryLockValidation::Mismatch;
}
const json &version = versions[dep.version];
if (!version.contains("tag") || !version["tag"].is_string() ||
!version.contains("commit") || !version["commit"].is_string())
{
reason = "registry metadata is missing tag or commit for " + dep.id + "@" + dep.version;
return RegistryLockValidation::Mismatch;
}
if (version["tag"].get<std::string>() != dep.tag)
{
reason = "registry metadata tag changed for " + dep.id + "@" + dep.version;
return RegistryLockValidation::Mismatch;
}
if (version["commit"].get<std::string>() != dep.commit)
{
reason = "registry metadata commit changed for " + dep.id + "@" + dep.version;
return RegistryLockValidation::Mismatch;
}
return RegistryLockValidation::Match;
}
static bool ensure_registry_metadata_still_matches_lock(
const DepResolved &dep,
std::string &reason)
{
RegistryLockValidation validation = validate_locked_registry_metadata(dep, reason);
if (validation == RegistryLockValidation::Match)
return true;
if (validation == RegistryLockValidation::Mismatch)
return false;
const int syncRc = RegistryCommand::sync(true, false);
if (syncRc == 0)
{
validation = validate_locked_registry_metadata(dep, reason);
return validation == RegistryLockValidation::Match;
}
if (git_checkout_head_matches(dep.checkout, dep.commit) && git_checkout_is_clean(dep.checkout))
{
reason.clear();
return true;
}
reason = "registry metadata is unavailable and the local checkout cannot validate the locked commit";
return false;
}
static bool refresh_obsolete_integrity_metadata(
DepResolved &dep,
json &lockEntry,
const std::string &actualHash,
bool &printedHeader,
bool &printedRefreshLine,
std::string &refusalReason)
{
refusalReason.clear();
if (lock_hash_metadata_is_current(dep))
return false;
if (dep.source == "git")
{
refusalReason = "automatic integrity metadata migration is only supported for registry packages";
return false;
}
const bool clean = git_checkout_is_clean(dep.checkout);
const bool headMatches = git_checkout_head_matches(dep.checkout, dep.commit);
if (!clean || !headMatches)
return false;
if (!ensure_registry_metadata_still_matches_lock(dep, refusalReason))
return false;
if (!printedHeader)
{
vix::cli::util::section(std::cout, "Installing dependencies");
printedHeader = true;
}
if (!printedRefreshLine)
{
std::cout << " " << CYAN << "•" << RESET << " "
<< GRAY << "refreshing obsolete integrity metadata" << RESET << "\n";
printedRefreshLine = true;
}
dep.hash = actualHash;
dep.hashAlgorithm = vix::cli::util::PACKAGE_HASH_ALGORITHM;
dep.hashVersion = vix::cli::util::PACKAGE_HASH_VERSION;
lockEntry["hash"] = dep.hash;
lockEntry["hash_algorithm"] = dep.hashAlgorithm;
lockEntry["hash_version"] = dep.hashVersion;
std::cout << " " << CYAN << "•" << RESET << " "
<< CYAN << BOLD << dep.id << RESET
<< GRAY << "@" << RESET
<< YELLOW << BOLD << dep.version << RESET
<< " "
<< GRAY << "metadata updated" << RESET
<< "\n";
return true;
}
static void print_integrity_recovery_hint(const DepResolved &dep, bool clean, bool headMatches)
{
if (!headMatches)
{
vix::cli::util::warn_line(std::cerr, "The cached checkout points at a different commit than vix.lock.");
vix::cli::util::warn_line(std::cerr, "Preview project-scoped cleanup first: vix store gc --project --dry-run");
return;
}
if (!clean)
{
vix::cli::util::warn_line(std::cerr, "The cached checkout has local modifications to tracked files.");
vix::cli::util::warn_line(std::cerr, "Use: vix reset");
vix::cli::util::warn_line(std::cerr, "If the shared store itself must be cleaned, preview first: vix store gc --project --dry-run");
return;
}
if (!lock_hash_metadata_is_current(dep))
{
vix::cli::util::warn_line(std::cerr, "locked integrity metadata does not match the content produced by the current hash algorithm");
vix::cli::util::warn_line(std::cerr, "Use: vix update");
return;
}
vix::cli::util::warn_line(std::cerr, "The checkout is Git-clean, but its package hash differs from vix.lock.");
vix::cli::util::warn_line(std::cerr, "This usually means registry metadata or lockfile integrity metadata is inconsistent.");
vix::cli::util::warn_line(std::cerr, "Use: vix registry sync");
vix::cli::util::warn_line(std::cerr, "If the mismatch persists with a fresh checkout, run: vix update");
}
static bool verify_dependency_hash(const DepResolved &dep)
{
if (dep.hash.empty())
return true;
const auto actualHashOpt = vix::cli::util::sha256_package_directory(dep.checkout);
if (!actualHashOpt)