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
// Copyright 2025 tsz authors. All rights reserved.
// MIT License.
use anyhow::{Context, Result};
use std::path::{Path, PathBuf};
use tracing::{info, warn};
use crate::args::CliArgs;
use crate::incremental::BuildInfo;
use crate::project_refs::{ProjectReferenceGraph, ResolvedProject};
use tsz::checker::diagnostics::DiagnosticCategory;
/// Build mode orchestrator for TypeScript project references.
///
/// This is the entry point for `--build` mode, which:
/// 1. Loads the project reference graph
/// 2. Determines build order via topological sort
/// 3. Checks up-to-date status for each project
/// 4. Compiles dirty projects in dependency order
pub fn build_solution(args: &CliArgs, cwd: &Path, _root_names: &[String]) -> Result<bool> {
// Determine root tsconfig path
let root_config = if let Some(project) = args.project.as_deref() {
cwd.join(project)
} else {
// Find tsconfig.json in current directory
find_tsconfig(cwd)
.ok_or_else(|| anyhow::anyhow!("No tsconfig.json found in {}", cwd.display()))?
};
info!(
"Loading project reference graph from: {}",
root_config.display()
);
// Load project reference graph
let graph = ProjectReferenceGraph::load(&root_config)
.context("Failed to load project reference graph")?;
// Get build order (topological sort)
let build_order = graph
.build_order()
.context("Failed to determine build order (circular dependencies?)")?;
info!("Build order: {} projects", build_order.len());
// Track overall success
let mut all_success = true;
let mut all_diagnostics = Vec::new();
// Build projects in dependency order
for project_id in build_order {
let project = graph
.get_project(project_id)
.ok_or_else(|| anyhow::anyhow!("Project not found: {project_id:?}"))?;
// Check if project is up-to-date
if !args.force && is_project_up_to_date(project, args) {
info!("✓ Project is up to date: {}", project.config_path.display());
continue;
}
info!("Building project: {}", project.config_path.display());
// Compile this project
let result = crate::driver::compile_project(args, &project.root_dir, &project.config_path)
.with_context(|| {
format!("Failed to build project: {}", project.config_path.display())
})?;
// Collect diagnostics
if !result.diagnostics.is_empty() {
all_diagnostics.extend(result.diagnostics.clone());
// Check for errors
let has_errors = result
.diagnostics
.iter()
.any(|d| d.category == DiagnosticCategory::Error);
if has_errors {
all_success = false;
warn!("✗ Project has errors: {}", project.config_path.display());
// Stop on first error unless --force
if !args.force {
// Print diagnostics
for diag in &result.diagnostics {
warn!(" {:?}", diag);
}
return Ok(false);
}
} else {
info!(
"✓ Project built with warnings: {}",
project.config_path.display()
);
}
} else {
info!(
"✓ Project built successfully: {}",
project.config_path.display()
);
}
}
// Print all diagnostics at the end
if !all_diagnostics.is_empty() {
warn!("\n=== Diagnostics ===");
for diag in &all_diagnostics {
warn!("{:?}", diag);
}
}
Ok(all_success)
}
/// Check if a project is up-to-date by examining its .tsbuildinfo file
/// and the outputs of its referenced projects.
pub fn is_project_up_to_date(project: &ResolvedProject, args: &CliArgs) -> bool {
use crate::fs::{FileDiscoveryOptions, discover_ts_files};
use crate::incremental::ChangeTracker;
// Load BuildInfo for this project
let build_info_path = match get_build_info_path(project) {
Some(path) => path,
None => return false,
};
if !build_info_path.exists() {
if args.build_verbose {
info!("No .tsbuildinfo found at {}", build_info_path.display());
}
return false;
}
// Try to load BuildInfo
let build_info = match BuildInfo::load(&build_info_path) {
Ok(Some(info)) => info,
Ok(None) => {
if args.build_verbose {
info!("BuildInfo version mismatch, needs rebuild");
}
return false;
}
Err(e) => {
if args.build_verbose {
warn!(
"Failed to load BuildInfo from {}: {}",
build_info_path.display(),
e
);
}
return false;
}
};
// Check if source files have changed using ChangeTracker
let root_dir = &project.root_dir;
// Discover all TypeScript source files in the project
// Note: out_dir is passed so output files are excluded from discovery
let discovery_options = FileDiscoveryOptions {
base_dir: root_dir.clone(),
files: Vec::new(),
include: None,
exclude: None,
out_dir: project.out_dir.clone(),
follow_links: false,
allow_js: false,
};
let current_files = match discover_ts_files(&discovery_options) {
Ok(files) => files,
Err(e) => {
if args.build_verbose {
warn!(
"Failed to discover source files in {}: {}",
root_dir.display(),
e
);
}
// If we can't scan files, assume we need to rebuild
return false;
}
};
// Use ChangeTracker to detect modifications
// Note: We pass absolute paths for file reading, but ChangeTracker compares using relative paths
let mut tracker = ChangeTracker::new();
if let Err(e) = tracker.compute_changes_with_base(&build_info, ¤t_files, root_dir) {
if args.build_verbose {
warn!("Failed to compute changes: {}", e);
}
return false;
}
if tracker.has_changes() {
if args.build_verbose {
info!(
"Project has changes: {} changed, {} new, {} deleted",
tracker.changed_files().len(),
tracker.new_files().len(),
tracker.deleted_files().len()
);
}
return false;
}
// Check if referenced projects' outputs are still valid
if !are_referenced_projects_uptodate(project, &build_info, args) {
return false;
}
true
}
/// Check if all referenced projects are up-to-date
/// by examining their .tsbuildinfo files and output timestamps.
fn are_referenced_projects_uptodate(
project: &ResolvedProject,
build_info: &BuildInfo,
args: &CliArgs,
) -> bool {
// For each referenced project
for reference in &project.resolved_references {
let project_dir = reference
.config_path
.parent()
.unwrap_or(reference.config_path.as_path());
let ref_build_info_path = project_dir.join("tsconfig.tsbuildinfo");
if !ref_build_info_path.exists() {
if args.build_verbose {
let project_name = reference
.config_path
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("unknown");
info!("Referenced project not built: {}", project_name);
}
return false;
}
match BuildInfo::load(&ref_build_info_path) {
Ok(Some(ref_build_info)) => {
// Check if the referenced project's latest .d.ts file is newer
// than our build time, which would mean we need to rebuild
if let Some(ref latest_dts) = ref_build_info.latest_changed_dts_file {
// Convert relative path to absolute path
let dts_absolute_path = project_dir.join(latest_dts);
// Get the modification time of the .d.ts file
if let Ok(metadata) = std::fs::metadata(&dts_absolute_path)
&& let Ok(dts_modified) = metadata.modified()
{
// Convert the .d.ts modification time to seconds since epoch
if let Ok(dts_secs) = dts_modified.duration_since(std::time::UNIX_EPOCH) {
let dts_timestamp = dts_secs.as_secs();
// Compare with our build time
if dts_timestamp > build_info.build_time {
if args.build_verbose {
let project_name = reference
.config_path
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("unknown");
info!(
"Referenced project's .d.ts is newer: {} ({} > {})",
project_name, dts_timestamp, build_info.build_time
);
}
return false;
}
}
}
}
}
Ok(None) => {
if args.build_verbose {
let project_name = reference
.config_path
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("unknown");
info!("Referenced project has version mismatch: {}", project_name);
}
return false;
}
Err(e) => {
if args.build_verbose {
let project_name = reference
.config_path
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("unknown");
warn!("Failed to load BuildInfo for {}: {}", project_name, e);
}
return false;
}
}
}
true
}
/// Get the path to the .tsbuildinfo file for a project
fn get_build_info_path(project: &ResolvedProject) -> Option<PathBuf> {
use crate::incremental::default_build_info_path;
// Use the same logic as incremental.rs
let out_dir = project.out_dir.as_deref();
Some(default_build_info_path(&project.config_path, out_dir))
}
/// Find a tsconfig.json file in the given directory
fn find_tsconfig(dir: &Path) -> Option<PathBuf> {
let config = dir.join("tsconfig.json");
config.exists().then_some(config)
}