-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontext.cpp
More file actions
769 lines (655 loc) · 24.8 KB
/
context.cpp
File metadata and controls
769 lines (655 loc) · 24.8 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
// SPDX-License-Identifier: MIT
// Copyright (c) 2024 Putup authors
#include "pup/cli/context.hpp"
#include "pup/core/layout.hpp"
#include "pup/core/metrics.hpp"
#include "pup/core/path_utils.hpp"
#include "pup/core/platform.hpp"
#include "pup/graph/builder.hpp"
#include "pup/graph/dag.hpp"
#include "pup/graph/dep_scanner.hpp"
#include "pup/graph/scanners/gcc.hpp"
#include "pup/index/reader.hpp"
#include "pup/parser/config.hpp"
#include "pup/parser/ignore.hpp"
#include "pup/parser/parser.hpp"
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <format>
#include <fstream>
#include <map>
#include <sstream>
#include <vector>
namespace pup::cli {
auto make_scanner_registry() -> std::optional<graph::DepScannerRegistry>
{
if (auto const* env = std::getenv("PUP_IMPLICIT_DEPS"); env && std::string_view { env } == "0") {
return std::nullopt;
}
auto registry = graph::DepScannerRegistry {};
registry.register_scanner(graph::scanners::make_gcc_scanner());
return registry;
}
auto compute_build_scopes(
Options const& opts,
ProjectLayout const& layout
) -> std::vector<std::string>
{
// -A/--all flag forces full project build
if (opts.all) {
return {};
}
// Explicit targets as scopes
if (!opts.targets.empty()) {
return opts.targets;
}
// Compute scope from current working directory
auto cwd = std::filesystem::current_path();
auto const& source_root = layout.source_root;
// If cwd is source_root, build all
if (cwd == source_root) {
return {};
}
// If cwd is under or equals output_root (but not source_root for in-tree builds),
// build all. The user is in the build directory, not a source subdirectory.
// Source files are under source_root, not output_root, so scoping to output_root
// would incorrectly skip all source file change detection.
auto const& output_root = layout.output_root;
if (source_root != output_root && pup::is_path_under(cwd, output_root)) {
return {};
}
// Get relative path if cwd is under source_root
auto rel = pup::relative_to_root(cwd, source_root);
if (rel.empty()) {
return {};
}
return std::vector<std::string> { rel };
}
namespace {
// Returns empty path for root-equivalent paths ("" or "."), otherwise unchanged
auto normalize_to_empty(std::filesystem::path const& p) -> std::filesystem::path
{
return (p.empty() || p == ".") ? std::filesystem::path {} : p;
}
// Returns "." for root-equivalent paths ("" or "."), otherwise unchanged
auto normalize_to_dot(std::filesystem::path const& p) -> std::filesystem::path
{
return (p.empty() || p == ".") ? std::filesystem::path { "." } : p;
}
// Joins base/rel, but if rel is root-equivalent returns just base
auto join_path(std::filesystem::path const& base, std::filesystem::path const& rel)
-> std::filesystem::path
{
return (rel.empty() || rel == ".") ? base : base / rel;
}
/// State for tracking Tupfile parsing across multiple directories
struct TupfileParseState {
std::set<std::filesystem::path> available;
std::set<std::filesystem::path> parsed;
std::set<std::filesystem::path> parsing;
std::map<std::filesystem::path, parser::VarDb> parsed_configs; // Cache of parsed tup.config files (by path)
std::map<std::filesystem::path, parser::VarDb> scoped_configs; // Cache of merged per-dir configs
std::vector<std::pair<std::string, std::string>> const* config_defines = nullptr; // CLI overrides
};
auto compute_tup_variantdir(
std::filesystem::path const& source_dir,
std::filesystem::path const& source_root,
std::filesystem::path const& output_root
) -> std::string
{
if (!output_root.empty() && source_root != output_root) {
auto output_dir = output_root / source_dir;
auto src_dir = source_root / source_dir;
auto rel = std::filesystem::relative(output_dir, src_dir);
return rel.generic_string();
}
return ".";
}
auto find_build_subdir(
std::filesystem::path const& root
) -> std::optional<std::filesystem::path>
{
for (auto const& name : { "build", "out", "variant" }) {
auto dir = std::filesystem::path { root / name };
if (std::filesystem::exists(dir / "tup.config")
|| std::filesystem::is_directory(dir / ".pup")) {
return dir;
}
}
if (std::filesystem::is_directory(root)) {
for (auto const& entry : std::filesystem::directory_iterator(root)) {
if (entry.is_directory()) {
if (std::filesystem::exists(entry.path() / "tup.config")
|| std::filesystem::is_directory(entry.path() / ".pup")) {
return entry.path();
}
}
}
}
return std::nullopt;
}
auto read_file(std::filesystem::path const& path) -> std::optional<std::string>
{
auto file = std::ifstream { path };
if (!file) {
return std::nullopt;
}
auto ss = std::stringstream {};
ss << file.rdbuf();
return ss.str();
}
auto discover_tupfile_dirs(
std::filesystem::path const& root,
pup::parser::IgnoreList const& ignore = {}
) -> std::set<std::filesystem::path>
{
auto dirs = std::set<std::filesystem::path> {};
auto ec = std::error_code {};
auto options = std::filesystem::directory_options::skip_permission_denied;
for (auto it = std::filesystem::recursive_directory_iterator(root, options, ec);
it != std::filesystem::recursive_directory_iterator();
++it) {
if (ec) {
break;
}
auto const& entry = *it;
auto rel = std::filesystem::relative(entry.path(), root);
if (entry.is_directory() && ignore.is_ignored(rel)) {
it.disable_recursion_pending();
continue;
}
if (!entry.is_regular_file()) {
continue;
}
if (entry.path().filename() != "Tupfile") {
continue;
}
auto dir = std::filesystem::path { entry.path().parent_path() };
auto dir_rel = std::filesystem::relative(dir, root);
dirs.insert(normalize_to_dot(dir_rel));
}
return dirs;
}
/// Apply CLI config overrides to a VarDb
auto apply_config_overrides(
parser::VarDb& config,
std::vector<std::pair<std::string, std::string>> const* defines
) -> void
{
if (!defines) {
return;
}
for (auto const& [name, value] : *defines) {
config.set(name, value);
config.set("CONFIG_" + name, value);
}
}
/// Parse a tup.config file, returning a cached result on repeat calls.
auto get_or_parse_config(
std::filesystem::path const& path,
TupfileParseState& state
) -> parser::VarDb const*
{
if (auto it = state.parsed_configs.find(path); it != state.parsed_configs.end()) {
return &it->second;
}
auto result = parser::parse_config(path);
if (!result) {
fprintf(stderr, "Warning: Failed to parse %s: %s\n", path.string().c_str(), result.error().message.c_str());
return nullptr;
}
auto [it, _] = state.parsed_configs.emplace(path, std::move(*result));
return &it->second;
}
/// Merge all tup.config files from root down to target directory.
/// Parent configs override child configs on collision (same authority
/// model as Tuprules.tup ?= defaults).
/// Returns pointer to the cached VarDb for that directory.
auto find_config_for_dir(
std::filesystem::path const& rel_dir,
std::filesystem::path const& output_root,
TupfileParseState& state
) -> parser::VarDb const*
{
auto normalized = normalize_to_empty(rel_dir);
// Check cache first
if (auto it = state.scoped_configs.find(normalized); it != state.scoped_configs.end()) {
return &it->second;
}
// Collect all tup.config paths from root down to target directory
auto config_paths = std::vector<std::filesystem::path> {};
auto root_config = output_root / "tup.config";
if (std::filesystem::exists(root_config)) {
config_paths.push_back(root_config);
}
if (!normalized.empty()) {
auto accumulated = output_root;
for (auto const& component : normalized) {
accumulated /= component;
auto config_path = accumulated / "tup.config";
if (std::filesystem::exists(config_path)) {
config_paths.push_back(config_path);
}
}
}
if (config_paths.empty()) {
auto [it, _] = state.scoped_configs.emplace(normalized, parser::VarDb {});
return &it->second;
}
// Merge leaf first (defaults), then each parent on top (overrides).
// config_paths is root-to-leaf, so reverse iteration gives leaf→root.
auto merged = parser::VarDb {};
for (auto it = config_paths.rbegin(); it != config_paths.rend(); ++it) {
auto const* cfg = get_or_parse_config(*it, state);
if (cfg) {
for (auto const& name : cfg->names()) {
merged.set(std::string { name }, std::string { cfg->get(name) });
}
}
}
apply_config_overrides(merged, state.config_defines);
auto [it, _] = state.scoped_configs.emplace(normalized, std::move(merged));
return &it->second;
}
auto make_circular_dep_error(std::filesystem::path const& dir) -> pup::Error
{
return pup::Error {
pup::ErrorCode::CyclicDependency,
std::format("Circular Tupfile dependency: {}", dir.string())
};
}
auto make_read_error(std::filesystem::path const& path) -> pup::Error
{
return pup::Error {
pup::ErrorCode::IoError,
std::format("Failed to read {}", path.string())
};
}
struct ParseContext {
TupfileParseState& state;
pup::graph::GraphBuilder& builder;
pup::graph::BuildGraph& graph;
std::filesystem::path const& source_root;
std::filesystem::path const& config_root;
std::filesystem::path const& output_root;
pup::parser::VarDb const& base_vars;
bool verbose;
bool root_config_only;
VarAssignedCallback on_var_assigned;
};
auto parse_directory(std::filesystem::path const& rel_dir, ParseContext& ctx) -> pup::Result<void>
{
auto vars = pup::parser::VarDb { ctx.base_vars };
auto normalized_dir = normalize_to_dot(rel_dir);
if (ctx.state.parsed.contains(normalized_dir)) {
return {};
}
if (ctx.state.parsing.contains(normalized_dir)) {
return pup::unexpected<pup::Error>(make_circular_dep_error(normalized_dir));
}
ctx.state.parsing.insert(normalized_dir);
// Tupfiles are found in config_root (may differ from source_root in 3-tree builds)
auto tupfile_path = join_path(ctx.config_root, normalize_to_empty(rel_dir)) / "Tupfile";
if (ctx.verbose) {
printf("Parsing: %s\n", tupfile_path.string().c_str());
}
auto source = read_file(tupfile_path);
if (!source) {
ctx.state.parsing.erase(normalized_dir);
return pup::unexpected<pup::Error>(make_read_error(tupfile_path));
}
auto parse_result = pup::parser::parse_tupfile(*source, tupfile_path.string());
if (!parse_result.success()) {
ctx.state.parsing.erase(normalized_dir);
for (auto const& err : parse_result.errors) {
fprintf(stderr, "%s:%u:%u: error: %s\n", tupfile_path.string().c_str(), err.location.line, err.location.column, err.message.c_str());
}
return pup::make_error<void>(pup::ErrorCode::ParseError, "Parse failed");
}
auto tup_cwd = normalized_dir.generic_string();
// In the "overlay" model, Tupfiles from config_root are treated as if they
// were in source_root. Commands run from source_root, so all relative paths
// (TUP_VARIANTDIR, TUP_OUTDIR, etc.) must be computed relative to source_root.
auto rel_dir_normalized = normalize_to_empty(rel_dir);
auto tup_variantdir = compute_tup_variantdir(rel_dir_normalized, ctx.source_root, ctx.output_root);
// TUP_SRCDIR: relative path to source files from where commands run.
// In overlay model, commands run from source_root, so TUP_SRCDIR is always "."
auto tup_srcdir = std::string { "." };
// TUP_OUTDIR: relative path from source dir (where commands run) to output dir.
// For in-tree builds (source == output): "."
// For variant builds: e.g., "../../build/coreutils" from source/coreutils/
auto tup_outdir = std::string { "." };
if (ctx.source_root != ctx.output_root) {
auto source_dir = join_path(ctx.source_root, rel_dir_normalized);
auto output_dir = join_path(ctx.output_root, rel_dir_normalized);
tup_outdir = std::filesystem::relative(output_dir, source_dir).generic_string();
}
// Get the scoped config for this directory (walks up tree to find nearest tup.config)
// When root_config_only is set (for configure pass), always use root config
auto const* scoped_config = find_config_for_dir(
ctx.root_config_only ? std::filesystem::path {} : rel_dir,
ctx.output_root,
ctx.state
);
auto request_directory = [&](std::filesystem::path const& dir) -> pup::Result<void> {
return parse_directory(dir, ctx);
};
auto eval_ctx = pup::parser::EvalContext {
.vars = &vars,
.config_vars = scoped_config,
.tup_cwd = tup_cwd,
.tup_platform = pup::get_platform(),
.tup_arch = std::string { pup::ARCH },
.tup_variantdir = tup_variantdir,
.tup_variant_outputdir = tup_variantdir,
.tup_srcdir = tup_srcdir,
.tup_outdir = tup_outdir,
.request_directory = request_directory,
.available_tupfile_dirs = &ctx.state.available,
.on_var_assigned = ctx.on_var_assigned,
};
auto result = pup::Result<void> { ctx.builder.add_tupfile(ctx.graph, parse_result.tupfile, eval_ctx) };
ctx.state.parsing.erase(normalized_dir);
ctx.state.parsed.insert(normalized_dir);
if (result) {
++pup::thread_metrics().tupfiles_parsed;
}
return result;
}
auto try_auto_init(ProjectLayout const& layout) -> void
{
auto pup_dir = layout.pup_dir();
if (std::filesystem::exists(pup_dir)) {
return;
}
if (!std::filesystem::exists(layout.source_root / "Tupfile.ini")) {
return;
}
std::filesystem::create_directories(pup_dir);
printf("Initialized pup in \"%s\"\n", pup_dir.string().c_str());
}
auto load_ignore_list(ProjectLayout const& layout, bool verbose) -> pup::parser::IgnoreList
{
auto ignore = pup::parser::IgnoreList::with_defaults();
for (auto const& root : { layout.config_root, layout.source_root }) {
auto ignore_path = root / ".pupignore";
if (!std::filesystem::exists(ignore_path)) {
continue;
}
auto ignore_result = pup::parser::IgnoreList::load(ignore_path);
if (!ignore_result) {
continue;
}
ignore = std::move(*ignore_result);
if (verbose) {
printf("Loaded %zu ignore patterns from %s\n", ignore.size(), ignore_path.string().c_str());
}
break;
}
return ignore;
}
struct IndexLoadResult {
std::optional<pup::index::Index> index;
std::unordered_map<std::string, std::string> cached_env_vars;
};
auto load_old_index(std::filesystem::path const& output_root, bool verbose) -> IndexLoadResult
{
auto result = IndexLoadResult {};
auto index_path = output_root / ".pup" / "index";
if (!std::filesystem::exists(index_path)) {
return result;
}
auto index_load_start = std::chrono::steady_clock::now();
auto index_result = pup::index::read_index(index_path);
if (!index_result) {
return result;
}
result.index = std::move(*index_result);
auto index_load_end = std::chrono::steady_clock::now();
pup::thread_metrics().index_load_time = std::chrono::duration_cast<std::chrono::milliseconds>(
index_load_end - index_load_start
);
constexpr auto ENV_VAR_DIR_PREFIX = std::string_view { "$/" };
for (auto const& file : result.index->files()) {
if (file.type != pup::NodeType::Variable) {
continue;
}
if (!file.path.starts_with(ENV_VAR_DIR_PREFIX)) {
continue;
}
auto key_value = std::string_view { file.path }.substr(ENV_VAR_DIR_PREFIX.size());
auto eq_pos = key_value.find('=');
if (eq_pos != std::string::npos) {
result.cached_env_vars[std::string { key_value.substr(0, eq_pos) }] = std::string { key_value.substr(eq_pos + 1) };
}
}
if (verbose && !result.cached_env_vars.empty()) {
printf("Loaded %zu cached env vars from index\n", result.cached_env_vars.size());
}
return result;
}
auto sort_dirs_by_depth(std::set<std::filesystem::path> const& available) -> std::vector<std::filesystem::path>
{
auto root_rel = std::filesystem::path { "." };
auto dirs = std::vector<std::filesystem::path> { available.begin(), available.end() };
std::ranges::sort(dirs, [&root_rel](auto const& a, auto const& b) {
auto is_root_a = (a == root_rel);
auto is_root_b = (b == root_rel);
if (is_root_a != is_root_b) {
return is_root_b;
}
auto depth_a = std::distance(a.begin(), a.end());
auto depth_b = std::distance(b.begin(), b.end());
if (depth_a != depth_b) {
return depth_a > depth_b;
}
return a < b;
});
return dirs;
}
} // namespace
auto make_layout_options(Options const& opts) -> LayoutOptions
{
auto layout_opts = LayoutOptions {};
if (!opts.source_dir.empty()) {
layout_opts.source_dir = std::filesystem::path { opts.source_dir };
}
if (!opts.config_dir.empty()) {
layout_opts.config_dir = std::filesystem::path { opts.config_dir };
}
if (!opts.build_dirs.empty()) {
layout_opts.build_dir = std::filesystem::path { opts.build_dirs[0] };
}
return layout_opts;
}
struct BuildContext::Impl {
ProjectLayout layout;
parser::VarDb config_vars;
parser::VarDb vars;
graph::BuildGraph graph;
TupfileParseState state;
std::optional<index::Index> old_index;
};
BuildContext::BuildContext()
: impl_(std::make_unique<Impl>())
{
}
BuildContext::~BuildContext() = default;
BuildContext::BuildContext(BuildContext&&) noexcept = default;
auto BuildContext::operator=(BuildContext&&) noexcept -> BuildContext& = default;
auto BuildContext::layout() const -> ProjectLayout const&
{
return impl_->layout;
}
auto BuildContext::graph() const -> graph::BuildGraph const&
{
return impl_->graph;
}
auto BuildContext::graph() -> graph::BuildGraph&
{
return impl_->graph;
}
auto BuildContext::config_vars() const -> parser::VarDb const&
{
return impl_->config_vars;
}
auto BuildContext::vars() const -> parser::VarDb const&
{
return impl_->vars;
}
auto BuildContext::parsed_dirs() const -> std::set<std::filesystem::path> const&
{
return impl_->state.parsed;
}
auto BuildContext::old_index() const -> index::Index const*
{
return impl_->old_index ? &*impl_->old_index : nullptr;
}
auto build_context(
Options const& opts,
BuildContextOptions const& ctx_opts
) -> Result<BuildContext>
{
// 1. Discover layout
auto layout_result = Result<ProjectLayout> { discover_layout(make_layout_options(opts)) };
if (!layout_result) {
return unexpected<Error>(layout_result.error());
}
auto ctx = BuildContext {};
ctx.impl_->layout = std::move(*layout_result);
// Early tup.config check (before expensive parsing)
if (ctx_opts.require_config) {
auto config_path = ctx.impl_->layout.output_root / "tup.config";
if (!std::filesystem::exists(config_path)) {
return make_error<BuildContext>(
ErrorCode::NotFound,
"No tup.config found. Run 'pup configure' first."
);
}
}
// Set build root name for variant builds (before parsing)
if (ctx.impl_->layout.source_root != ctx.impl_->layout.output_root) {
auto build_root_name = std::filesystem::relative(
ctx.impl_->layout.output_root,
ctx.impl_->layout.source_root
)
.generic_string();
ctx.impl_->graph.set_build_root_name(std::move(build_root_name));
}
// 2. Auto-init if needed
if (ctx_opts.auto_init) {
try_auto_init(ctx.impl_->layout);
}
// 3. Discover Tupfiles
auto ignore = load_ignore_list(ctx.impl_->layout, ctx_opts.verbose);
ctx.impl_->state.available = discover_tupfile_dirs(ctx.impl_->layout.config_root, ignore);
if (ctx.impl_->state.available.empty()) {
return make_error<BuildContext>(ErrorCode::IoError, "No Tupfiles found in project");
}
if (ctx_opts.verbose) {
printf("Found %zu directories with Tupfiles\n", ctx.impl_->state.available.size());
}
// 4. Load config (seeds the per-file parse cache for find_config_for_dir)
auto config_path = ctx.impl_->layout.output_root / "tup.config";
if (std::filesystem::exists(config_path)) {
auto const* root_cfg = get_or_parse_config(config_path, ctx.impl_->state);
if (root_cfg) {
ctx.impl_->config_vars = *root_cfg;
if (ctx_opts.verbose) {
printf("Loaded %zu config variables from %s\n", ctx.impl_->config_vars.names().size(), config_path.string().c_str());
}
}
}
// Apply -D config overrides (highest precedence)
for (auto const& [name, value] : opts.config_defines) {
ctx.impl_->config_vars.set(name, value);
ctx.impl_->config_vars.set("CONFIG_" + name, value);
if (ctx_opts.verbose) {
printf("-D %s=%s\n", name.c_str(), value.c_str());
}
}
// Store config_defines for scoped configs to use
if (!opts.config_defines.empty()) {
ctx.impl_->state.config_defines = &opts.config_defines;
}
// 5. Load index
auto [old_index, cached_env_vars] = load_old_index(ctx.impl_->layout.output_root, ctx_opts.verbose);
ctx.impl_->old_index = std::move(old_index);
// 6. Parse Tupfiles
auto builder_opts = graph::BuilderOptions {
.source_root = ctx.impl_->layout.source_root,
.config_root = ctx.impl_->layout.config_root,
.output_root = ctx.impl_->layout.output_root,
.config_path = config_path,
.expand_globs = true,
.scanner_registry = ctx_opts.scanner_registry,
.pattern_registry = ctx_opts.pattern_registry,
.cached_env_vars = std::move(cached_env_vars),
};
auto builder = graph::GraphBuilder { builder_opts };
auto parse_ctx = ParseContext {
.state = ctx.impl_->state,
.builder = builder,
.graph = ctx.impl_->graph,
.source_root = ctx.impl_->layout.source_root,
.config_root = ctx.impl_->layout.config_root,
.output_root = ctx.impl_->layout.output_root,
.base_vars = ctx.impl_->vars,
.verbose = ctx_opts.verbose,
.root_config_only = ctx_opts.root_config_only,
.on_var_assigned = ctx_opts.on_var_assigned,
};
for (auto const& dir : sort_dirs_by_depth(ctx.impl_->state.available)) {
if (ctx.impl_->state.parsed.contains(dir)) {
continue;
}
auto result = Result<void> { parse_directory(dir, parse_ctx) };
if (!result && !ctx_opts.keep_going) {
return unexpected<Error>(result.error());
}
}
// Resolve deferred order-only edges (side effect: modifies graph; return value is count, unused)
(void)builder.resolve_deferred_order_only_edges(ctx.impl_->graph);
for (auto const& warning : builder.warnings()) {
fprintf(stderr, "warning: %s\n", warning.c_str());
}
if (ctx_opts.verbose) {
printf("Parsed %zu Tupfiles\n", ctx.impl_->state.parsed.size());
}
return ctx;
}
auto resolve_clean_context(Options const& opts) -> std::optional<CleanContext>
{
auto cwd = std::filesystem::current_path();
auto root = find_project_root(cwd);
if (!root) {
return std::nullopt;
}
auto build_dir = std::filesystem::path {};
auto is_in_tree = false;
if (!opts.build_dirs.empty()) {
build_dir = std::filesystem::path { opts.build_dirs[0] };
if (build_dir.is_relative()) {
build_dir = *root / build_dir;
}
is_in_tree = (build_dir == *root);
} else if (std::filesystem::exists(cwd / ".pup") && cwd != *root) {
// cwd contains .pup and is not source root - we're inside a build directory
build_dir = cwd;
is_in_tree = false;
} else if (auto detected = find_build_subdir(*root)) {
// Prefer build subdirectory with .pup/index over source root
build_dir = *detected;
is_in_tree = false;
} else if (std::filesystem::exists(*root / "tup.config")
|| std::filesystem::exists(*root / ".pup")) {
// Fall back to source root for in-tree builds
build_dir = *root;
is_in_tree = true;
} else {
return std::nullopt;
}
return CleanContext { *root, build_dir, is_in_tree };
}
} // namespace pup::cli