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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
|
// file : libbuild2/dist/operation.cxx -*- C++ -*-
// license : MIT; see accompanying LICENSE file
#include <libbuild2/dist/operation.hxx>
#include <libbutl/sha1.hxx>
#include <libbutl/sha256.hxx>
#include <libbutl/filesystem.hxx> // try_mkdir_p(), cpfile()
#include <libbuild2/file.hxx>
#include <libbuild2/dump.hxx>
#include <libbuild2/scope.hxx>
#include <libbuild2/target.hxx>
#include <libbuild2/context.hxx>
#include <libbuild2/algorithm.hxx>
#include <libbuild2/filesystem.hxx>
#include <libbuild2/diagnostics.hxx>
#include <libbuild2/dist/types.hxx>
#include <libbuild2/dist/rule.hxx>
#include <libbuild2/dist/module.hxx>
using namespace std;
using namespace butl;
namespace build2
{
namespace dist
{
// install -d <dir>
//
static void
install (const process_path*, context&, const dir_path&);
// install <file> <dir>[/<name>]
//
// Return the destination file path.
//
static path
install (const process_path*, const file&, const dir_path&, const path&);
// tar|zip ... <dir>/<pkg>.<ext> <pkg>
//
// Return the archive file path.
//
static path
archive (context& ctx,
const dir_path& root,
const string& pkg,
const dir_path& dir,
const string& ext);
// <ext>sum <arc> > <dir>/<arc>.<ext>
//
// Return the checksum file path.
//
static path
checksum (context&,
const path& arc, const dir_path& dir, const string& ext);
static operation_id
dist_operation_pre (context& ctx, const values&, operation_id o)
{
// Note: cannot be --load-only which requires perform(update).
//
if (ctx.match_only)
fail << "--match-only specified for dist meta-operation";
if (o != default_id)
fail << "explicit operation specified for dist meta-operation";
return o;
}
static void
dist_load_load (const values& vs,
scope& rs,
const path& bf,
const dir_path& out_base,
const dir_path& src_base,
const location& l)
{
// @@ TMP: redo after release (do it here and not in execute, also add
// custom search and do the other half there).
//
#if 0
if (rs.out_path () != out_base || rs.src_path () != src_base)
fail (l) << "dist meta-operation target must be project root directory";
#endif
// Mark this project as being distributed.
//
if (auto* m = rs.find_module<module> (module::name))
m->distributed = true;
perform_load (vs, rs, bf, out_base, src_base, l);
}
// Enter the specified source file as a target of type T. The path is
// expected to be normalized and relative to src_root. If the third
// argument is false, then first check if the file exists. If the fourth
// argument is true, then set the target's path.
//
template <typename T>
static const T*
add_target (const scope& rs, const path& f, bool e = false, bool s = false)
{
tracer trace ("dist::add_target");
path p (rs.src_path () / f);
if (e || exists (p))
{
dir_path d (p.directory ());
// Figure out if we need out.
//
dir_path out (!rs.out_eq_src () ? out_src (d, rs) : dir_path ());
const T& t (rs.ctx.targets.insert_implied<T> (
move (d),
move (out),
p.leaf ().base ().string (),
p.extension (), // Specified.
trace));
if (s)
t.path (move (p));
return &t;
}
return nullptr;
}
// Recursively traverse an src_root subdirectory entering/collecting the
// contained files and file symlinks as the file targets and skipping
// entries that start with a dot. Follow directory symlinks (preserving
// their names) and fail on dangling symlinks. Also detect directory
// symlink cycles.
//
struct subdir
{
const subdir* prev;
const dir_path& dir;
};
static void
add_subdir (const scope& rs,
const dir_path& sd,
action_targets& files,
const subdir* prev = nullptr)
{
dir_path d (rs.src_path () / sd);
const subdir next {prev, d};
try
{
for (const dir_entry& e: dir_iterator (d, dir_iterator::no_follow))
{
const path& n (e.path ());
const string& s (n.string ());
if (s.compare (0, 4, ".git") != 0 &&
s != ".bdep" &&
s != ".bpkg" &&
s != ".build2")
try
{
if (e.type () == entry_type::directory) // Can throw.
{
// If this is a symlink, check that it doesn't cause a cycle.
//
if (e.ltype () == entry_type::symlink)
{
// Note that the resulting path will be absolute and
// normalized.
//
dir_path ld (d / path_cast<dir_path> (n));
dir_path td (path_cast<dir_path> (followsymlink (ld)));
const subdir* s (&next);
for (; s != nullptr; s = s->prev)
{
if (s->dir == td)
{
if (verb)
warn << "directory cycle caused by symlink " << ld <<
info << "symlink target " << td;
break;
}
}
if (s != nullptr)
break;
}
add_subdir (rs, sd / path_cast<dir_path> (n), files, &next);
}
else
files.push_back (add_target<file> (rs, sd / n, true, true));
}
catch (const system_error& e)
{
fail << "unable to stat " << (d / n) << ": " << e;
}
}
}
catch (const system_error& e)
{
fail << "unable to iterate over " << d << ": " << e;
}
}
// If tgt is NULL, then this is the bootstrap mode.
//
static void
dist_project (const scope& rs, const target* tgt, bool prog)
{
tracer trace ("dist::dist_project");
context& ctx (rs.ctx);
const dir_path& out_root (rs.out_path ());
const dir_path& src_root (rs.src_path ());
// Make sure we have the necessary configuration before we get down to
// business.
//
auto l (rs.vars["dist.root"]);
if (!l || l->empty ())
fail << "unknown root distribution directory" <<
info << "did you forget to specify config.dist.root?";
// We used to complain if dist.root does not exist but then, similar
// to install, got tired of user's complaints. So now we just let
// install -d for the package directory create it if necessary.
//
const dir_path& dist_root (cast<dir_path> (l));
l = rs.vars["dist.package"];
if (!l || l->empty ())
fail << "unknown distribution package name" <<
info << "did you forget to set dist.package?";
const module& mod (*rs.find_module<module> (module::name));
const string& dist_package (cast<string> (l));
const process_path* dist_cmd (
cast_null<process_path> (rs.vars["dist.cmd"]));
dir_path td (dist_root / dir_path (dist_package));
// We used to print 'dist <target>' at verbosity level 1 but that has
// proven to be just noise. Though we still want to print something
// since otherwise, once the progress line is cleared, we may end up
// with nothing printed at all.
//
// Note that because of this we can also suppress diagnostics noise
// (e.g., output directory creation) in all the operations below.
//
if (verb == 1)
print_diag ("dist", src_root, td);
// Get the list of files to distribute.
//
action_targets files;
const variable* dist_var (nullptr);
if (tgt != nullptr)
{
l5 ([&]{trace << "load dist " << rs;});
dist_var = rs.var_pool ().find ("dist");
// Match a rule for every operation supported by this project. Skip
// default_id.
//
// Note that we are not calling operation_pre/post() callbacks here
// since the meta operation is dist and we know what we are doing.
//
path_name pn ("<dist>");
const location loc (pn); // Dummy location.
action_targets ts {tgt};
{
// Signal to the rules we will not be executing.
//
auto mog = make_guard ([&ctx] () {ctx.match_only = nullopt;});
ctx.match_only = match_only_level::all;
auto process_postponed = [&ctx, &mod, &ts] (action a)
{
if (!mod.postponed.list.empty ())
{
auto eg (
make_exception_guard (
[&ctx, a, &ts] ()
{
perform_post_operation_callbacks (
ctx, a, ts, true /* failed */);
}));
// Re-grab the phase lock similar to perform_match().
//
phase_lock l (ctx, run_phase::match);
// Note that we don't need to bother with the mutex since we do
// all of this serially. But we can end up with new elements at
// the end.
//
// Strictly speaking, to handle this correctly we would need to
// do multiple passes over this list and only give up when we
// cannot make any progress since earlier entries that we cannot
// resolve could be "fixed" by later entries. But this feels
// far-fetched and so let's wait for a real example before
// complicating this.
//
for (auto i (mod.postponed.list.begin ());
i != mod.postponed.list.end ();
++i)
rule::match_postponed (*i);
}
};
const operations& ops (rs.root_extra->operations);
for (operations::size_type id (default_id + 1); // Skip default_id.
id < ops.size ();
++id)
{
if (const operation_info* oif = ops[id])
{
// Skip aliases (e.g., update-for-install). In fact, one can
// argue the default update should be sufficient since it is
// assumed to update all prerequisites and we no longer support
// ad hoc stuff like test.input. Though here we are using the
// dist meta-operation, not perform.
//
if (oif->id != id)
continue;
// Use standard (perform) match.
//
if (auto pp = oif->pre_operation)
{
if (operation_id pid = pp (ctx, {}, dist_id, loc))
{
const operation_info* poif (ops[pid]);
ctx.current_operation (*poif, oif, false /* diag_noise */);
if (oif->operation_pre != nullptr)
oif->operation_pre (ctx, {}, false /* inner */, loc);
if (poif->operation_pre != nullptr)
poif->operation_pre (ctx, {}, true /* inner */, loc);
action a (dist_id, poif->id, oif->id);
mod.postponed.list.clear ();
perform_match ({}, a, ts,
1 /* diag (failures only) */,
false /* progress */);
process_postponed (a);
perform_post_operation_callbacks (ctx, a, ts, false /*failed*/);
if (poif->operation_post != nullptr)
poif->operation_post (ctx, {}, true /* inner */);
if (oif->operation_post != nullptr)
oif->operation_post (ctx, {}, false /* inner */);
}
}
ctx.current_operation (*oif, nullptr, false /* diag_noise */);
if (oif->operation_pre != nullptr)
oif->operation_pre (ctx, {}, true /* inner */, loc);
action a (dist_id, oif->id);
mod.postponed.list.clear ();
perform_match ({}, a, ts,
1 /* diag (failures only) */,
false /* progress */);
process_postponed (a);
perform_post_operation_callbacks (ctx, a, ts, false /*failed*/);
if (oif->operation_post != nullptr)
oif->operation_post (ctx, {}, true /* inner */);
if (auto po = oif->post_operation)
{
if (operation_id pid = po (ctx, {}, dist_id))
{
const operation_info* poif (ops[pid]);
ctx.current_operation (*poif, oif, false /* diag_noise */);
if (oif->operation_pre != nullptr)
oif->operation_pre (ctx, {}, false /* inner */, loc);
if (poif->operation_pre != nullptr)
poif->operation_pre (ctx, {}, true /* inner */, loc);
action a (dist_id, poif->id, oif->id);
mod.postponed.list.clear ();
perform_match ({}, a, ts,
1 /* diag (failures only) */,
false /* progress */);
process_postponed (a);
perform_post_operation_callbacks (ctx, a, ts, false /*failed*/);
if (poif->operation_post != nullptr)
poif->operation_post (ctx, {}, true /* inner */);
if (oif->operation_post != nullptr)
oif->operation_post (ctx, {}, false /* inner */);
}
}
}
}
}
// Add ad hoc files and buildfiles that are not normally loaded as
// part of the project, for example, the export stub. They will still
// be ignored on the next step if the user explicitly marked them
// with dist=false.
//
auto add_adhoc = [] (const scope& rs)
{
add_target<buildfile> (rs, rs.root_extra->export_file);
if (auto* m = rs.find_module<module> (module::name))
{
for (const path& f: m->adhoc)
{
if (!path_pattern (f))
add_target<file> (rs, f);
else
try
{
path_search (f,
[&rs] (path&& pe, const string&, bool interm)
{
if (!interm)
add_target<file> (rs, pe, true /* exists */);
return true;
},
rs.src_path (),
path_match_flags::none /* no follow_symlinks */);
}
catch (const system_error& e)
{
fail << "unable to scan " << rs.src_path () / f.directory ()
<< ": " << e;
}
}
}
};
add_adhoc (rs);
// The same for subprojects that have been loaded.
//
if (const subprojects* ps = *rs.root_extra->subprojects)
{
for (auto p: *ps)
{
const dir_path& pd (p.second);
dir_path out_nroot (out_root / pd);
const scope& nrs (ctx.scopes.find_out (out_nroot));
if (nrs.out_path () != out_nroot) // This subproject is not loaded.
continue;
if (!nrs.src_path ().sub (src_root)) // Not a strong amalgamation.
continue;
add_adhoc (nrs);
}
}
// Collect the files. We want to take the snapshot of targets since
// updating some of them may result in more targets being entered.
//
// Note that we are not showing progress here (e.g., "N targets to
// distribute") since it will be useless (too fast).
//
auto see_through = [] (const target& t)
{
return ((t.type ().flags & target_type::flag::see_through) ==
target_type::flag::see_through);
};
auto collect = [&trace, &dist_var,
&src_root, &out_root] (const file& ft)
{
if (ft.dir.sub (src_root))
{
// Include unless explicitly excluded.
//
if (const path* v = cast_null<path> (ft[dist_var]))
{
if (v->string () == "false")
{
l5 ([&]{trace << "excluding " << ft;});
return false;
}
}
return true;
}
else if (ft.dir.sub (out_root))
{
// Exclude unless explicitly included.
//
if (const path* v = cast_null<path> (ft[dist_var]))
{
if (v->string () != "false")
{
l5 ([&]{trace << "including " << ft;});
return true;
}
}
return false;
}
else
return false; // Out of project.
};
for (const auto& pt: ctx.targets)
{
// Collect see-through groups if they are marked with dist=true.
//
// Note that while it's possible that only their certain members are
// marked as such (e.g., via a pattern), we will still require
// dist=true on the group itself (and potentially dist=false on some
// of its members) for such cases because we don't want to update
// every see-through group only to discover that most of them don't
// have anything to distribute.
//
if (see_through (*pt))
{
if (const path* v = cast_null<path> ((*pt)[dist_var]))
{
if (v->string () != "false")
{
l5 ([&]{trace << "including group " << *pt;});
files.push_back (pt.get ());
}
}
continue;
}
file* ft (pt->is_a<file> ());
if (ft == nullptr) // Not a file.
continue;
// Skip member of see-through groups since after dist_* their list
// can be incomplete (or even bogus, e.g., the "representative
// sample"). Instead, we will collect them during perfrom_update
// below.
//
if (ft->group != nullptr && see_through (*ft->group))
continue;
if (collect (*ft))
files.push_back (ft);
}
// Make sure what we need to distribute is up to date.
//
{
if (mo_perform.meta_operation_pre != nullptr)
mo_perform.meta_operation_pre (ctx, {}, loc);
// This is a hack since according to the rules we need to completely
// reset the state. We could have done that (i.e., saved target
// names and then re-searched them in the new tree) but that would
// just slow things down while this little cheat seems harmless
// (i.e., assume the dist mete-opreation is "compatible" with
// perform).
//
// Note also that we don't do any structured result printing.
//
size_t on (ctx.current_on);
ctx.current_meta_operation (mo_perform);
ctx.current_on = on + 1;
if (mo_perform.operation_pre != nullptr)
mo_perform.operation_pre (ctx, {}, update_id);
ctx.current_operation (op_update, nullptr, false /* diag_noise */);
if (op_update.operation_pre != nullptr)
op_update.operation_pre (ctx, {}, true /* inner */, loc);
action a (perform_update_id);
mo_perform.match ({}, a, files,
1 /* diag (failures only) */,
prog /* progress */);
mo_perform.execute ({}, a, files,
1 /* diag (failures only) */,
prog /* progress */);
// Replace see-through groups (which now should have their members
// resolved) with members.
//
for (auto i (files.begin ()); i != files.end (); )
{
const target& t (i->as<target> ());
if (see_through (t))
{
group_view gv (t.group_members (a)); // Go directly.
if (gv.members == nullptr)
fail << "unable to resolve see-through group " << t
<< " members";
i = files.erase (i); // Drop the group itself.
for (size_t j (0); j != gv.count; ++j)
{
if (const target* m = gv.members[j])
{
if (const file* ft = m->is_a<file> ())
{
// Note that a rule may only link-up its members to groups
// if/when matched (for example, the cli.cxx{} group). It
// feels harmless for us to do the linking here.
//
if (ft->group == nullptr)
const_cast<file*> (ft)->group = &t;
else
assert (ft->group == &t); // Sanity check.
if (collect (*ft))
{
i = files.insert (i, ft); // Insert instead of the group.
i++; // Stay after the group.
}
}
}
}
}
else
++i;
}
if (op_update.operation_post != nullptr)
op_update.operation_post (ctx, {}, true /* inner */);
if (mo_perform.operation_post != nullptr)
mo_perform.operation_post (ctx, {}, update_id);
if (mo_perform.meta_operation_post != nullptr)
mo_perform.meta_operation_post (ctx, {});
}
}
else
{
l5 ([&]{trace << "bootstrap dist " << rs;});
// Recursively enter/collect file targets in src_root ignoring the
// following ones: .git*, .bdep, .bpkg, and .build2.
//
// Note that, in particular, we also collect the symlinks which point
// outside src_root (think of third-party project packaging with the
// upstream git submodule at the root of the git project). Also note
// that we could probably exclude symlinks which point outside the VCS
// project (e.g., backlinks in a forwarded configuration) but that
// would require the user to supply this boundary (since we don't have
// the notion of VCS root at this level). So let's keep it simple for
// now.
//
add_subdir (rs, dir_path (), files);
}
// Apply project environment.
//
auto_project_env penv (rs);
// Clean up the target directory.
//
if (rmdir_r (ctx, td, true, 2) == rmdir_status::not_empty)
fail << "unable to clean target directory " << td;
auto_rmdir rm_td (td); // Clean it up if things go bad.
install (dist_cmd, ctx, td);
// Copy over all the files. Apply post-processing callbacks.
//
prog = prog && show_progress (1 /* max_verb */);
size_t prog_percent (0);
for (size_t i (0), n (files.size ()); i != n; ++i)
{
const file& t (files[i].as<target> ().as<file> ()); // Only files.
// Figure out where this file is inside the target directory.
//
// First see if the path has been remapped (unless bootstrap).
//
const path* rp (nullptr);
if (tgt != nullptr)
{
if ((rp = cast_null<path> (t[dist_var])) != nullptr)
{
if (rp->string () == "true") // Wouldn't be here if false.
rp = nullptr;
}
}
bool src;
path rn;
dir_path dl;
if (rp == nullptr)
{
src = t.dir.sub (src_root);
dl = src ? t.dir.leaf (src_root) : t.dir.leaf (out_root);
}
else
{
// Sort the remapped path into name (if any) and directory,
// completing the latter if relative.
//
bool n (!rp->to_directory ());
if (n)
{
if (rp->simple ())
{
fail << "expected true, false, of path in the dist variable "
<< "value of target " << t <<
info << "specify ./" << *rp << " to remap the name";
}
rn = rp->leaf ();
}
dir_path rd (n ? rp->directory () : path_cast<dir_path> (*rp));
if (rd.relative ())
rd = t.dir / rd;
rd.normalize ();
src = rd.sub (src_root);
dl = src ? rd.leaf (src_root) : rd.leaf (out_root);
}
dir_path d (td / dl);
if (!exists (d))
install (dist_cmd, ctx, d);
path r (install (dist_cmd, t, d, rn));
// See if this file is in a subproject.
//
const scope* srs (&rs);
const module::callbacks* cbs (&mod.callbacks_);
if (const subprojects* ps = *rs.root_extra->subprojects)
{
for (auto p: *ps)
{
const dir_path& pd (p.second);
if (dl.sub (pd))
{
srs = &ctx.scopes.find_out (out_root / pd);
if (auto* m = srs->find_module<module> (module::name))
cbs = &m->callbacks_;
else
fail << "dist module not loaded in subproject " << pd;
break;
}
}
}
for (module::callback cb: *cbs)
{
const path& pat (cb.pattern);
// If we have a directory, then it should be relative to the project
// root.
//
if (!pat.simple ())
{
assert (pat.relative ());
dir_path d ((src ? srs->src_path () : srs->out_path ()) /
pat.directory ());
d.normalize ();
if (d != t.dir)
continue;
}
if (path_match (t.path ().leaf ().string (), pat.leaf ().string ()))
{
auto_project_env penv (*srs);
cb.function (r, *srs, cb.data);
}
}
if (prog)
{
// Note that this is not merely an optimization since if stderr is
// not a terminal, we print real lines for progress.
//
size_t p ((i * 100) / n);
if (prog_percent != p)
{
prog_percent = p;
diag_progress_lock pl;
diag_progress = ' ';
diag_progress += to_string (prog_percent);
diag_progress += "% of targets distributed";
}
}
}
// Clear the progress if shown.
//
if (prog)
{
diag_progress_lock pl;
diag_progress.clear ();
}
rm_td.cancel ();
// Archive and checksum if requested.
//
if (lookup as = rs.vars["dist.archives"])
{
lookup cs (rs.vars["dist.checksums"]);
// Split the dist.{archives,checksums} value into a directory and
// extension.
//
auto split = [] (const path& p, const dir_path& r, const char* what)
{
dir_path d (p.relative () ? r : dir_path ());
d /= p.directory ();
const string& s (p.string ());
size_t i (path::traits_type::find_leaf (s));
if (i == string::npos)
fail << "invalid extension '" << s << "' in " << what;
if (s[i] == '.') // Skip the dot if specified.
++i;
return pair<dir_path, string> (move (d), string (s, i));
};
for (const path& p: cast<paths> (as))
{
auto ap (split (p, dist_root, "dist.archives"));
path a (archive (ctx, dist_root, dist_package, ap.first, ap.second));
if (cs)
{
for (const path& p: cast<paths> (cs))
{
auto cp (split (p, ap.first, "dist.checksums"));
checksum (ctx, a, cp.first, cp.second);
}
}
}
}
}
static void
dist_load_execute (const values&, action, action_targets& ts,
uint16_t, bool prog)
{
// We cannot do multiple projects because we need to start with a clean
// set of targets.
//
if (ts.size () != 1)
fail << "multiple targets in dist meta-operation" <<
info << "one dist meta-operation can handle one project" <<
info << "consider using several dist meta-operations";
const target& t (ts[0].as<target> ());
const scope* rs (t.base_scope ().root_scope ());
if (rs == nullptr ||
!t.is_a<dir> () ||
(rs->out_path () != t.dir && rs->src_path () != t.dir))
fail << "dist meta-operation target must be project root directory";
if (rs->out_eq_src ())
fail << "in source distribution of target " << t <<
info << "distribution requires out of source build";
dist_project (*rs, &t, prog);
}
// install -d <dir>
//
static void
install (const process_path* cmd, context& ctx, const dir_path& d)
{
path reld;
cstrings args;
if (cmd != nullptr || verb >= 2)
{
reld = relative (d);
args.push_back (cmd != nullptr ? cmd->recall_string () : "install");
args.push_back ("-d");
args.push_back ("-m");
args.push_back ("755");
args.push_back (reld.string ().c_str ());
args.push_back (nullptr);
if (verb >= 2)
print_process (args);
}
if (cmd != nullptr)
run (ctx, *cmd, args, 1 /* finish_verbosity */);
else
{
try
{
// Note that mode has no effect on Windows, which is probably for
// the best.
//
try_mkdir_p (d, 0755);
}
catch (const system_error& e)
{
fail << "unable to create directory " << d << ": " << e;
}
}
}
// install <file> <dir>[/<name>]
//
static path
install (const process_path* cmd,
const file& t,
const dir_path& d,
const path& n)
{
const path& f (t.path ());
path r (d / (n.empty () ? f.leaf () : n));
// Assume the file is executable if the owner has execute permission,
// in which case we make it executable for everyone.
//
bool exe ((path_perms (f) & permissions::xu) == permissions::xu);
path relf, reld;
cstrings args;
if (cmd != nullptr || verb >= 2)
{
relf = relative (f);
reld = relative (d);
if (!n.empty ()) // Leave as just directory if no custom name.
reld /= n;
args.push_back (cmd != nullptr ? cmd->recall_string () : "install");
// Preserve timestamps. This could becomes important if, for example,
// we have pre-generated sources. Note that the install-sh script
// doesn't support this option, while both Linux and BSD install's do.
//
args.push_back ("-p");
// Assume the file is executable if the owner has execute permission,
// in which case we make it executable for everyone.
//
args.push_back ("-m");
args.push_back (exe ? "755" : "644");
args.push_back (relf.string ().c_str ());
args.push_back (reld.string ().c_str ());
args.push_back (nullptr);
if (verb >= 2)
print_process (args);
}
if (cmd != nullptr)
run (t.ctx, *cmd, args, 1 /* finish_verbosity */);
else
{
permissions perm (permissions::ru | permissions::wu |
permissions::rg |
permissions::ro); // 644
if (exe)
perm |= permissions::xu | permissions::xg | permissions::xo; // 755
try
{
// Note that we don't pass cpflags::overwrite_content which means
// this will fail if the file already exists. Since we clean up the
// destination directory, this will detect cases where we have
// multiple source files with the same distribution destination.
//
cpfile (f,
r,
cpflags::overwrite_permissions | cpflags::copy_timestamps,
perm);
}
catch (const system_error& e)
{
if (e.code ().category () == generic_category () &&
e.code ().value () == EEXIST)
{
// @@ TMP (added in 0.16.0).
//
warn << "multiple files are distributed as " << r <<
info << "second file is " << f <<
info << "this warning will become error in the future";
}
else
fail << "unable to copy " << f << " to " << r << ": " << e;
}
}
return r;
}
static path
archive (context& ctx,
const dir_path& root,
const string& pkg,
const dir_path& dir,
const string& e)
{
// NOTE: similar code in bpkg (system-package-manager-archive.cxx).
path an (pkg + '.' + e);
// Delete old archive for good measure.
//
path ap (dir / an);
if (exists (ap, false))
rmfile (ctx, ap, 3 /* verbosity */);
// Use zip for .zip archives. Also recognize and handle a few well-known
// tar.xx cases (in case tar doesn't support -a or has other issues like
// MSYS). Everything else goes to tar in the auto-compress mode (-a).
//
cstrings args;
// Separate compressor (gzip, xz, etc) state.
//
size_t i (0); // Command line start or 0 if not used.
auto_rmfile out_rm; // Output file cleanup (must come first).
auto_fd out_fd; // Output file.
if (e == "zip")
{
// On Windows we use libarchive's bsdtar (zip is an MSYS executable).
//
// While not explicitly stated, the compression-level option works
// for zip archives.
//
#ifdef _WIN32
args = {"bsdtar",
"-a", // -a with the .zip extension seems to be the only way.
"--options=compression-level=9",
"-cf", ap.string ().c_str (),
pkg.c_str (),
nullptr};
#else
args = {"zip",
"-9",
"-rq", ap.string ().c_str (),
pkg.c_str (),
nullptr};
#endif
}
else
{
// On Windows we use libarchive's bsdtar with auto-compression (tar
// itself and quite a few compressors are MSYS executables).
//
// OpenBSD tar does not support --format but it appear ustar is the
// default (while this is not said explicitly in tar(1), it is said in
// pax(1) and confirmed on the mailing list). Nor does it support -a,
// at least as of 7.1 but we will let this play out naturally, in case
// this support gets added.
//
// Note also that our long-term plan is to switch to libarchive in
// order to generate reproducible archives.
//
const char* l (nullptr); // Compression level (option).
#ifdef _WIN32
args = {"bsdtar", "--format", "ustar"};
if (e == "tar.gz")
l = "--options=compression-level=9";
#else
args = {"tar"
#ifndef __OpenBSD__
, "--format", "ustar"
#endif
};
// For gzip it's a good idea to use -9 by default. For bzip2, -9 is
// the default. And for xz, -9 is not recommended as the default due
// memory requirements.
//
// Note also that the compression level can be altered via the GZIP
// (GZIP_OPT also seems to work), BZIP2, and XZ_OPT environment
// variables, respectively.
//
const char* c (nullptr);
if (e == "tar.gz") { c = "gzip"; l = "-9"; }
else if (e == "tar.xz") { c = "xz"; }
else if (e == "tar.bz2") { c = "bzip2"; }
if (c != nullptr)
{
args.push_back ("-cf");
args.push_back ("-");
args.push_back (pkg.c_str ());
args.push_back (nullptr); i = args.size ();
args.push_back (c);
if (l != nullptr)
args.push_back (l);
args.push_back (nullptr);
args.push_back (nullptr); // Pipe end.
try
{
out_fd = fdopen (ap,
fdopen_mode::out | fdopen_mode::binary |
fdopen_mode::truncate | fdopen_mode::create);
out_rm = auto_rmfile (ap);
}
catch (const io_error& e)
{
fail << "unable to open " << ap << ": " << e;
}
}
else
#endif
{
if (e != "tar")
{
args.push_back ("-a");
if (l != nullptr)
args.push_back (l);
}
args.push_back ("-cf");
args.push_back (ap.string ().c_str ());
args.push_back (pkg.c_str ());
args.push_back (nullptr);
}
}
process_path app; // Archiver path.
process_path cpp; // Compressor path.
app = run_search (args[0]);
if (i != 0)
cpp = run_search (args[i]);
if (verb >= 2)
print_process (args);
else if (verb)
print_diag (args[0], dir / dir_path (pkg), ap);
process apr;
process cpr;
// Change the archiver's working directory to root.
//
// Note: this function is called during serial execution and so no
// diagnostics buffering is needed (here and below).
//
apr = run_start (process_env (app, root),
args,
0 /* stdin */,
(i != 0 ? -1 : 1) /* stdout */);
// Start the compressor if required.
//
if (i != 0)
{
cpr = run_start (cpp,
args.data () + i,
apr.in_ofd.get () /* stdin */,
out_fd.get () /* stdout */);
cpr.in_ofd.reset (); // Close the archiver's stdout on our side.
}
// Delay throwing until we diagnose both ends of the pipe.
//
if (!run_finish_code (args.data (),
apr,
1 /* verbosity */,
false /* omit_normal */) ||
!(i == 0 || run_finish_code (args.data () + i, cpr, 1, false)))
throw failed ();
out_rm.cancel ();
return ap;
}
static path
checksum (context& ctx,
const path& ap, const dir_path& dir, const string& e)
{
path an (ap.leaf ());
dir_path ad (ap.directory ());
path cn (an + '.' + e);
// Delete old checksum for good measure.
//
path cp (dir / cn);
if (exists (cp, false))
rmfile (ctx, cp, 3 /* verbosity */);
auto_rmfile c_rm; // Note: must come first.
auto_fd c_fd;
try
{
c_fd = fdopen (cp,
fdopen_mode::out |
fdopen_mode::create |
fdopen_mode::truncate);
c_rm = auto_rmfile (cp);
}
catch (const io_error& e)
{
fail << "unable to open " << cp << ": " << e;
}
// The plan is as follows: look for the <ext>sum program (e.g., sha1sum,
// md5sum, etc). If found, then use that, otherwise, fall back to our
// built-in checksum calculation support.
//
// There are two benefits to first trying the external program: it may
// supports more checksum algorithms and could be faster than our
// built-in code.
//
string pn (e + "sum");
process_path pp (process::try_path_search (pn, true /* init */));
if (!pp.empty ())
{
const char* args[] {
pp.recall_string (),
"-b" /* binary */,
an.string ().c_str (),
nullptr};
if (verb >= 2)
print_process (args);
else if (verb)
print_diag (args[0], ap, cp);
// Note that to only get the archive name (without the directory) in
// the output we have to run from the archive's directory.
//
// Note: this function is called during serial execution and so no
// diagnostics buffering is needed.
//
process pr (run_start (process_env (pp, ad /* cwd */),
args,
0 /* stdin */,
c_fd.get () /* stdout */));
run_finish (args, pr, 1 /* verbosity */);
}
else
{
string (*f) (ifdstream&);
// Note: remember to update info: below if adding another algorithm.
//
if (e == "sha1")
f = [] (ifdstream& i) -> string {return sha1 (i).string ();};
else if (e == "sha256")
f = [] (ifdstream& i) -> string {return sha256 (i).string ();};
else
fail << "no built-in support for checksum algorithm " << e
<< " nor " << e << "sum program found" <<
info << "built-in support is available for sha1, sha256" << endf;
if (verb >= 2)
text << "cat >" << cp;
else if (verb)
print_diag ((e + "sum").c_str (), ap, cp);
string c;
try
{
ifdstream is (ap, fdopen_mode::in | fdopen_mode::binary);
c = f (is);
is.close ();
}
catch (const io_error& e)
{
fail << "unable to read " << ap << ": " << e;
}
try
{
ofdstream os (move (c_fd));
os << c << " *" << an << endl;
os.close ();
}
catch (const io_error& e)
{
fail << "unable to write to " << cp << ": " << e;
}
}
c_rm.cancel ();
return cp;
}
static include_type
dist_include (action,
const target&,
const prerequisite_member& p,
include_type i,
lookup& l)
{
tracer trace ("dist::dist_include");
// Override excluded to adhoc so that every source is included into the
// distribution. Note that this should be harmless to a custom rule
// given the prescribed semantics of adhoc (match/execute but otherwise
// ignore) is followed.
//
// Note that we don't need to do anything for posthoc.
//
if (i == include_type::excluded)
{
l5 ([&]{trace << "overriding exclusion of " << p;});
i = include_type::adhoc;
}
// Also clear any operation-specific overrides.
//
l = lookup ();
return i;
}
const meta_operation_info mo_dist_load {
dist_id,
"dist",
"distribute",
"distributing",
"distributed",
"has nothing to distribute", // We cannot "be distributed".
true, // bootstrap_outer
nullptr, // meta-operation pre
&dist_operation_pre,
&dist_load_load,
&perform_search, // normal search
nullptr, // no match (see dist_execute()).
&dist_load_execute,
nullptr, // operation post
nullptr, // meta-operation post
&dist_include
};
// The bootstrap distribution mode.
//
// Note: pretty similar overall idea as the info meta-operation.
//
void
init_config (scope&); // init.cxx
static void
dist_bootstrap_load (const values&,
scope& rs,
const path&,
const dir_path& out_base,
const dir_path& src_base,
const location& l)
{
if (rs.out_path () != out_base || rs.src_path () != src_base)
fail (l) << "dist meta-operation target must be project root directory";
setup_base (rs.ctx.scopes.rw (rs).insert_out (out_base),
out_base,
src_base);
// Also initialize the dist.* variables (needed in dist_project()).
//
init_config (rs);
}
static void
dist_bootstrap_search (const values&,
const scope& rs,
const scope&,
const path&,
const target_key& tk,
const location& l,
action_targets& ts)
{
if (!tk.type->is_a<dir> ())
fail (l) << "dist meta-operation target must be project root directory";
ts.push_back (&rs);
}
static void
dist_bootstrap_execute (const values&, action, action_targets& ts,
uint16_t, bool prog)
{
for (const action_target& at: ts)
dist_project (at.as<scope> (), nullptr, prog);
}
const meta_operation_info mo_dist_bootstrap {
dist_id,
"dist",
"distribute",
"distributing",
"distributed",
"has nothing to distribute",
true, // bootstrap_outer //@@ Maybe not? (But will overrides work)?
nullptr, // meta-operation pre
&dist_operation_pre,
&dist_bootstrap_load,
&dist_bootstrap_search,
nullptr, // no match (see dist_bootstrap_execute()).
&dist_bootstrap_execute,
nullptr, // operation post
nullptr, // meta-operation post
nullptr // include
};
}
}
|