-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathPublishCommand.cpp
More file actions
2714 lines (2339 loc) · 81.6 KB
/
Copy pathPublishCommand.cpp
File metadata and controls
2714 lines (2339 loc) · 81.6 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 PublishCommand.cpp
* @brief Implements `vix publish` command (registry publication via git + optional GitHub PR).
* @author Gaspard Kirira
*
* @copyright Copyright (c) 2025 Gaspard Kirira
* @license MIT
*
* Project: Vix.cpp
* Repository: https://github.com/vixcpp/vix
*
* This source code is governed by the MIT license found in the LICENSE file.
*/
#include <vix/cli/commands/PublishCommand.hpp>
#include <vix/cli/commands/CloudCommand.hpp>
#include <vix/cli/util/Ui.hpp>
#include <vix/cli/util/Semver.hpp>
#include <vix/cli/Style.hpp>
#include <vix/utils/Env.hpp>
#include <nlohmann/json.hpp>
#include <algorithm>
#include <cctype>
#include <chrono>
#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <optional>
#include <sstream>
#include <regex>
#include <stdexcept>
#include <string>
#include <thread>
#include <vector>
#include <unordered_set>
#if defined(_WIN32)
#include <windows.h>
#else
#include <errno.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#endif
namespace fs = std::filesystem;
using json = nlohmann::json;
namespace vix::commands
{
using namespace vix::cli::style;
namespace
{
struct PublishOptions
{
std::string version;
std::string notes;
bool dryRun{false};
bool cleanup{false};
bool jsonOut{false};
bool verbose{false};
};
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 lower_copy(std::string s)
{
std::transform(s.begin(), s.end(), s.begin(),
[](unsigned char c)
{ return static_cast<char>(std::tolower(c)); });
return s;
}
static std::string stable_hash_hex(const std::string &input)
{
std::uint64_t hash = 1469598103934665603ull;
for (char ch : input)
{
const auto c = static_cast<unsigned char>(ch);
hash ^= static_cast<std::uint64_t>(c);
hash *= 1099511628211ull;
}
std::ostringstream out;
out << std::hex << std::setw(16) << std::setfill('0') << hash;
return out.str();
}
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_repo_dir()
{
// vix registry sync clones into ~/.vix/registry/index
return vix_root() / "registry" / "index";
}
static fs::path registry_index_dir()
{
// entries folder inside the registry repo: ~/.vix/registry/index/index
return registry_repo_dir() / "index";
}
static std::string registry_repo_url()
{
return "https://github.com/vixcpp/registry.git";
}
[[maybe_unused]] static std::string iso_utc_now()
{
using namespace std::chrono;
const auto now = system_clock::now();
const std::time_t t = system_clock::to_time_t(now);
std::tm tm{};
#if defined(_WIN32)
gmtime_s(&tm, &t);
#else
gmtime_r(&t, &tm);
#endif
std::ostringstream oss;
oss << std::put_time(&tm, "%Y-%m-%dT%H:%M:%SZ");
return oss.str();
}
static bool file_exists_nonempty(const fs::path &p)
{
std::error_code ec;
return fs::exists(p, ec) && fs::is_regular_file(p, ec);
}
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::ofstream out(p);
if (!out)
throw std::runtime_error("cannot write: " + p.string());
out << j.dump(2) << "\n";
}
#if defined(_WIN32)
static std::string join_for_log(
const std::vector<std::string> &args)
{
std::ostringstream out;
for (std::size_t i = 0; i < args.size(); ++i)
{
if (i > 0)
{
out << ' ';
}
const std::string &arg = args[i];
const bool needsQuotes =
arg.find(' ') != std::string::npos ||
arg.find('\t') != std::string::npos ||
arg.find('"') != std::string::npos;
if (!needsQuotes)
{
out << arg;
continue;
}
out << '"';
for (char c : arg)
{
if (c == '"')
{
out << "\\\"";
}
else
{
out << c;
}
}
out << '"';
}
return out.str();
}
#endif
struct ProcessResult
{
int exitCode{127};
std::string out;
std::string err;
};
#if defined(_WIN32)
static std::string win_last_error()
{
const DWORD err = GetLastError();
if (!err)
return {};
LPSTR buf = nullptr;
const DWORD n = FormatMessageA(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr,
err,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPSTR)&buf,
0,
nullptr);
std::string s = (n && buf) ? std::string(buf, buf + n) : std::string();
if (buf)
LocalFree(buf);
return trim_copy(s);
}
static std::string win_read_all(HANDLE h)
{
std::string out;
char buf[4096];
DWORD read = 0;
while (true)
{
const BOOL ok = ReadFile(h, buf, (DWORD)sizeof(buf), &read, nullptr);
if (!ok || read == 0)
break;
out.append(buf, buf + read);
}
return out;
}
static ProcessResult run_process_capture(const std::vector<std::string> &args, const std::optional<fs::path> &cwd = std::nullopt)
{
ProcessResult r;
if (args.empty())
{
r.exitCode = 127;
r.err = "empty command";
return r;
}
SECURITY_ATTRIBUTES sa{};
sa.nLength = sizeof(sa);
sa.bInheritHandle = TRUE;
HANDLE outRead = nullptr, outWrite = nullptr;
HANDLE errRead = nullptr, errWrite = nullptr;
if (!CreatePipe(&outRead, &outWrite, &sa, 0))
{
r.exitCode = 127;
r.err = "CreatePipe(stdout) failed: " + win_last_error();
return r;
}
if (!SetHandleInformation(outRead, HANDLE_FLAG_INHERIT, 0))
{
r.exitCode = 127;
r.err = "SetHandleInformation(stdout) failed: " + win_last_error();
CloseHandle(outRead);
CloseHandle(outWrite);
return r;
}
if (!CreatePipe(&errRead, &errWrite, &sa, 0))
{
r.exitCode = 127;
r.err = "CreatePipe(stderr) failed: " + win_last_error();
CloseHandle(outRead);
CloseHandle(outWrite);
return r;
}
if (!SetHandleInformation(errRead, HANDLE_FLAG_INHERIT, 0))
{
r.exitCode = 127;
r.err = "SetHandleInformation(stderr) failed: " + win_last_error();
CloseHandle(outRead);
CloseHandle(outWrite);
CloseHandle(errRead);
CloseHandle(errWrite);
return r;
}
STARTUPINFOA si{};
si.cb = sizeof(si);
si.dwFlags = STARTF_USESTDHANDLES;
si.hStdOutput = outWrite;
si.hStdError = errWrite;
si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
PROCESS_INFORMATION pi{};
std::string cmd = join_for_log(args);
// CreateProcess requires a writable buffer
std::vector<char> cmdBuf(cmd.begin(), cmd.end());
cmdBuf.push_back('\0');
std::string cwdStr;
LPCSTR cwdPtr = nullptr;
if (cwd)
{
cwdStr = cwd->string();
cwdPtr = cwdStr.c_str();
}
const BOOL ok = CreateProcessA(
nullptr,
cmdBuf.data(),
nullptr,
nullptr,
TRUE,
0,
nullptr,
cwdPtr,
&si,
&pi);
CloseHandle(outWrite);
CloseHandle(errWrite);
if (!ok)
{
r.exitCode = 127;
r.err = "CreateProcess failed: " + win_last_error();
CloseHandle(outRead);
CloseHandle(errRead);
return r;
}
WaitForSingleObject(pi.hProcess, INFINITE);
DWORD ec = 127;
GetExitCodeProcess(pi.hProcess, &ec);
r.exitCode = (int)ec;
r.out = win_read_all(outRead);
r.err = win_read_all(errRead);
CloseHandle(outRead);
CloseHandle(errRead);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
r.out = trim_copy(r.out);
r.err = trim_copy(r.err);
return r;
}
#else
static int set_cloexec(int fd)
{
const int flags = fcntl(fd, F_GETFD);
if (flags < 0)
return -1;
return fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
}
static std::string read_fd_all(int fd)
{
std::string out;
char buf[4096];
while (true)
{
const ssize_t n = ::read(fd, buf, sizeof(buf));
if (n > 0)
{
out.append(buf, buf + n);
continue;
}
if (n == 0)
break;
if (errno == EINTR)
continue;
break;
}
return out;
}
static ProcessResult run_process_capture(const std::vector<std::string> &args, const std::optional<fs::path> &cwd = std::nullopt)
{
ProcessResult r;
if (args.empty())
{
r.exitCode = 127;
r.err = "empty command";
return r;
}
int outPipe[2]{-1, -1};
int errPipe[2]{-1, -1};
if (pipe(outPipe) != 0)
{
r.exitCode = 127;
r.err = "pipe(stdout) failed";
return r;
}
if (pipe(errPipe) != 0)
{
r.exitCode = 127;
r.err = "pipe(stderr) failed";
close(outPipe[0]);
close(outPipe[1]);
return r;
}
set_cloexec(outPipe[0]);
set_cloexec(outPipe[1]);
set_cloexec(errPipe[0]);
set_cloexec(errPipe[1]);
pid_t pid = fork();
if (pid < 0)
{
r.exitCode = 127;
r.err = "fork failed";
close(outPipe[0]);
close(outPipe[1]);
close(errPipe[0]);
close(errPipe[1]);
return r;
}
if (pid == 0)
{
// child
if (cwd)
{
if (chdir(cwd->c_str()) != 0)
_exit(127);
}
dup2(outPipe[1], STDOUT_FILENO);
dup2(errPipe[1], STDERR_FILENO);
close(outPipe[0]);
close(outPipe[1]);
close(errPipe[0]);
close(errPipe[1]);
std::vector<char *> argv;
argv.reserve(args.size() + 1);
for (const auto &a : args)
argv.push_back(const_cast<char *>(a.c_str()));
argv.push_back(nullptr);
execvp(argv[0], argv.data());
_exit(127);
}
// parent
close(outPipe[1]);
close(errPipe[1]);
r.out = read_fd_all(outPipe[0]);
r.err = read_fd_all(errPipe[0]);
close(outPipe[0]);
close(errPipe[0]);
int status = 0;
while (waitpid(pid, &status, 0) < 0)
{
if (errno == EINTR)
continue;
break;
}
if (WIFEXITED(status))
r.exitCode = WEXITSTATUS(status);
else if (WIFSIGNALED(status))
r.exitCode = 128 + WTERMSIG(status);
else
r.exitCode = 127;
r.out = trim_copy(r.out);
r.err = trim_copy(r.err);
return r;
}
#endif
static ProcessResult run_process_retry_debug(
const std::vector<std::string> &args,
const std::optional<fs::path> &cwd = std::nullopt,
int attempts = 2)
{
ProcessResult last;
for (int i = 0; i < attempts; ++i)
{
last = run_process_capture(args, cwd);
if (last.exitCode == 0)
return last;
// small retry for transient filesystem/network issues
if (i + 1 < attempts)
std::this_thread::sleep_for(std::chrono::milliseconds(200));
}
return last;
}
static std::optional<std::string> git_top_level()
{
const auto r = run_process_capture({"git", "rev-parse", "--show-toplevel"});
if (r.exitCode != 0 || r.out.empty())
return std::nullopt;
return r.out;
}
static bool git_is_clean()
{
const auto r = run_process_capture({"git", "status", "--porcelain"});
if (r.exitCode != 0)
return false;
return r.out.empty();
}
static bool git_tag_exists(const std::string &tag)
{
{
const auto r = run_process_capture({"git", "rev-parse", "-q", "--verify", tag + "^{tag}"});
if (r.exitCode == 0)
return true;
}
{
const auto r = run_process_capture({"git", "rev-parse", "-q", "--verify", "refs/tags/" + tag});
return r.exitCode == 0;
}
}
static std::optional<std::string> git_commit_for_tag(const std::string &tag)
{
const auto r = run_process_capture({"git", "rev-list", "-n", "1", tag});
if (r.exitCode != 0 || r.out.empty())
return std::nullopt;
return r.out;
}
enum class RemoteGitFailure
{
none,
tagMissing,
network,
authentication,
repository,
unknown,
};
struct RemoteTagLookup
{
std::optional<std::string> commit;
RemoteGitFailure failure{RemoteGitFailure::none};
std::string detail;
};
static RemoteGitFailure classify_git_remote_error(const ProcessResult &r)
{
const std::string text = lower_copy(r.err + "\n" + r.out);
if (text.find("could not resolve host") != std::string::npos ||
text.find("temporary failure") != std::string::npos ||
text.find("network is unreachable") != std::string::npos ||
text.find("connection timed out") != std::string::npos ||
text.find("connection reset") != std::string::npos ||
text.find("failed to connect") != std::string::npos ||
text.find("unable to access") != std::string::npos ||
text.find("gnutls recv error") != std::string::npos ||
text.find("tls") != std::string::npos)
return RemoteGitFailure::network;
if (text.find("authentication failed") != std::string::npos ||
text.find("permission denied") != std::string::npos ||
text.find("could not read from remote repository") != std::string::npos ||
text.find("repository access denied") != std::string::npos)
return RemoteGitFailure::authentication;
if (text.find("repository not found") != std::string::npos ||
text.find("not found") != std::string::npos ||
text.find("does not appear to be a git repository") != std::string::npos)
return RemoteGitFailure::repository;
return RemoteGitFailure::unknown;
}
static std::string remote_git_failure_message(RemoteGitFailure failure, const std::string &tag)
{
switch (failure)
{
case RemoteGitFailure::tagMissing:
return "Tag " + tag + " is not on origin\n Run: git push origin " + tag;
case RemoteGitFailure::network:
return "Cannot reach git origin to verify tag " + tag + "\n Check your network connection and try again.";
case RemoteGitFailure::authentication:
return "Cannot access git origin to verify tag " + tag + "\n Check your Git credentials for origin.";
case RemoteGitFailure::repository:
return "Git origin repository could not be found\n Check: git remote -v";
case RemoteGitFailure::unknown:
return "Could not verify tag " + tag + " on origin";
case RemoteGitFailure::none:
return {};
}
return "Could not verify tag " + tag + " on origin";
}
static bool looks_like_semver_tag(const std::string &tag)
{
std::string s = trim_copy(tag);
if (s.empty())
return false;
if (s[0] == 'v' || s[0] == 'V')
s.erase(s.begin());
if (s.empty())
return false;
const auto firstDot = s.find('.');
if (firstDot == std::string::npos)
return false;
const auto secondDot = s.find('.', firstDot + 1);
if (secondDot == std::string::npos)
return false;
return vix::cli::util::semver::compare(s, s) == 0;
}
static std::string normalize_version_from_tag(std::string tag)
{
tag = trim_copy(tag);
if (!tag.empty() && (tag[0] == 'v' || tag[0] == 'V'))
tag.erase(tag.begin());
return trim_copy(tag);
}
static std::optional<std::string> git_latest_semver_tag()
{
const auto r = run_process_capture({"git", "tag", "--list"});
if (r.exitCode != 0 || r.out.empty())
return std::nullopt;
std::istringstream iss(r.out);
std::string line;
std::vector<std::string> versions;
while (std::getline(iss, line))
{
line = trim_copy(line);
if (!looks_like_semver_tag(line))
continue;
versions.push_back(normalize_version_from_tag(line));
}
if (versions.empty())
return std::nullopt;
return vix::cli::util::semver::findLatest(versions);
}
static std::optional<std::string> resolve_publish_version_or_throw(
const PublishOptions &opt)
{
const std::string explicitVersion = trim_copy(opt.version);
if (!explicitVersion.empty())
{
const std::string tag = "v" + explicitVersion;
if (!git_tag_exists(tag))
{
throw std::runtime_error(
"tag not found locally: " + tag +
". Create it first or run `vix publish` without a version to use the latest git tag");
}
return explicitVersion;
}
const auto detected = git_latest_semver_tag();
if (!detected.has_value())
{
throw std::runtime_error(
"no publishable git tag found. Create and push a tag like v0.2.0");
}
const std::string tag = "v" + *detected;
return detected;
}
[[maybe_unused]] static json read_vix_json_object(const fs::path &repoRoot)
{
const fs::path p = repoRoot / "vix.json";
if (!file_exists_nonempty(p))
return json::object();
try
{
const json j = read_json_or_throw(p);
if (j.is_object())
return j;
}
catch (...)
{
}
return json::object();
}
[[maybe_unused]] static std::string https_repo_from_remote(const std::string &remoteUrl)
{
std::string httpsUrl = trim_copy(remoteUrl);
if (httpsUrl.empty())
return {};
if (httpsUrl.find("git@") == 0)
{
const auto pos = httpsUrl.find(':');
if (pos != std::string::npos)
{
const std::string path = httpsUrl.substr(pos + 1);
httpsUrl = "https://github.com/" + path;
}
}
if (httpsUrl.size() >= 4 && httpsUrl.rfind(".git") == httpsUrl.size() - 4)
httpsUrl.erase(httpsUrl.size() - 4);
return httpsUrl;
}
static std::string normalize_repository_url(std::string url)
{
url = trim_copy(url);
if (url.empty())
return {};
while (!url.empty() && url.back() == '/')
url.pop_back();
if (url.rfind("git@", 0) == 0)
{
const auto at = url.find('@');
const auto colon = url.find(':', at == std::string::npos ? 0 : at);
if (at != std::string::npos && colon != std::string::npos)
{
const std::string host = url.substr(at + 1, colon - at - 1);
const std::string path = url.substr(colon + 1);
url = "https://" + host + "/" + path;
}
}
else if (url.rfind("ssh://git@", 0) == 0)
{
std::string rest = url.substr(std::string("ssh://git@").size());
const auto slash = rest.find('/');
if (slash != std::string::npos)
url = "https://" + rest.substr(0, slash) + "/" + rest.substr(slash + 1);
}
if (url.size() >= 4 && url.rfind(".git") == url.size() - 4)
url.erase(url.size() - 4);
const auto scheme = url.find("://");
if (scheme != std::string::npos)
{
const auto hostStart = scheme + 3;
const auto slash = url.find('/', hostStart);
if (slash != std::string::npos)
{
std::string schemePart = lower_copy(url.substr(0, scheme));
std::string host = lower_copy(url.substr(hostStart, slash - hostStart));
std::string path = url.substr(slash + 1);
if (host == "github.com")
path = lower_copy(path);
url = schemePart + "://" + host + "/" + path;
}
}
return url;
}
static std::optional<std::string> git_origin_url()
{
const auto r = run_process_capture({"git", "remote", "get-url", "origin"});
if (r.exitCode != 0 || trim_copy(r.out).empty())
return std::nullopt;
return trim_copy(r.out);
}
static RemoteTagLookup git_remote_commit_for_tag(const std::string &tag)
{
const auto r = run_process_capture({"git", "ls-remote", "--tags", "origin", "refs/tags/" + tag, "refs/tags/" + tag + "^{}"});
RemoteTagLookup lookup;
lookup.detail = trim_copy(r.err.empty() ? r.out : r.err);
if (r.exitCode != 0)
{
lookup.failure = classify_git_remote_error(r);
return lookup;
}
if (trim_copy(r.out).empty())
{
lookup.failure = RemoteGitFailure::tagMissing;
return lookup;
}
std::istringstream iss(r.out);
std::string line;
std::string first;
while (std::getline(iss, line))
{
line = trim_copy(line);
if (line.empty())
continue;
const auto tab = line.find_first_of(" \t");
if (tab == std::string::npos)
continue;
const std::string sha = line.substr(0, tab);
const std::string ref = trim_copy(line.substr(tab + 1));
if (first.empty())
first = sha;
if (ref == "refs/tags/" + tag + "^{}")
{
lookup.commit = sha;
return lookup;
}
}
if (!first.empty())
lookup.commit = first;
else
lookup.failure = RemoteGitFailure::tagMissing;
return lookup;
}
static bool is_valid_package_atom(const std::string &value)
{
if (value.empty())
return false;
for (char c : value)
{
const unsigned char uc = static_cast<unsigned char>(c);
if (!(std::isalnum(uc) || c == '-' || c == '_' || c == '.'))
return false;
}
return value.find("..") == std::string::npos &&
value.front() != '.' && value.back() != '.';
}
static bool is_safe_relative_path(const std::string &value)
{
if (value.empty())
return false;
fs::path p(value);
if (p.is_absolute())
return false;
for (const auto &part : p)
{
if (part == "..")
return false;
}
return true;
}
static std::vector<std::string> manifest_include_roots(const json &manifest)
{
std::vector<std::string> roots;
if (manifest.contains("include") && manifest["include"].is_string())
roots.push_back(manifest["include"].get<std::string>());
if (manifest.contains("includes") && manifest["includes"].is_array())
{
for (const auto &item : manifest["includes"])
if (item.is_string())
roots.push_back(item.get<std::string>());
}
if (roots.empty())
roots.push_back("include");
std::sort(roots.begin(), roots.end());
roots.erase(std::unique(roots.begin(), roots.end()), roots.end());
return roots;
}
struct PublicHeader
{
std::string includeRoot;
std::string path;
fs::path absolute;
};
static std::vector<PublicHeader> scan_public_headers_or_throw(const fs::path &repoRoot, const json &manifest)
{
std::vector<PublicHeader> headers;
const fs::path rootAbs = fs::weakly_canonical(repoRoot);
for (const std::string &root : manifest_include_roots(manifest))
{
if (!is_safe_relative_path(root))
throw std::runtime_error("invalid include path in vix.json: " + root);
const fs::path includeRoot = repoRoot / root;
std::error_code ec;
if (!fs::exists(includeRoot, ec) || ec)
continue;
const fs::path includeRootAbs = fs::weakly_canonical(includeRoot, ec);
if (ec || includeRootAbs.string().rfind(rootAbs.string(), 0) != 0)
throw std::runtime_error("include path escapes repository: " + root);
for (auto it = fs::recursive_directory_iterator(includeRootAbs, fs::directory_options::skip_permission_denied, ec);
!ec && it != fs::recursive_directory_iterator(); ++it)
{
if (it->is_symlink(ec))
{
const fs::path target = fs::weakly_canonical(it->path(), ec);
if (ec || target.string().rfind(rootAbs.string(), 0) != 0)
throw std::runtime_error("public include symlink escapes repository: " + it->path().string());
}
if (!it->is_regular_file(ec) || ec)
continue;
const std::string ext = lower_copy(it->path().extension().string());
if (ext != ".h" && ext != ".hpp" && ext != ".hh" && ext != ".hxx" && ext != ".ipp")
continue;
const std::string name = it->path().filename().string();
if (name.rfind(".", 0) == 0 || name.find("~") != std::string::npos)
continue;
const fs::path rel = fs::relative(it->path(), includeRootAbs, ec);
if (ec)
continue;
headers.push_back({root, rel.generic_string(), it->path()});
}
}
std::sort(headers.begin(), headers.end(), [](const PublicHeader &a, const PublicHeader &b)
{ return std::tie(a.includeRoot, a.path) < std::tie(b.includeRoot, b.path); });
return headers;
}
[[maybe_unused]] static std::string read_text_file_or_empty_local(const fs::path &p)
{
std::ifstream in(p, std::ios::binary);
if (!in)
return {};
std::ostringstream ss;
ss << in.rdbuf();
return ss.str();
}
static json generate_api_document(const std::string &pkgId,
const std::string &version,
const std::string &commit,
const std::vector<PublicHeader> &headers)
{
json api = json::object();
api["format"] = "vix-api-1";
api["package"] = pkgId;
api["version"] = version;
api["commit"] = commit;
api["headers"] = json::array();
const std::regex functionLike(R"(^\s*(?:template\s*<[^;]+>\s*)?(?:inline\s+|constexpr\s+|static\s+|virtual\s+|friend\s+)*([A-Za-z_][A-Za-z0-9_:<>~,&*\s]+)\s+([A-Za-z_][A-Za-z0-9_:~]*)\s*\(([^;{}]*)\)\s*(?:const\s*)?(?:noexcept\s*)?(?:->\s*[^;{]+)?[;{])");
const std::regex classLike(R"(^\s*(class|struct|enum\s+class|enum)\s+([A-Za-z_][A-Za-z0-9_]*)\b)");
const std::regex nsLike(R"(^\s*namespace\s+([A-Za-z_][A-Za-z0-9_:]*)\s*\{?)");
for (const auto &header : headers)
{
json h = json::object();
h["path"] = header.path;