-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCloudCommand.cpp
More file actions
2268 lines (2035 loc) · 79.6 KB
/
Copy pathCloudCommand.cpp
File metadata and controls
2268 lines (2035 loc) · 79.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 CloudCommand.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/CloudCommand.hpp>
#include <vix/cli/cmake/CMakeBuild.hpp>
#include <vix/cli/util/Hash.hpp>
#include <vix/requests/requests.hpp>
#include <vix/utils/Env.hpp>
#include <nlohmann/json.hpp>
#include <algorithm>
#include <array>
#include <chrono>
#include <cctype>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <iterator>
#include <new>
#include <optional>
#include <random>
#include <sstream>
#include <string>
#include <vector>
#ifdef _WIN32
#include <io.h>
#include <windows.h>
#else
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <termios.h>
#include <unistd.h>
#endif
namespace fs = std::filesystem;
using json = nlohmann::json;
namespace vix::commands
{
namespace
{
constexpr const char *default_cloud_url = "https://api.softadastra.com";
constexpr const char *legacy_default_cloud_url = "http://127.0.0.1:8080";
constexpr const char *frontend_cloud_url = "https://cloud.softadastra.com";
struct GlobalCloudConfig
{
std::string cloud_url;
std::string session_id;
std::string user_id;
std::string email;
std::string display_name;
};
struct ProjectCloudConfig
{
std::string cloud_url;
std::string workspace_id;
std::string project_id;
std::string workspace_name;
std::string project_name;
};
struct ApiResult
{
bool ok{false};
int status{0};
json data = json::object();
std::string error;
std::string message;
};
struct CloudContext
{
GlobalCloudConfig global;
ProjectCloudConfig project;
std::string cloud_url;
};
struct CloudPublishOptions
{
std::string package_name;
std::string version;
std::string visibility{"private"};
std::string description;
std::string repository_url;
fs::path archive_path;
fs::path manifest_path;
bool dry_run{false};
bool json_output{false};
bool help{false};
};
struct PreparedArchive
{
fs::path path;
bool generated{false};
std::uintmax_t size{0};
std::string checksum_sha256;
};
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;
}
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;
}
std::string strip_trailing_slash(std::string value)
{
while (value.size() > 1 && value.back() == '/')
value.pop_back();
return value;
}
std::string normalize_cloud_url(std::string value)
{
value = strip_trailing_slash(value);
if (value.empty() || value == legacy_default_cloud_url || value == frontend_cloud_url)
return default_cloud_url;
return value;
}
namespace terminal
{
constexpr const char *reset = "\033[0m";
constexpr const char *bold = "\033[1m";
constexpr const char *red = "\033[31m";
constexpr const char *green = "\033[32m";
constexpr const char *yellow = "\033[33m";
constexpr const char *cyan = "\033[36m";
constexpr const char *white = "\033[97m";
constexpr const char *dim = "\033[37m";
bool stream_is_terminal(std::ostream &stream)
{
int descriptor = -1;
if (&stream == &std::cout)
#ifdef _WIN32
descriptor = _fileno(stdout);
#else
descriptor = fileno(stdout);
#endif
else if (&stream == &std::cerr)
#ifdef _WIN32
descriptor = _fileno(stderr);
#else
descriptor = fileno(stderr);
#endif
if (descriptor < 0)
return false;
#ifdef _WIN32
return _isatty(descriptor) != 0;
#else
return isatty(descriptor) != 0;
#endif
}
#ifdef _WIN32
void enable_virtual_terminal(std::ostream &stream)
{
const DWORD standard_handle = (&stream == &std::cerr) ? STD_ERROR_HANDLE : STD_OUTPUT_HANDLE;
HANDLE handle = GetStdHandle(standard_handle);
if (handle == INVALID_HANDLE_VALUE || handle == nullptr)
return;
DWORD mode = 0;
if (GetConsoleMode(handle, &mode) == 0)
return;
SetConsoleMode(handle, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
}
#endif
bool color_enabled(std::ostream &stream)
{
const char *no_color = vix::utils::vix_getenv("NO_COLOR");
if (no_color && *no_color)
return false;
const char *term = vix::utils::vix_getenv("TERM");
if (term && std::string(term) == "dumb")
return false;
if (!stream_is_terminal(stream))
return false;
#ifdef _WIN32
static bool stdout_enabled = false;
static bool stderr_enabled = false;
bool &enabled = (&stream == &std::cerr) ? stderr_enabled : stdout_enabled;
if (!enabled)
{
enable_virtual_terminal(stream);
enabled = true;
}
#endif
return true;
}
void code(std::ostream &stream, const char *value)
{
if (color_enabled(stream))
stream << value;
}
void symbol(std::ostream &stream, const char *glyph, const char *color)
{
code(stream, color);
stream << glyph;
code(stream, reset);
}
void header(const std::string &title, const std::string &subtitle = {})
{
symbol(std::cout, "◆", cyan);
std::cout << " ";
code(std::cout, bold);
code(std::cout, cyan);
std::cout << title;
code(std::cout, reset);
std::cout << "\n";
if (!subtitle.empty())
std::cout << " " << subtitle << "\n";
}
void field(const std::string &label, const std::string &value)
{
if (value.empty())
return;
const auto flags = std::cout.flags();
const auto fill = std::cout.fill();
std::cout << " ";
std::cout << std::left << std::setw(16) << label;
std::cout.flags(flags);
std::cout.fill(fill);
code(std::cout, bold);
code(std::cout, white);
std::cout << value;
code(std::cout, reset);
std::cout << "\n";
}
void status(std::ostream &stream, const char *glyph, const char *color, const std::string &message)
{
stream << " ";
symbol(stream, glyph, color);
stream << " " << message << "\n";
}
void success(const std::string &message)
{
status(std::cout, "✓", green, message);
}
void error(const std::string &message)
{
status(std::cerr, "×", red, message);
}
void warning(const std::string &message)
{
status(std::cout, "!", yellow, message);
}
void hint(const std::string &message)
{
std::cout << " ";
symbol(std::cout, "→", cyan);
std::cout << " " << message << "\n";
}
void progress(const std::string &message)
{
std::cout << " ";
symbol(std::cout, "●", cyan);
std::cout << " " << message << "\n";
}
void section(const std::string &title)
{
std::cout << "\n ";
code(std::cout, bold);
code(std::cout, cyan);
std::cout << title;
code(std::cout, reset);
std::cout << "\n";
}
void command(const std::string &usage, const std::string &description = {})
{
std::cout << " ";
code(std::cout, cyan);
std::cout << usage;
code(std::cout, reset);
if (!description.empty())
{
std::cout << "\n ";
code(std::cout, dim);
std::cout << description;
code(std::cout, reset);
}
std::cout << "\n";
}
void check(const std::string &label, bool ok, const std::string &detail)
{
const auto flags = std::cout.flags();
const auto fill = std::cout.fill();
std::cout << " ";
symbol(std::cout, ok ? "✓" : "×", ok ? green : red);
std::cout << " " << std::left << std::setw(18) << label;
std::cout.flags(flags);
std::cout.fill(fill);
code(std::cout, ok ? dim : yellow);
std::cout << detail;
code(std::cout, reset);
std::cout << "\n";
}
}
void cloud_header(const std::string &title, const std::string &subtitle = {})
{
terminal::header(title, subtitle);
}
void cloud_step(const std::string &label, const std::string &value)
{
if (value.empty())
return;
terminal::field(label, value);
}
void cloud_success(const std::string &message)
{
terminal::success(message);
}
void cloud_error(const std::string &message)
{
terminal::error(message);
}
void cloud_hint(const std::string &message)
{
terminal::hint(message);
}
std::string cloud_bad_alloc_message()
{
return "Softadastra Cloud returned a response the CLI could not buffer. Check that the Cloud API endpoint is serving JSON. The API URL is https://api.softadastra.com.";
}
std::string slugify(std::string value)
{
std::string out;
bool dash = false;
for (char ch : value)
{
const unsigned char c = static_cast<unsigned char>(ch);
if (std::isalnum(c))
{
out.push_back(static_cast<char>(std::tolower(c)));
dash = false;
}
else if (!dash && !out.empty())
{
out.push_back('-');
dash = true;
}
}
while (!out.empty() && out.back() == '-')
out.pop_back();
return out.empty() ? "project" : out;
}
fs::path home_dir()
{
#ifdef _WIN32
const char *home = vix::utils::vix_getenv("USERPROFILE");
#else
const char *home = vix::utils::vix_getenv("HOME");
#endif
return home && *home ? fs::path(home) : fs::current_path();
}
fs::path global_config_path()
{
return home_dir() / ".vix" / "cloud" / "config.json";
}
fs::path project_config_path()
{
return fs::current_path() / ".vix" / "cloud.json";
}
bool has_flag(const std::vector<std::string> &args, const std::string &name)
{
return std::find(args.begin(), args.end(), name) != args.end();
}
std::optional<std::string> arg_value(const std::vector<std::string> &args, const std::string &name)
{
const std::string prefix = name + "=";
for (std::size_t i = 0; i < args.size(); ++i)
{
if (args[i] == name && i + 1 < args.size())
return args[i + 1];
if (args[i].rfind(prefix, 0) == 0)
return args[i].substr(prefix.size());
}
return std::nullopt;
}
std::string prompt_line(const std::string &label, const std::string &fallback = {})
{
terminal::symbol(std::cout, "?", terminal::cyan);
std::cout << " " << label;
if (!fallback.empty())
{
std::cout << " ";
terminal::code(std::cout, terminal::dim);
std::cout << "[" << fallback << "]";
terminal::code(std::cout, terminal::reset);
}
std::cout << ": " << std::flush;
std::string value;
std::getline(std::cin, value);
value = trim_copy(value);
return value.empty() ? fallback : value;
}
std::string prompt_password()
{
terminal::symbol(std::cout, "?", terminal::cyan);
std::cout << " Password: " << std::flush;
std::string password;
#ifndef _WIN32
termios oldt{};
if (tcgetattr(STDIN_FILENO, &oldt) == 0)
{
termios newt = oldt;
newt.c_lflag &= static_cast<unsigned int>(~ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
std::getline(std::cin, password);
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
std::cout << "\n";
return password;
}
#endif
std::getline(std::cin, password);
return password;
}
bool read_json_file(const fs::path &path, json &out)
{
std::ifstream in(path);
if (!in)
return false;
try
{
in >> out;
return true;
}
catch (...)
{
return false;
}
}
std::optional<std::string> read_text_file(const fs::path &path)
{
std::ifstream in(path, std::ios::binary);
if (!in)
return std::nullopt;
return std::string((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
}
std::optional<std::vector<unsigned char>> read_binary_file(const fs::path &path)
{
std::ifstream in(path, std::ios::binary);
if (!in)
return std::nullopt;
return std::vector<unsigned char>((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
}
bool write_json_file(const fs::path &path, const json &value)
{
std::error_code ec;
fs::create_directories(path.parent_path(), ec);
std::ofstream out(path);
if (!out)
return false;
out << value.dump(2) << "\n";
return true;
}
std::optional<GlobalCloudConfig> load_global_config()
{
json value;
if (!read_json_file(global_config_path(), value) || !value.is_object())
return std::nullopt;
GlobalCloudConfig cfg;
cfg.cloud_url = normalize_cloud_url(value.value("cloud_url", default_cloud_url));
cfg.session_id = value.value("session_id", "");
if (value.contains("user") && value["user"].is_object())
{
cfg.user_id = value["user"].value("id", "");
cfg.email = value["user"].value("email", "");
cfg.display_name = value["user"].value("display_name", value["user"].value("name", ""));
}
return cfg;
}
bool save_global_config(const GlobalCloudConfig &cfg)
{
return write_json_file(global_config_path(), json{
{"cloud_url", cfg.cloud_url},
{"session_id", cfg.session_id},
{"user", {{"id", cfg.user_id}, {"email", cfg.email}, {"display_name", cfg.display_name}}}});
}
std::optional<ProjectCloudConfig> load_project_config()
{
json value;
if (!read_json_file(project_config_path(), value) || !value.is_object())
return std::nullopt;
ProjectCloudConfig cfg;
cfg.cloud_url = normalize_cloud_url(value.value("cloud_url", default_cloud_url));
cfg.workspace_id = value.value("workspace_id", "");
cfg.project_id = value.value("project_id", "");
cfg.workspace_name = value.value("workspace_name", "");
cfg.project_name = value.value("project_name", "");
return cfg;
}
bool save_project_config(const ProjectCloudConfig &cfg)
{
return write_json_file(project_config_path(), json{
{"cloud_url", cfg.cloud_url},
{"workspace_id", cfg.workspace_id},
{"project_id", cfg.project_id},
{"workspace_name", cfg.workspace_name},
{"project_name", cfg.project_name}});
}
vix::requests::RequestOptions request_options(const std::optional<GlobalCloudConfig> &cfg = std::nullopt)
{
vix::requests::RequestOptions options;
options.timeout = vix::requests::Timeout(
std::chrono::seconds(10),
std::chrono::seconds(20),
std::chrono::seconds(30));
options.headers.set("Accept", "application/json");
if (cfg && !cfg->session_id.empty())
{
options.headers.set("Authorization", "Bearer " + cfg->session_id);
options.headers.set("X-Session-Id", cfg->session_id);
}
return options;
}
ApiResult parse_response(const vix::requests::Response &response)
{
ApiResult result;
result.status = response.status_code();
json payload;
const auto contentType = response.content_type().value_or("");
if (!response.text().empty() &&
contentType.find("application/json") == std::string::npos &&
contentType.find("+json") == std::string::npos)
{
result.error = "invalid_cloud_response";
result.message = "Softadastra Cloud API returned " +
(contentType.empty() ? std::string("a non-JSON response") : ("Content-Type " + contentType)) +
". Check that the CLI is using https://api.softadastra.com, not the frontend domain.";
return result;
}
try
{
payload = response.text().empty() ? json::object() : json::parse(response.text());
}
catch (...)
{
result.error = "invalid_cloud_response";
result.message = "Softadastra Cloud API returned invalid JSON. Check that the CLI is using https://api.softadastra.com, not the frontend domain.";
return result;
}
result.ok = response.ok() && payload.value("ok", false);
if (payload.contains("data"))
result.data = payload["data"];
result.error = payload.value("error", response.ok() ? std::string{} : "http_error");
result.message = payload.value("message", response.ok() ? std::string{} : ("HTTP " + std::to_string(response.status_code())));
return result;
}
ApiResult api_post(const std::string &cloud_url, const std::string &path, const json &body, const std::optional<GlobalCloudConfig> &cfg = std::nullopt)
{
try
{
vix::requests::Client client;
const auto response = client.post(strip_trailing_slash(cloud_url) + path, vix::requests::json_body(body.dump()), request_options(cfg));
return parse_response(response);
}
catch (const std::bad_alloc &)
{
return ApiResult{false, 0, json::object(), "network_error", cloud_bad_alloc_message()};
}
catch (const std::exception &ex)
{
return ApiResult{false, 0, json::object(), "network_error", ex.what()};
}
}
ApiResult api_post_binary(const std::string &cloud_url, const std::string &path, std::vector<unsigned char> body, const std::optional<GlobalCloudConfig> &cfg = std::nullopt)
{
try
{
vix::requests::Client client;
auto options = request_options(cfg);
options.headers.set("Content-Type", "application/gzip");
const auto response = client.post(strip_trailing_slash(cloud_url) + path, vix::requests::binary_body(std::move(body), "application/gzip"), options);
return parse_response(response);
}
catch (const std::bad_alloc &)
{
return ApiResult{false, 0, json::object(), "network_error", cloud_bad_alloc_message()};
}
catch (const std::exception &ex)
{
return ApiResult{false, 0, json::object(), "network_error", ex.what()};
}
}
ApiResult api_get(const std::string &cloud_url, const std::string &path, const std::optional<GlobalCloudConfig> &cfg = std::nullopt)
{
try
{
vix::requests::Client client;
const auto response = client.get(strip_trailing_slash(cloud_url) + path, request_options(cfg));
return parse_response(response);
}
catch (const std::bad_alloc &)
{
return ApiResult{false, 0, json::object(), "network_error", cloud_bad_alloc_message()};
}
catch (const std::exception &ex)
{
return ApiResult{false, 0, json::object(), "network_error", ex.what()};
}
}
std::string api_error_text(const ApiResult &result)
{
if (!result.error.empty() && !result.message.empty())
return result.error + ": " + result.message;
if (!result.message.empty())
return result.message;
if (!result.error.empty())
return result.error;
if (result.status > 0)
return "HTTP " + std::to_string(result.status);
return "Cloud request failed.";
}
std::string permission_error_text(const ApiResult &result, const std::string &permissionMessage)
{
if (result.status == 401)
return "Authentication failed. Run vix login again.";
if (result.status == 403)
return permissionMessage;
if (result.status == 404)
return "Linked workspace or project was not found.";
return api_error_text(result);
}
void print_api_error(const ApiResult &result)
{
if (result.status == 403)
{
cloud_error("You do not have permission to perform this action in this workspace.");
return;
}
cloud_error(result.message.empty() ? "Cloud request failed." : result.message);
if (!result.error.empty())
cloud_step("Error", result.error);
if (result.status > 0)
cloud_step("HTTP status", std::to_string(result.status));
if (result.status == 401)
cloud_hint("Run: vix login");
}
std::optional<GlobalCloudConfig> require_connected()
{
auto cfg = load_global_config();
if (!cfg || cfg->session_id.empty())
{
cloud_error("Not connected to Softadastra Cloud.");
cloud_hint("Run: vix login");
return std::nullopt;
}
return cfg;
}
std::optional<CloudContext> load_cloud_context(std::string &message)
{
auto global = load_global_config();
if (!global || global->cloud_url.empty() || global->session_id.empty())
{
message = "Authentication failed. Run vix login again.";
return std::nullopt;
}
if (global->user_id.empty())
{
auto me = api_post(global->cloud_url, "/api/auth/me", json{{"session_id", global->session_id}}, global);
if (!me.ok)
{
message = permission_error_text(me, "Authentication failed. Run vix login again.");
return std::nullopt;
}
const auto user = me.data.value("user", json::object());
global->user_id = user.value("id", "");
global->email = user.value("email", global->email);
global->display_name = user.value("display_name", global->display_name);
}
auto project = load_project_config();
if (!project || project->workspace_id.empty() || project->project_id.empty() || project->cloud_url.empty())
{
message = "This project is not linked to Softadastra Cloud. Run vix cloud init first.";
return std::nullopt;
}
if (global->user_id.empty())
{
message = "Authentication failed. Run vix login again.";
return std::nullopt;
}
CloudContext ctx;
ctx.global = *global;
ctx.project = *project;
ctx.cloud_url = strip_trailing_slash(project->cloud_url.empty() ? global->cloud_url : project->cloud_url);
return ctx;
}
bool executable_available(const std::string &exe)
{
std::string output;
const auto result = vix::cli::build::run_process_capture({exe, "--version"}, {}, output);
return result.exitCode == 0;
}
std::string git_value(const std::vector<std::string> &argv)
{
std::string output;
const auto result = vix::cli::build::run_process_capture(argv, {}, output);
if (result.exitCode != 0)
return {};
return trim_copy(output);
}
std::string json_error_output(const std::string &error, const std::string &message)
{
return json{{"ok", false}, {"error", error}, {"message", message}}.dump(2);
}
int print_cloud_publish_error(const CloudPublishOptions &opt, const std::string &error, const std::string &message)
{
if (opt.json_output)
{
std::cout << json_error_output(error, message) << "\n";
}
else
{
cloud_error(message);
if (!error.empty())
cloud_step("Error", error);
}
return 1;
}
CloudPublishOptions parse_cloud_publish_options(const std::vector<std::string> &args)
{
CloudPublishOptions opt;
for (std::size_t i = 0; i < args.size(); ++i)
{
const std::string &a = args[i];
auto take = [&](const std::string &name) -> std::string
{
if (i + 1 >= args.size())
throw std::runtime_error(name + " requires a value");
++i;
return args[i];
};
if (a == "--help" || a == "-h")
opt.help = true;
else if (a == "--dry-run")
opt.dry_run = true;
else if (a == "--json")
opt.json_output = true;
else if (a == "--package")
opt.package_name = take("--package");
else if (a.rfind("--package=", 0) == 0)
opt.package_name = a.substr(std::string("--package=").size());
else if (a == "--version")
opt.version = take("--version");
else if (a.rfind("--version=", 0) == 0)
opt.version = a.substr(std::string("--version=").size());
else if (a == "--visibility")
opt.visibility = take("--visibility");
else if (a.rfind("--visibility=", 0) == 0)
opt.visibility = a.substr(std::string("--visibility=").size());
else if (a == "--description")
opt.description = take("--description");
else if (a.rfind("--description=", 0) == 0)
opt.description = a.substr(std::string("--description=").size());
else if (a == "--repository-url")
opt.repository_url = take("--repository-url");
else if (a.rfind("--repository-url=", 0) == 0)
opt.repository_url = a.substr(std::string("--repository-url=").size());
else if (a == "--archive")
opt.archive_path = fs::path(take("--archive"));
else if (a.rfind("--archive=", 0) == 0)
opt.archive_path = fs::path(a.substr(std::string("--archive=").size()));
else if (a == "--manifest")
opt.manifest_path = fs::path(take("--manifest"));
else if (a.rfind("--manifest=", 0) == 0)
opt.manifest_path = fs::path(a.substr(std::string("--manifest=").size()));
else if (!a.empty())
throw std::runtime_error("unknown cloud publish flag: " + a);
}
return opt;
}
std::string toml_like_value(const std::string &content, const std::string &key)
{
std::istringstream in(content);
std::string line;
const std::string prefix = key + " =";
while (std::getline(in, line))
{
line = trim_copy(line);
if (line.rfind(prefix, 0) != 0)
continue;
std::string value = trim_copy(line.substr(prefix.size()));
if (!value.empty() && value.front() == '"')
value.erase(value.begin());
if (!value.empty() && value.back() == '"')
value.pop_back();
return value;
}
return {};
}
json load_optional_json(const fs::path &path)
{
json value;
if (read_json_file(path, value) && value.is_object())
return value;
return json::object();
}
void fill_package_metadata_from_files(CloudPublishOptions &opt, json &manifest)
{
const fs::path root = fs::current_path();
const fs::path vix_json_path = root / "vix.json";
const fs::path vix_app_path = root / "vix.app";
json vix_json = load_optional_json(vix_json_path);
if (!vix_json.empty())
{
manifest["vix_json"] = vix_json;
const std::string name = vix_json.value("name", "");
const std::string ns = vix_json.value("namespace", "");
if (opt.package_name.empty() && !name.empty())
opt.package_name = ns.empty() ? name : (ns + "/" + name);
if (opt.version.empty())
opt.version = vix_json.value("version", "");
if (opt.description.empty())
opt.description = vix_json.value("description", "");
if (opt.repository_url.empty())
opt.repository_url = vix_json.value("repository", vix_json.value("repository_url", ""));
}
if (auto content = read_text_file(vix_app_path))
{
const std::string app_name = toml_like_value(*content, "name");
const std::string app_version = toml_like_value(*content, "version");
json app_info = json::object();
if (!app_name.empty())
app_info["name"] = app_name;
if (!app_version.empty())
app_info["version"] = app_version;
if (!app_info.empty())
manifest["vix_app"] = app_info;
if (opt.package_name.empty() && !app_name.empty())
opt.package_name = app_name;
if (opt.version.empty() && !app_version.empty())
opt.version = app_version;
}
}
std::string latest_git_semver_version()
{
std::string output;
const auto result = vix::cli::build::run_process_capture({"git", "tag", "--list", "v[0-9]*", "--sort=-v:refname"}, {}, output);
if (result.exitCode != 0)
return {};
std::istringstream in(output);
std::string line;
while (std::getline(in, line))
{
line = trim_copy(line);
if (line.size() > 1 && line[0] == 'v')
return line.substr(1);
}
return {};
}
fs::path make_temp_archive_path()
{
const auto now = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch())
.count();
fs::path dir = fs::temp_directory_path() / ("vix-cloud-publish-" + std::to_string(now));
std::error_code ec;
fs::create_directories(dir, ec);
return dir / "package.tar.gz";
}
std::optional<PreparedArchive> prepare_archive(const CloudPublishOptions &opt, std::string &message)
{
PreparedArchive archive;
if (!opt.archive_path.empty())
{
archive.path = fs::absolute(opt.archive_path);
archive.generated = false;
if (!fs::exists(archive.path) || !fs::is_regular_file(archive.path))
{
message = "Archive file not found: " + archive.path.string();
return std::nullopt;
}
}
else
{
#if defined(_WIN32)
if (!executable_available("tar"))
{
message = "Cloud publish archive creation is not available on this platform yet. Pass --archive <path>.";
return std::nullopt;
}
#endif
if (!executable_available("tar"))
{
message = "tar is required to create a package archive. Pass --archive <path>.";
return std::nullopt;
}