forked from OpenAtom-Linyaps/linyaps
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
1159 lines (989 loc) · 39.4 KB
/
Copy pathmain.cpp
File metadata and controls
1159 lines (989 loc) · 39.4 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
/*
* SPDX-FileCopyrightText: 2022 - 2026 UnionTech Software Technology Co., Ltd.
*
* SPDX-License-Identifier: LGPL-3.0-or-later
*/
#include "command_options.h"
#include "configure.h"
#include "linglong/builder/config.h"
#include "linglong/builder/linglong_builder.h"
#include "linglong/cli/cli.h"
#include "linglong/common/global/initialize.h"
#include "linglong/package/architecture.h"
#include "linglong/package/version.h"
#include "linglong/repo/client_factory.h"
#include "linglong/repo/config.h"
#include "linglong/repo/migrate.h"
#include "linglong/utils/error/error.h"
#include "linglong/utils/file.h"
#include "linglong/utils/gettext.h"
#include "linglong/utils/log/log.h"
#include "linglong/utils/namespace.h"
#include "linglong/utils/serialize/yaml.h"
#include "ocppi/cli/crun/Crun.hpp"
#include <CLI/CLI.hpp>
#include <QCoreApplication>
#include <QStringList>
#include <iostream>
#include <list>
#include <optional>
#include <ostream>
#include <string>
#include <vector>
#include <wordexp.h>
namespace {
std::string validateNonEmptyString(const std::string ¶meter)
{
if (parameter.empty()) {
return std::string{ _("Input parameter is empty, please input valid parameter instead") };
}
return {};
}
linglong::utils::error::Result<linglong::api::types::v1::BuilderProject>
parseProjectConfig(const std::filesystem::path &filename)
{
LINGLONG_TRACE("parse project config " + filename.string());
std::cerr << "Using project file " + filename.string() << std::endl;
auto project =
linglong::utils::serialize::LoadYAMLFile<linglong::api::types::v1::BuilderProject>(filename);
if (!project) {
return project;
}
auto version = linglong::package::VersionV1::parse(project->package.version);
if (!version || !version->tweak) {
return LINGLONG_ERR("Please ensure the package.version number has three parts formatted as "
"'MAJOR.MINOR.PATCH.TWEAK'");
}
if (project->modules.has_value()) {
if (std::any_of(project->modules->begin(), project->modules->end(), [](const auto &module) {
return module.name == "binary";
})) {
return LINGLONG_ERR("configuration of binary modules is not allowed. see "
"https://linglong.space/guide/ll-builder/modules.html");
}
}
if (project->package.kind == "app" && !project->command.has_value()) {
return LINGLONG_ERR(
"'command' field is missing, app should hava command as the default startup command");
}
// 校验bese和runtime版本是否合法
auto baseFuzzyRef = linglong::package::FuzzyReference::parse(project->base.c_str());
if (!baseFuzzyRef) {
return LINGLONG_ERR("failed to parse base field", baseFuzzyRef);
}
auto ret = linglong::package::Version::validateDependVersion(baseFuzzyRef->version.value());
if (!ret) {
return LINGLONG_ERR("base version is not valid", ret);
}
if (project->runtime) {
auto runtimeFuzzyRef =
linglong::package::FuzzyReference::parse(project->runtime.value().c_str());
if (!runtimeFuzzyRef) {
return LINGLONG_ERR("failed to parse runtime field", runtimeFuzzyRef);
}
ret = linglong::package::Version::validateDependVersion(runtimeFuzzyRef->version.value());
if (!ret) {
return LINGLONG_ERR("runtime version is not valid", ret);
}
}
return project;
}
linglong::utils::error::Result<std::filesystem::path>
getProjectYAMLPath(const std::filesystem::path &projectDir, const std::string &usePath)
{
LINGLONG_TRACE("get project yaml path");
std::error_code ec;
if (!usePath.empty()) {
std::filesystem::path path = std::filesystem::canonical(usePath, ec);
if (ec) {
return LINGLONG_ERR(
fmt::format("invalid file path {} error: {}", usePath, ec.message()));
}
return path;
}
std::filesystem::path path = projectDir
/ ("linglong." + linglong::package::Architecture::currentCPUArchitecture().toString()
+ ".yaml");
if (std::filesystem::exists(path, ec)) {
return path;
}
if (ec) {
return LINGLONG_ERR(fmt::format("path {} error: {}", path, ec.message()));
}
path = projectDir / "linglong.yaml";
if (std::filesystem::exists(path, ec)) {
return path;
}
if (ec) {
return LINGLONG_ERR(fmt::format("path {} error: {}", path, ec.message()));
}
return LINGLONG_ERR("project yaml file not found");
}
int handleCreate(const CreateCommandOptions &options)
{
LogI("Handling create for project: {}", options.projectName);
auto name = QString::fromStdString(options.projectName);
QDir projectDir = QDir::current().absoluteFilePath(name);
if (projectDir.exists()) {
LogE("{} project dir already exists", options.projectName);
return -1;
}
auto ret = projectDir.mkpath(".");
if (!ret) {
LogE("create project dir failed: {}", projectDir.absolutePath().toStdString());
return -1;
}
auto configFilePath = projectDir.absoluteFilePath("linglong.yaml");
const auto *templateFilePath = LINGLONG_DATA_DIR "/builder/templates/example.yaml";
if (!QFileInfo::exists(templateFilePath)) {
templateFilePath = ":/example.yaml"; // Use Qt resource fallback
LogI("Using template file from Qt resources: {}", templateFilePath);
} else {
LogI("Using template file from system path: {}", templateFilePath);
}
QFile templateFile(templateFilePath);
QFile configFile(configFilePath);
if (!templateFile.open(QIODevice::ReadOnly)) {
LogE("Failed to open template file {}: {}",
templateFilePath,
templateFile.errorString().toStdString());
return -1;
}
if (!configFile.open(QIODevice::WriteOnly)) {
LogE("Failed to open config file {} for writing: {}",
configFilePath.toStdString(),
configFile.errorString().toStdString());
return -1;
}
auto rawData = templateFile.readAll();
rawData.replace("@ID@", name.toUtf8());
if (configFile.write(rawData) <= 0) {
LogE("Failed to write config file {}: {}",
configFilePath.toStdString(),
configFile.errorString().toStdString());
return -1;
}
LogI("Project {} created successfully at {}",
options.projectName,
projectDir.absolutePath().toStdString());
return 0;
}
int handleBuild(linglong::builder::Builder &builder, const BuildCommandOptions &options)
{
LogI("Handling build command");
auto cfg = builder.getConfig();
auto finalBuildOptions = options.builderSpecificOptions;
// offline means skip fetch source and pull dependency
if (options.buildOffline || cfg.offline) {
finalBuildOptions.skipFetchSource = true;
finalBuildOptions.skipPullDepend = true;
}
builder.setBuildOptions(finalBuildOptions);
QStringList commandList;
if (!options.commands.empty()) {
for (const auto &command : options.commands) {
commandList.append(QString::fromStdString(command));
}
}
linglong::utils::error::Result<void> ret;
if (!commandList.isEmpty()) {
ret = builder.build(commandList);
} else {
ret = builder.build();
}
if (!ret) {
LogE("Build failed: {}", ret.error());
return ret.error().code();
}
LogI("Build completed successfully.");
return 0;
}
int handleRun(linglong::builder::Builder &builder, const RunCommandOptions &options)
{
LogI("Handling run command");
std::vector<std::string> modules = { "binary" };
if (options.debugMode) {
modules.emplace_back("develop");
}
if (!options.execModules.empty()) {
for (const auto &module : options.execModules) {
if (std::find(modules.begin(), modules.end(), module) == modules.end()) {
modules.emplace_back(module);
}
}
}
auto result = builder.run(modules,
options.commands,
options.debugMode,
options.workdir,
options.extensions);
if (!result) {
LogE("Run failed: {}", result.error());
return result.error().code();
}
LogI("Run completed successfully.");
return 0;
}
int handleExport(linglong::builder::Builder &builder, const ExportCommandOptions &options)
{
// Create a mutable copy of the export options to potentially modify defaults
auto exportOpts = options.exportSpecificOptions;
// layer 默认使用lz4, 保持和之前版本的兼容
if (exportOpts.compressor.empty()) {
LogI("Compressor not specified, defaulting to lz4 for layer export.");
exportOpts.compressor = "lz4";
}
if (options.layerMode) {
auto result = builder.exportLayer(exportOpts);
if (!result) {
LogE("Export layer failed: {}", result.error());
return result.error().code();
}
return 0;
}
auto result = builder.exportUAB(exportOpts, options.outputFile);
if (!result) {
LogE("Export UAB failed: {}", result.error());
return result.error().code();
}
return 0;
}
int handlePush(linglong::builder::Builder &builder, const PushCommandOptions &options)
{
LogI("Handling push command");
const auto &repoOpts = options.repoOptions;
for (const auto &module : options.pushModules) {
LogI("Pushing module: {}", module);
auto result = builder.push(module, repoOpts.repoUrl, repoOpts.repoName);
if (!result) {
LogE("Push failed for module {}: {}", module, result.error());
return result.error().code();
}
LogI("Module {} pushed successfully.", module);
}
LogI("All modules pushed successfully.");
return 0;
}
int handleList(linglong::repo::OSTreeRepo &repo, [[maybe_unused]] const ListCommandOptions &options)
{
auto ret = linglong::builder::cmdListApp(repo);
if (!ret.has_value()) {
return -1;
}
return 0;
}
int handleRemove(linglong::repo::OSTreeRepo &repo, const RemoveCommandOptions &options)
{
auto ret = linglong::builder::cmdRemoveApp(repo, options.removeList, !options.noCleanObjects);
if (!ret.has_value()) {
return -1;
}
return 0;
}
int handleImport(linglong::repo::OSTreeRepo &repo, const ImportCommandOptions &options)
{
LogI("Handling import command for layer file: {}", options.layerFile);
auto result = linglong::builder::Builder::importLayer(repo, options.layerFile);
if (!result) {
LogE("Import layer failed: {}", result.error());
return result.error().code();
}
LogI("Layer import completed successfully.");
return 0;
}
int handleImportDir(linglong::repo::OSTreeRepo &repo, const ImportDirCommandOptions &options)
{
LogI("Handling import-dir command for layer directory: {}", options.layerDir);
auto result = linglong::builder::Builder::importLayer(repo, options.layerDir);
if (!result) {
LogE("Import layer directory failed: {}", result.error());
return result.error().code();
}
LogI("Layer directory import completed successfully.");
return 0;
}
int handleExtract(const ExtractCommandOptions &options)
{
LogI("Handling extract command for layer file: {} to directory: {}",
options.layerFile,
options.dir);
QString layerFile = QString::fromStdString(options.layerFile);
QString targetDir = QString::fromStdString(options.dir);
auto result = linglong::builder::Builder::extractLayer(layerFile, targetDir);
if (!result) {
LogE("Extract layer failed: {}", result.error());
return result.error().code();
}
LogI("Layer extraction completed successfully.");
return 0;
}
int handleRepoShow(linglong::repo::OSTreeRepo &repo)
{
const auto &cfg = repo.getConfig();
// Note: keep the same format as ll-cli repo
size_t maxUrlLength = 0;
for (const auto &r : cfg.repos) {
maxUrlLength = std::max(maxUrlLength, r.url.size());
}
std::cout << "Default: " << cfg.defaultRepo << std::endl;
std::cout << std::left << std::setw(11) << "Name";
std::cout << std::setw(maxUrlLength + 2) << "Url" << std::setw(11) << "Alias" << std::endl;
for (const auto &r : cfg.repos) {
std::cout << std::left << std::setw(11) << r.name << std::setw(maxUrlLength + 2) << r.url
<< std::setw(11) << r.alias.value_or(r.name) << std::endl;
}
return 0;
}
int handleRepoAdd(linglong::repo::OSTreeRepo &repo, linglong::cli::RepoOptions &options)
{
auto newCfg = repo.getConfig();
std::string alias = options.repoAlias.value_or(options.repoName);
if (options.repoUrl.empty()) {
std::cerr << "url is empty." << std::endl;
return EINVAL;
}
bool isExist = std::any_of(newCfg.repos.begin(), newCfg.repos.end(), [&alias](const auto &r) {
return r.alias.value_or(r.name) == alias;
});
if (isExist) {
LogE("repo {} already exist.", alias);
return -1;
}
newCfg.repos.push_back(linglong::api::types::v1::Repo{
.alias = options.repoAlias,
.name = options.repoName,
.url = options.repoUrl,
});
auto ret = repo.setConfig(newCfg);
if (!ret) {
std::cerr << ret.error().message() << std::endl;
return -1;
}
return 0;
}
int handleRepoRemove(linglong::repo::OSTreeRepo &repo, linglong::cli::RepoOptions &options)
{
auto newCfg = repo.getConfig();
const std::string &alias = options.repoAlias.value_or(options.repoName);
auto existingRepo =
std::find_if(newCfg.repos.begin(), newCfg.repos.end(), [&alias](const auto &r) {
return r.alias.value_or(r.name) == alias;
});
if (existingRepo == newCfg.repos.cend()) {
std::cerr << "the operated repo " + alias + " doesn't exist." << std::endl;
return -1;
}
if (newCfg.defaultRepo == alias) {
std::cerr << "repo " + alias
+ " is default repo, please change default repo before removing it."
<< std::endl;
return -1;
}
newCfg.repos.erase(existingRepo);
auto ret = repo.setConfig(newCfg);
if (!ret) {
std::cerr << ret.error().message() << std::endl;
return -1;
}
LogI("Repository {} removed successfully.", alias);
return 0;
}
int handleRepoUpdate(linglong::repo::OSTreeRepo &repo, linglong::cli::RepoOptions &options)
{
auto newCfg = repo.getConfig();
const std::string &alias = options.repoAlias.value_or(options.repoName);
if (options.repoUrl.empty()) {
std::cerr << "url is empty." << std::endl;
return EINVAL;
}
auto existingRepo =
std::find_if(newCfg.repos.begin(), newCfg.repos.end(), [&alias](const auto &r) {
return r.alias.value_or(r.name) == alias;
});
if (existingRepo == newCfg.repos.cend()) {
std::cerr << "the operated repo " + alias + " doesn't exist." << std::endl;
return -1;
}
existingRepo->url = options.repoUrl;
auto ret = repo.setConfig(newCfg);
if (!ret) {
std::cerr << ret.error().message() << std::endl;
return -1;
}
LogI("Repository {} updated successfully.", alias);
return 0;
}
int handleRepoSetDefault(linglong::repo::OSTreeRepo &repo, linglong::cli::RepoOptions &options)
{
auto newCfg = repo.getConfig();
const std::string &alias = options.repoAlias.value_or(options.repoName);
auto existingRepo =
std::find_if(newCfg.repos.begin(), newCfg.repos.end(), [&alias](const auto &r) {
return r.alias.value_or(r.name) == alias;
});
if (existingRepo == newCfg.repos.cend()) {
std::cerr << "the operated repo " + alias + " doesn't exist." << std::endl;
return -1;
}
if (newCfg.defaultRepo != alias) {
newCfg.defaultRepo = alias;
auto ret = repo.setConfig(newCfg);
if (!ret) {
std::cerr << ret.error().message() << std::endl;
return -1;
}
LogI("Default repository set to {} successfully.", alias);
} else {
LogI("{} is already the default repository.", alias);
}
return 0;
}
int handleRepoEnableMirror(linglong::repo::OSTreeRepo &repo, linglong::cli::RepoOptions &options)
{
auto newCfg = repo.getConfig();
const std::string &alias = options.repoAlias.value_or(options.repoName);
auto existingRepo =
std::find_if(newCfg.repos.begin(), newCfg.repos.end(), [&alias](const auto &r) {
return r.alias.value_or(r.name) == alias;
});
if (existingRepo == newCfg.repos.cend()) {
std::cerr << "the operated repo " + alias + " doesn't exist." << std::endl;
return -1;
}
existingRepo->mirrorEnabled = true;
auto ret = repo.setConfig(newCfg);
if (!ret) {
std::cerr << ret.error().message() << std::endl;
return -1;
}
std::cerr << "Repository " << alias << " mirror enabled successfully.";
return 0;
}
int handleRepoDisableMirror(linglong::repo::OSTreeRepo &repo, linglong::cli::RepoOptions &options)
{
auto newCfg = repo.getConfig();
const std::string &alias = options.repoAlias.value_or(options.repoName);
auto existingRepo =
std::find_if(newCfg.repos.begin(), newCfg.repos.end(), [&alias](const auto &r) {
return r.alias.value_or(r.name) == alias;
});
if (existingRepo == newCfg.repos.cend()) {
std::cerr << "the operated repo " + alias + " doesn't exist." << std::endl;
return -1;
}
existingRepo->mirrorEnabled = false;
auto ret = repo.setConfig(newCfg);
if (!ret) {
std::cerr << ret.error().message() << std::endl;
return -1;
}
std::cerr << "Repository " << alias << " mirror disabled successfully.";
return 0;
}
int handleRepo(linglong::repo::OSTreeRepo &repo,
const RepoSubcommandOptions &options,
CLI::App *buildRepoShow,
CLI::App *buildRepoAdd,
CLI::App *buildRepoRemove,
CLI::App *buildRepoUpdate,
CLI::App *buildRepoSetDefault,
CLI::App *buildRepoEnableMirror,
CLI::App *buildRepoDisableMirror)
{
if (buildRepoShow->parsed()) {
return handleRepoShow(repo);
}
linglong::cli::RepoOptions repoOptions = options.repoOptions;
if (!repoOptions.repoUrl.empty()) {
if (repoOptions.repoUrl.rfind("http", 0) != 0) {
std::cerr << "url is invalid." << std::endl;
return EINVAL;
}
if (repoOptions.repoUrl.back() == '/') {
repoOptions.repoUrl.pop_back();
}
}
if (buildRepoAdd->parsed()) {
return handleRepoAdd(repo, repoOptions);
}
if (buildRepoRemove->parsed()) {
return handleRepoRemove(repo, repoOptions);
}
if (buildRepoUpdate->parsed()) {
return handleRepoUpdate(repo, repoOptions);
}
if (buildRepoSetDefault->parsed()) {
return handleRepoSetDefault(repo, repoOptions);
}
if (buildRepoEnableMirror->parsed()) {
return handleRepoEnableMirror(repo, repoOptions);
}
if (buildRepoDisableMirror->parsed()) {
return handleRepoDisableMirror(repo, repoOptions);
}
std::cerr << "unknown repo operation, please see help information." << std::endl;
return EINVAL;
}
std::vector<std::string> getProjectModule(const linglong::api::types::v1::BuilderProject &project)
{
std::list<std::string> modules = { "binary", "develop" }; // Start with base modules
if (project.modules.has_value()) {
for (const auto &moduleConfig : project.modules.value()) {
// Add module name from the project config
modules.push_back(moduleConfig.name);
}
}
// Ensure uniqueness in the list
modules.sort();
modules.unique();
// Convert the unique list to a vector for the return type
return { modules.begin(), modules.end() };
}
std::optional<std::filesystem::path>
backupFailedMigrationRepo(const std::filesystem::path &repoPath)
{
LogW("Repository migration failed. Attempting to back up the old repository {}",
repoPath.string());
auto backupDirPattern = (repoPath.parent_path() / "linglong-builder.old-XXXXXX").string();
std::error_code ec;
char *backupDir = ::mkdtemp(backupDirPattern.data());
if (backupDir == nullptr) {
LogE("we couldn't generate a temporary directory for migrate, old repo will be removed.");
std::filesystem::remove_all(repoPath, ec); // Use remove_all for directories
if (ec) {
LogE("failed to remove the old repo: {}", repoPath);
}
return std::nullopt;
}
std::filesystem::rename(repoPath, backupDir, ec);
if (ec) {
LogE("Failed to move the old repository to the backup location ({}): {}\nPlease move or "
"remove it manually: {}",
backupDir,
ec.message(),
repoPath.string());
// Attempt to clean up the created backup directory if rename failed
return std::nullopt;
}
LogI("Old repository successfully backed up to: {}. All data will need to be pulled again.",
backupDir);
return backupDir;
}
} // namespace
int main(int argc, char **argv)
{
bindtextdomain(PACKAGE_LOCALE_DOMAIN, PACKAGE_LOCALE_DIR);
textdomain(PACKAGE_LOCALE_DOMAIN);
QCoreApplication app(argc, argv);
// 初始化 qt qrc
Q_INIT_RESOURCE(builder_releases);
// 初始化应用,builder在非tty环境也输出日志
linglong::common::global::applicationInitialize();
linglong::common::global::initLinyapsLogSystem(linglong::utils::log::LogBackend::Console);
CLI::App commandParser{ _("linyaps builder CLI \n"
"A CLI program to build linyaps application\n") };
commandParser.get_help_ptr()->description(_("Print this help message and exit"));
commandParser.set_help_all_flag("--help-all", _("Expand all help"));
commandParser.usage(_("Usage: ll-builder [OPTIONS] [SUBCOMMAND]"));
commandParser.footer([]() {
return _(R"(If you found any problems during use
You can report bugs to the linyaps team under this project: https://github.com/OpenAtom-Linyaps/linyaps/issues)");
});
CLI::Validator validatorString{ validateNonEmptyString, "" };
CreateCommandOptions createOpts;
BuildCommandOptions buildOpts;
RunCommandOptions runOpts;
ExportCommandOptions exportOpts;
PushCommandOptions pushOpts;
ListCommandOptions listOpts;
RemoveCommandOptions removeOpts;
ImportCommandOptions importOpts;
ImportDirCommandOptions importDirOpts;
ExtractCommandOptions extractOpts;
RepoSubcommandOptions repoCmdOpts;
// add builder flags
bool versionFlag = false;
commandParser.add_flag("--version", versionFlag, _("Show version"));
// add builder create
auto buildCreate =
commandParser.add_subcommand("create", _("Create linyaps build template project"));
buildCreate->usage(_("Usage: ll-builder create [OPTIONS] NAME"));
buildCreate->add_option("NAME", createOpts.projectName, _("Project name"))
->required()
->check(validatorString);
// add builder build
std::string filePath;
// group empty will hide command
std::string hiddenGroup = "";
auto buildBuilder = commandParser.add_subcommand("build", _("Build a linyaps project"));
buildBuilder->usage(_("Usage: ll-builder build [OPTIONS] [COMMAND...]"));
buildBuilder->add_option("-f, --file", filePath, _("File path of the linglong.yaml"))
->type_name("FILE")
->check(CLI::ExistingFile);
buildBuilder->add_option(
"COMMAND",
buildOpts.commands,
_("Enter the container to execute command instead of building applications"));
buildBuilder->add_flag("--offline",
buildOpts.buildOffline,
_("Only use local files. This implies --skip-fetch-source and "
"--skip-pull-depend will be set"));
buildBuilder
->add_flag("--full-develop-module",
buildOpts.builderSpecificOptions.fullDevelop,
_("Build full develop packages, runtime requires"))
->group(hiddenGroup);
buildBuilder->add_flag("--skip-fetch-source",
buildOpts.builderSpecificOptions.skipFetchSource,
_("Skip fetch sources"));
buildBuilder->add_flag("--skip-pull-depend",
buildOpts.builderSpecificOptions.skipPullDepend,
_("Skip pull dependency"));
buildBuilder->add_flag("--skip-run-container",
buildOpts.builderSpecificOptions.skipRunContainer,
_("Skip run container"));
buildBuilder->add_flag("--skip-commit-output",
buildOpts.builderSpecificOptions.skipCommitOutput,
_("Skip commit build output"));
buildBuilder->add_flag("--skip-output-check",
buildOpts.builderSpecificOptions.skipCheckOutput,
_("Skip output check"));
buildBuilder->add_flag("--skip-strip-symbols",
buildOpts.builderSpecificOptions.skipStripSymbols,
_("Skip strip debug symbols"));
buildBuilder->add_flag("--isolate-network",
buildOpts.builderSpecificOptions.isolateNetWork,
_("Build in an isolated network environment"));
// add builder run
auto buildRun = commandParser.add_subcommand("run", _("Run built linyaps app"));
buildRun->usage(_("Usage: ll-builder run [OPTIONS] [COMMAND...]"));
buildRun->add_option("-f, --file", filePath, _("File path of the linglong.yaml"))
->type_name("FILE")
->check(CLI::ExistingFile);
buildRun
->add_option("--modules",
runOpts.execModules,
_("Run specified module. eg: --modules binary,develop"))
->delimiter(',')
->allow_extra_args(false)
->type_name("modules");
buildRun
->add_option("--workdir",
runOpts.workdir,
_("Specify the working directory where the application runs"))
->type_name("PATH");
buildRun->add_option(
"COMMAND",
runOpts.commands,
_("Enter the container to execute command instead of running application"));
buildRun->add_flag("--debug",
runOpts.debugMode,
_("Run in debug mode (enable develop module)"));
buildRun
->add_option("--extensions",
runOpts.extensions,
_("Specify extension(s) used by the app to run"))
->type_name("REF")
->delimiter(',')
->allow_extra_args(false)
->check(validatorString);
auto buildList = commandParser.add_subcommand("list", _("List built linyaps app"));
buildList->usage(_("Usage: ll-builder list [OPTIONS]"));
auto buildRemove = commandParser.add_subcommand("remove", _("Remove built linyaps app"));
buildRemove->usage(_("Usage: ll-builder remove [OPTIONS] [APP...]"));
buildRemove->add_flag("--no-clean-objects",
removeOpts.noCleanObjects,
_("Do not clean objects files before remove apps"));
buildRemove->add_option("APP", removeOpts.removeList);
// build export
auto *buildExport = commandParser.add_subcommand("export", _("Export to linyaps layer or uab"));
buildExport->usage(_("Usage: ll-builder export [OPTIONS]"));
buildExport->add_option("-f, --file", filePath, _("File path of the linglong.yaml"))
->type_name("FILE")
->check(CLI::ExistingFile);
buildExport
->add_option("-z, --compressor",
exportOpts.exportSpecificOptions.compressor,
"supported compressors are: lz4(default), lzma, zstd")
->type_name("X");
auto *iconOpt =
buildExport
->add_option("--icon", exportOpts.exportSpecificOptions.iconPath, _("Uab icon (optional)"))
->type_name("FILE")
->check(CLI::ExistingFile);
auto *layerFlag =
buildExport
->add_flag("--layer", exportOpts.layerMode, _("Export to linyaps layer file (deprecated)"))
->excludes(iconOpt);
buildExport
->add_option("--loader", exportOpts.exportSpecificOptions.loader, _("Use custom loader"))
->type_name("FILE")
->check(CLI::ExistingFile)
->excludes(layerFlag);
buildExport
->add_flag("--no-develop",
exportOpts.exportSpecificOptions.noExportDevelop,
_("Don't export the develop module"))
->needs(layerFlag);
buildExport->add_option("-o, --output", exportOpts.outputFile, _("Output file"))
->type_name("FILE")
->excludes(layerFlag);
buildExport
->add_option("--ref", exportOpts.exportSpecificOptions.ref, _("Reference of the package"))
->type_name("REF")
->check(validatorString)
->excludes(layerFlag);
buildExport
->add_option("--modules", exportOpts.exportSpecificOptions.modules, _("Modules to export"))
->type_name("MODULES")
->delimiter(',')
->check(validatorString)
->excludes(layerFlag);
// build push
std::string pushModule;
auto *buildPush = commandParser.add_subcommand("push", _("Push linyaps app to remote repo"));
buildPush->usage(_("Usage: ll-builder push [OPTIONS]"));
buildPush->add_option("-f, --file", filePath, _("File path of the linglong.yaml"))
->type_name("FILE")
->check(CLI::ExistingFile);
buildPush->add_option("--repo-url", pushOpts.repoOptions.repoUrl, _("Remote repo url"))
->type_name("URL")
->check(validatorString);
buildPush->add_option("--repo-name", pushOpts.repoOptions.repoName, _("Remote repo name"))
->type_name("NAME")
->check(validatorString);
buildPush->add_option("--module", pushModule, _("Push single module"))->check(validatorString);
// add build import
auto buildImport =
commandParser.add_subcommand("import", _("Import linyaps layer to build repo"));
buildImport->usage(_("Usage: ll-builder import [OPTIONS] LAYER"));
buildImport->add_option("LAYER", importOpts.layerFile, _("Layer file path"))
->type_name("FILE")
->required()
->check(CLI::ExistingFile);
// add build importDir
auto buildImportDir =
commandParser.add_subcommand("import-dir", _("Import linyaps layer dir to build repo"))
->group(hiddenGroup);
buildImportDir->usage(_("Usage: ll-builder import-dir PATH"));
buildImportDir->add_option("PATH", importDirOpts.layerDir, _("Layer dir path"))
->type_name("PATH")
->required();
// add build extract
auto buildExtract = commandParser.add_subcommand("extract", _("Extract linyaps layer to dir"));
buildExtract->usage(_("Usage: ll-builder extract [OPTIONS] LAYER DIR"));
buildExtract->add_option("LAYER", extractOpts.layerFile, _("Layer file path"))
->required()
->check(CLI::ExistingFile);
buildExtract->add_option("DIR", extractOpts.dir, _("Destination directory"))
->type_name("DIR")
->required();
// add build repo
auto buildRepo = commandParser.add_subcommand("repo", _("Display and manage repositories"));
buildRepo->usage(_("Usage: ll-builder repo [OPTIONS] SUBCOMMAND"));
buildRepo->require_subcommand(1);
// add repo sub command add
auto buildRepoAdd = buildRepo->add_subcommand("add", _("Add a new repository"));
buildRepoAdd->usage(_("Usage: ll-builder repo add [OPTIONS] NAME URL"));
buildRepoAdd->add_option("NAME", repoCmdOpts.repoOptions.repoName, _("Specify the repo name"))
->required()
->check(validatorString);
buildRepoAdd->add_option("URL", repoCmdOpts.repoOptions.repoUrl, _("Url of the repository"))
->required()
->check(validatorString);
buildRepoAdd
->add_option("--alias", repoCmdOpts.repoOptions.repoAlias, _("Alias of the repo name"))
->type_name("ALIAS")
->check(validatorString);
// add repo sub command remove
auto buildRepoRemove = buildRepo->add_subcommand("remove", _("Remove a repository"));
buildRepoRemove->usage(_("Usage: ll-builder repo remove [OPTIONS] NAME"));
buildRepoRemove
->add_option("Alias", repoCmdOpts.repoOptions.repoAlias, _("Alias of the repo name"))
->required()
->check(validatorString);
// add repo sub command update
auto buildRepoUpdate = buildRepo->add_subcommand("update", _("Update the repository URL"));
buildRepoUpdate->usage(_("Usage: ll-builder repo update [OPTIONS] NAME URL"));
buildRepoUpdate
->add_option("Alias", repoCmdOpts.repoOptions.repoAlias, _("Alias of the repo name"))
->required()
->check(validatorString);
buildRepoUpdate->add_option("URL", repoCmdOpts.repoOptions.repoUrl, _("Url of the repository"))
->required()
->check(validatorString);
// add repo sub command update
auto buildRepoSetDefault =
buildRepo->add_subcommand("set-default", _("Set a default repository name"));
buildRepoSetDefault->usage(_("Usage: ll-builder repo set-default [OPTIONS] NAME"));
buildRepoSetDefault
->add_option("Alias", repoCmdOpts.repoOptions.repoAlias, _("Alias of the repo name"))
->required()
->check(validatorString);
// add repo sub command enable mirror
auto buildRepoEnableMirror =
buildRepo->add_subcommand("enable-mirror", _("Enable mirror for the repo"));
buildRepoEnableMirror->usage(_("Usage: ll-builder repo enable-mirror [OPTIONS] ALIAS"));
buildRepoEnableMirror
->add_option("ALIAS", repoCmdOpts.repoOptions.repoAlias, _("Alias of the repo name"))
->required()
->check(validatorString);
// add repo sub command disable mirror
auto buildRepoDisableMirror =
buildRepo->add_subcommand("disable-mirror", _("Disable mirror for the repo"));
buildRepoDisableMirror->usage(_("Usage: ll-builder repo disable-mirror [OPTIONS] ALIAS"));
buildRepoDisableMirror
->add_option("ALIAS", repoCmdOpts.repoOptions.repoAlias, _("Alias of the repo name"))
->required()
->check(validatorString);
// add repo sub command show
auto buildRepoShow = buildRepo->add_subcommand("show", _("Show repository information"));
buildRepoShow->usage(_("Usage: ll-builder repo show [OPTIONS]"));
CLI11_PARSE(commandParser, argc, argv);
if (versionFlag) {
std::cout << _("linyaps build tool version ") << LINGLONG_VERSION << std::endl;
return 0;
}
// command which runs container need run in new user namespace and mount namespace
if (buildBuilder->parsed() || buildExport->parsed() || buildRun->parsed()) {
auto res = linglong::utils::needRunInNamespace();
if (!res) {
LogE("failed to check need run in namespace {}", res.error());
return -1;
}
if (*res) {
auto res = linglong::utils::runInNamespace(argc, argv);
if (!res) {
LogE("failed to run in namespace {}", res.error());
return -1;
}