jbuild 0.1.9

High-performance Java build tool supporting Maven and Gradle
Documentation
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
//! Interactive build monitoring and enhanced user experience

use std::{
    time::{Duration, Instant},
    sync::mpsc::{self, Sender, Receiver},
    thread,
};
use console::{Term, style};
use crate::ui::{info, success, error, create_build_progress, create_dependency_progress};
use crate::build::{BuildSystem, BuildExecutor, ExecutionRequest};
use crate::maven::core::MavenBuildExecutor;
use crate::gradle::core::GradleExecutor;
use anyhow::Result;
use chrono;

/// Build monitoring data structure
#[derive(Debug, Clone)]
pub struct BuildMetrics {
    pub start_time: Instant,
    pub phase_times: Vec<(String, Duration)>,
    pub current_phase: Option<String>,
    pub total_dependencies: usize,
    pub processed_dependencies: usize,
    pub compilation_files: usize,
    pub test_files: usize,
    pub memory_usage_mb: u64,
    pub cpu_usage_percent: f32,
}

impl BuildMetrics {
    pub fn new() -> Self {
        Self {
            start_time: Instant::now(),
            phase_times: Vec::new(),
            current_phase: None,
            total_dependencies: 0,
            processed_dependencies: 0,
            compilation_files: 0,
            test_files: 0,
            memory_usage_mb: 0,
            cpu_usage_percent: 0.0,
        }
    }

    pub fn elapsed(&self) -> Duration {
        self.start_time.elapsed()
    }

    pub fn add_phase_time(&mut self, phase: String, duration: Duration) {
        self.phase_times.push((phase, duration));
    }

    pub fn update_progress(&mut self, processed: usize, total: usize) {
        self.processed_dependencies = processed;
        self.total_dependencies = total;
    }
}

/// Interactive build execution with real-time monitoring
pub fn run_interactive(verbose: bool, monitor: bool, dashboard: bool) -> Result<()> {
    info("🚀 Starting interactive build mode");
    
    let base_dir = std::env::current_dir()?;
    let build_system = BuildSystem::detect(&base_dir)
        .ok_or_else(|| anyhow::anyhow!("No build system detected"))?;
    
    info(&format!("📦 Detected build system: {}", 
        match build_system {
            BuildSystem::Maven => "Maven",
            BuildSystem::Gradle => "Gradle",
        }
    ));

    let term = Term::stdout();
    term.clear_line()?;
    
    if dashboard {
        run_dashboard(build_system, verbose)?;
    } else {
        run_interactive_build(build_system, verbose, monitor)?;
    }
    
    Ok(())
}

/// Run build with interactive monitoring
fn run_interactive_build(build_system: BuildSystem, _verbose: bool, _monitor: bool) -> Result<()> {
    let (metrics_tx, metrics_rx) = mpsc::channel();
    let (progress_tx, _progress_rx) = mpsc::channel();
    
    // Create progress clone for simulation
    let progress_clone = progress_tx.clone();
    
    // Start monitoring thread
    let handle = thread::spawn(move || {
        monitor_build_progress(metrics_rx, progress_tx);
    });
    
    // Execute build
    let request = ExecutionRequest {
        base_directory: std::env::current_dir()?,
        goals: vec!["compile".to_string()],
        system_properties: std::collections::HashMap::new(),
        show_errors: true,
        offline: false,
    };
    
    let executor: Box<dyn BuildExecutor> = match build_system {
        BuildSystem::Maven => Box::new(MavenBuildExecutor::new()),
        BuildSystem::Gradle => Box::new(GradleExecutor::new()),
    };
    
    // Send metrics to monitor
    metrics_tx.send(BuildMetrics::new())?;
    
    // Simulate progress updates (in real implementation, this would come from actual build)
    simulate_progress_updates(progress_clone)?;
    
    let _result = executor.execute(request);
    
    // Cleanup
    handle.join().unwrap();
    
    // TODO: Fix actual result handling
    success("✅ Build completed successfully!");
    Ok(())
}

/// Run dashboard view
fn run_dashboard(build_system: BuildSystem, _verbose: bool) -> Result<()> {
    info("📊 Starting build dashboard");
    
    let term = Term::stdout();
    let mut metrics = BuildMetrics::new();
    
    // Create dashboard elements
    let main_progress = create_build_progress();
    let dependency_progress = create_dependency_progress(100);
    
    println!("\n{} jbuild Build Dashboard {}\n", 
        style("=".repeat(10)).blue().bold(),
        style("=".repeat(10)).blue().bold()
    );
    
    let mut running = true;
    let start_time = Instant::now();
    
    while running {
        term.clear_line()?;
        
        // Update metrics (simulated)
        metrics.processed_dependencies = (metrics.processed_dependencies + 1) % 100;
        metrics.total_dependencies = 100;
        metrics.compilation_files = (metrics.compilation_files + 2) % 50;
        metrics.test_files = (metrics.test_files + 1) % 20;
        
        // Display dashboard
        display_dashboard(&metrics, &start_time, build_system)?;
        
        thread::sleep(Duration::from_millis(100));
        
        // Simulate dashboard duration
        if start_time.elapsed() > Duration::from_secs(10) {
            running = false;
        }
    }
    
    main_progress.finish();
    dependency_progress.finish();
    
    success("🎉 Dashboard session completed!");
    Ok(())
}

/// Display interactive dashboard
pub fn display_dashboard(metrics: &BuildMetrics, start_time: &Instant, build_system: BuildSystem) -> Result<()> {
    let elapsed = start_time.elapsed();
    let elapsed_secs = elapsed.as_secs();
    let elapsed_mins = elapsed_secs / 60;
    let remaining_secs = elapsed_secs % 60;
    
    // Header
    println!("{} Build Status {}", style("").green(), style(format!("[{elapsed_mins:02}:{remaining_secs:02}]")).cyan());
    
    // Build system info
    println!("📦 System: {}", 
        match build_system {
            BuildSystem::Maven => "Maven",
            BuildSystem::Gradle => "Gradle",
        }
    );
    
    // Progress bars
    println!("⚡ Dependencies: {}/{}", metrics.processed_dependencies, metrics.total_dependencies);
    println!("📄 Compiling: {} files", metrics.compilation_files);
    println!("🧪 Testing: {} files", metrics.test_files);
    
    // Memory and CPU (simulated)
    let memory_mb = 512 + (metrics.processed_dependencies as f64 * 0.1) as u64;
    let cpu_percent = 25.0 + (metrics.processed_dependencies as f64 * 0.5);
    
    println!("💾 Memory: {} MB", memory_mb);
    println!("🖥️  CPU: {:.1}%", cpu_percent);
    
    // Performance indicators
    let throughput = metrics.processed_dependencies as f64 / elapsed_secs.max(1) as f64;
    println!("⚡ Throughput: {:.1} deps/sec", throughput);
    
    println!();
    Ok(())
}

/// Monitor build progress
fn monitor_build_progress(metrics_rx: Receiver<BuildMetrics>, progress_tx: Sender<String>) {
    while let Ok(metrics) = metrics_rx.recv() {
        // Simulate progress monitoring
        if let Some(ref phase) = metrics.current_phase {
            progress_tx.send(format!("🔄 {}: {}%", phase, metrics.processed_dependencies)).unwrap();
        }
    }
}

/// Simulate progress updates (would be replaced with real build integration)
pub fn simulate_progress_updates(progress_tx: Sender<String>) -> Result<()> {
    for i in 0..100 {
        progress_tx.send(format!("Processing dependency {}/100", i + 1))?;
        thread::sleep(Duration::from_millis(50));
    }
    Ok(())
}

/// Run real-time build monitoring
pub fn run_monitor(duration: Option<u64>, realtime: bool) -> Result<()> {
    info("🔍 Starting real-time build monitoring");
    
    let term = Term::stdout();
    let mut metrics = BuildMetrics::new();
    let mut running = true;
    let start_time = Instant::now();
    
    // Setup progress bars
    let main_progress = create_build_progress();
    let dependency_progress = create_dependency_progress(100);
    
    if realtime {
        term.clear_line()?;
        println!("{} Real-time Build Monitor {}\n", 
            style("".repeat(3)).green().bold(),
            style("".repeat(3)).green().bold()
        );
    }
    
    while running {
        // Update metrics (simulated)
        metrics.processed_dependencies = (metrics.processed_dependencies + 1) % 100;
        metrics.total_dependencies = 100;
        metrics.compilation_files = (metrics.compilation_files + 2) % 50;
        metrics.test_files = (metrics.test_files + 1) % 20;
        metrics.memory_usage_mb = 512 + (metrics.processed_dependencies as f64 * 0.1) as u64;
        metrics.cpu_usage_percent = (25.0 + (metrics.processed_dependencies as f64 * 0.5)) as f32;
        
        if realtime {
            display_monitor(&metrics, &start_time, realtime)?;
        }
        
        // Check if we should stop
        if let Some(duration_seconds) = duration {
            if start_time.elapsed().as_secs() >= duration_seconds {
                running = false;
            }
        } else if start_time.elapsed() > Duration::from_secs(30) {
            running = false;
        }
        
        thread::sleep(Duration::from_millis(200));
    }
    
    main_progress.finish();
    dependency_progress.finish();
    
    success("🎉 Monitoring session completed!");
    Ok(())
}

/// Display real-time monitor
pub fn display_monitor(metrics: &BuildMetrics, start_time: &Instant, _realtime: bool) -> Result<()> {
    let elapsed = start_time.elapsed();
    let elapsed_secs = elapsed.as_secs();
    let elapsed_mins = elapsed_secs / 60;
    let remaining_secs = elapsed_secs % 60;
    
    // Clear line and move cursor to beginning
    print!("\r");
    
    // Header
    print!("{} [{elapsed_mins:02}:{remaining_secs:02}] ", style("").green());
    
    // Progress bars in one line
    print!("Deps: {}/{} | ", metrics.processed_dependencies, metrics.total_dependencies);
    print!("Files: {}/{} | ", metrics.compilation_files, metrics.test_files);
    print!("Mem: {}MB | ", metrics.memory_usage_mb);
    print!("CPU: {:.1}%", metrics.cpu_usage_percent);
    
    std::io::Write::flush(&mut std::io::stdout())?;
    
    Ok(())
}

/// Run build profiling
pub fn run_profile(output: Option<std::path::PathBuf>, format: String) -> Result<()> {
    info("🔍 Starting build profiling");
    
    let start_time = Instant::now();
    let base_dir = std::env::current_dir()?;
    let build_system = BuildSystem::detect(&base_dir)
        .ok_or_else(|| anyhow::anyhow!("No build system detected"))?;
    
    // Execute build with timing
    let request = ExecutionRequest {
        base_directory: base_dir,
        goals: vec!["compile".to_string()],
        system_properties: std::collections::HashMap::new(),
        show_errors: true,
        offline: false,
    };
    
    let executor: Box<dyn BuildExecutor> = match build_system {
        BuildSystem::Maven => Box::new(MavenBuildExecutor::new()),
        BuildSystem::Gradle => Box::new(GradleExecutor::new()),
    };
    
    // TODO: Fix actual build execution
    // TODO: Implement actual build execution
    let _result = executor.execute(request);
    let build_time = start_time.elapsed();
    
    // Generate profile report
    generate_profile_report(build_time, &output, &format)?;
    
    // TODO: Implement actual result handling
    success("✅ Build profiling completed");
    
    Ok(())
}

/// Generate profile report
pub fn generate_profile_report(build_time: Duration, 
                         output: &Option<std::path::PathBuf>, 
                         format: &str) -> Result<()> {
    let report = ProfileReport {
        build_time,
        success: true, // TODO: Get from actual result
        error_count: 0, // TODO: Get from actual result
        phases: vec![
            ("Dependency Resolution".to_string(), Duration::from_millis(1500)),
            ("Compilation".to_string(), Duration::from_millis(3000)),
            ("Testing".to_string(), Duration::from_millis(2000)),
        ],
        timestamp: chrono::Local::now(),
    };
    
    match format {
        "json" => {
            let json = serde_json::to_string_pretty(&report)?;
            match output {
                Some(path) => std::fs::write(path, json)?,
                None => println!("{}", json),
            }
        }
        "markdown" => {
            let markdown = generate_markdown_report(&report);
            match output {
                Some(path) => std::fs::write(path, markdown)?,
                None => println!("{}", markdown),
            }
        }
        "text" => {
            let text = generate_text_report(&report);
            match output {
                Some(path) => std::fs::write(path, text)?,
                None => println!("{}", text),
            }
        }
        _ => {
            error(&format!("Unsupported format: {}", format));
        }
    }
    
    Ok(())
}

/// Profile report structure
#[derive(Debug, serde::Serialize)]
pub struct ProfileReport {
    pub build_time: Duration,
    pub success: bool,
    pub error_count: usize,
    pub phases: Vec<(String, Duration)>,
    pub timestamp: chrono::DateTime<chrono::Local>,
}

/// Generate markdown report
pub fn generate_markdown_report(report: &ProfileReport) -> String {
    let _total_phases = report.phases.len();
    format!(
        "# Build Profile Report\n\n\
        **Timestamp**: {}\n\n\
        ## Summary\n\n\
        - **Build Time**: {:.2}s\n\
        - **Status**: {}\n\
        - **Errors**: {}\n\n\
        ## Phase Timing\n\n\
        | Phase | Duration | Percentage |\n\
        |-------|----------|------------|\n\
        {}",
        report.timestamp.format("%Y-%m-%d %H:%M:%S"),
        report.build_time.as_secs_f64(),
        if report.success { "✅ Success" } else { "❌ Failed" },
        report.error_count,
        report.phases.iter().map(|(phase, duration)| {
            let percentage = (duration.as_millis() as f64 / report.build_time.as_millis() as f64) * 100.0;
            format!("| {} | {:.2}s | {:.1}% |", phase, duration.as_secs_f64(), percentage)
        }).collect::<Vec<_>>().join("\n")
    )
}

/// Generate text report
pub fn generate_text_report(report: &ProfileReport) -> String {
    let _total_phases = report.phases.len();
    let phase_width = report.phases.iter().map(|(p, _)| p.len()).max().unwrap_or(20);
    
    format!(
        "Build Profile Report\n\
        ===================\n\n\
        Timestamp: {}\n\
        Build Time: {:.2}s\n\
        Status: {}\n\
        Errors: {}\n\n\
        Phase Timing:\n\
        {}\n\
        Total: {:.2}s\n",
        report.timestamp.format("%Y-%m-%d %H:%M:%S"),
        report.build_time.as_secs_f64(),
        if report.success { "SUCCESS" } else { "FAILED" },
        report.error_count,
        report.phases.iter().map(|(phase, duration)| {
            let percentage = (duration.as_millis() as f64 / report.build_time.as_millis() as f64) * 100.0;
            format!("  {:<width$}: {:.2}s ({:.1}%)", phase, duration.as_secs_f64(), percentage, width = phase_width)
        }).collect::<Vec<_>>().join("\n"),
        report.build_time.as_secs_f64()
    )
}