xbp 10.5.0

XBP is a zero-config build pack that can also interact with proxies, kafka, sockets, synthetic monitors.
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
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
//! Project type detection module
//!
//! This module analyzes project directories to determine the type of application
//! and extract relevant configuration information.

use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::fs;
use std::path::Path;

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ProjectType {
    Docker {
        has_dockerfile: bool,
    },
    DockerCompose {
        compose_files: Vec<String>,
        detected_ports: Vec<u16>,
    },
    Railway {
        has_railway_json: bool,
        has_railway_toml: bool,
    },
    Python {
        has_requirements_txt: bool,
        has_pyproject_toml: bool,
    },
    OpenApi {
        spec_files: Vec<String>,
    },
    Terraform {
        tf_file_count: usize,
    },
    NextJs {
        package_json: PackageJsonInfo,
        has_next_config: bool,
    },
    NodeJs {
        package_json: PackageJsonInfo,
    },
    Rust {
        cargo_toml: CargoTomlInfo,
    },
    Unknown,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PackageJsonInfo {
    pub name: String,
    pub version: String,
    pub scripts: std::collections::HashMap<String, String>,
    pub dependencies: std::collections::HashMap<String, String>,
    pub dev_dependencies: std::collections::HashMap<String, String>,
    pub main: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CargoTomlInfo {
    pub name: String,
    pub version: String,
    pub description: Option<String>,
    pub authors: Vec<String>,
    pub edition: Option<String>,
}

pub struct ProjectDetector;

impl ProjectDetector {
    /// Detect the project type by analyzing the directory structure and configuration files
    pub async fn detect_project_type(project_path: &Path) -> Result<ProjectType, String> {
        let project_path = project_path
            .canonicalize()
            .map_err(|e| format!("Failed to resolve project path: {}", e))?;

        if let Ok(project_type) = Self::detect_docker_compose(&project_path).await {
            return Ok(project_type);
        }

        if let Ok(project_type) = Self::detect_docker(&project_path).await {
            return Ok(project_type);
        }

        if let Ok(project_type) = Self::detect_railway(&project_path).await {
            return Ok(project_type);
        }

        if let Ok(project_type) = Self::detect_python(&project_path).await {
            return Ok(project_type);
        }

        // Check for Next.js project
        if let Ok(project_type) = Self::detect_nextjs(&project_path).await {
            return Ok(project_type);
        }

        // Check for Node.js project
        if let Ok(project_type) = Self::detect_nodejs(&project_path).await {
            return Ok(project_type);
        }

        // Check for Rust project
        if let Ok(project_type) = Self::detect_rust(&project_path).await {
            return Ok(project_type);
        }

        if let Ok(project_type) = Self::detect_openapi(&project_path).await {
            return Ok(project_type);
        }

        if let Ok(project_type) = Self::detect_terraform(&project_path).await {
            return Ok(project_type);
        }

        Ok(ProjectType::Unknown)
    }

    pub fn detect_provider_manifests(project_path: &Path) -> Vec<String> {
        let mut detections = Vec::new();

        if project_path.join("Dockerfile").exists() {
            detections.push("Dockerfile".to_string());
        }

        for name in [
            "docker-compose.yml",
            "docker-compose.yaml",
            "compose.yml",
            "compose.yaml",
        ] {
            if project_path.join(name).exists() {
                detections.push(name.to_string());
            }
        }

        if project_path.join("railway.json").exists() {
            detections.push("railway.json".to_string());
        }
        if project_path.join("railway.toml").exists() {
            detections.push("railway.toml".to_string());
        }

        if project_path.join("requirements.txt").exists() {
            detections.push("requirements.txt".to_string());
        }
        if project_path.join("pyproject.toml").exists() {
            detections.push("pyproject.toml".to_string());
        }

        for name in [
            "openapi.yaml",
            "openapi.yml",
            "swagger.yaml",
            "swagger.yml",
            "swagger.json",
        ] {
            if project_path.join(name).exists() {
                detections.push(name.to_string());
            }
        }

        let tf_count = match fs::read_dir(project_path) {
            Ok(entries) => entries
                .filter_map(|e| e.ok())
                .filter(|e| {
                    e.path()
                        .extension()
                        .and_then(|s| s.to_str())
                        .map(|ext| ext.eq_ignore_ascii_case("tf"))
                        .unwrap_or(false)
                })
                .count(),
            Err(_) => 0,
        };
        if tf_count > 0 {
            detections.push(format!("Terraform (.tf) x{}", tf_count));
        }

        detections
    }

    async fn detect_docker_compose(project_path: &Path) -> Result<ProjectType, String> {
        let compose_names = [
            "docker-compose.yml",
            "docker-compose.yaml",
            "compose.yml",
            "compose.yaml",
        ];

        let mut compose_files = Vec::new();
        for name in compose_names {
            if project_path.join(name).exists() {
                compose_files.push(name.to_string());
            }
        }

        if compose_files.is_empty() {
            return Err("No compose file found".to_string());
        }

        let mut detected_ports: Vec<u16> = Vec::new();
        for file in &compose_files {
            let path = project_path.join(file);
            if let Ok(contents) = fs::read_to_string(&path) {
                if let Ok(value) = serde_yaml::from_str::<serde_yaml::Value>(&contents) {
                    if let Some(services) = value.get("services").and_then(|v| v.as_mapping()) {
                        for (_svc_name, svc_cfg) in services.iter() {
                            let ports = svc_cfg
                                .get("ports")
                                .and_then(|v| v.as_sequence())
                                .cloned()
                                .unwrap_or_default();
                            for p in ports {
                                if let Some(s) = p.as_str() {
                                    if let Some(host) = s.split(':').next() {
                                        if let Ok(port) = host.parse::<u16>() {
                                            detected_ports.push(port);
                                        }
                                    }
                                } else if let Some(n) = p.as_i64() {
                                    if n >= 1 && n <= u16::MAX as i64 {
                                        detected_ports.push(n as u16);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        detected_ports.sort_unstable();
        detected_ports.dedup();

        Ok(ProjectType::DockerCompose {
            compose_files,
            detected_ports,
        })
    }

    async fn detect_docker(project_path: &Path) -> Result<ProjectType, String> {
        let dockerfile = project_path.join("Dockerfile");
        if !dockerfile.exists() {
            return Err("No Dockerfile found".to_string());
        }
        Ok(ProjectType::Docker {
            has_dockerfile: true,
        })
    }

    async fn detect_railway(project_path: &Path) -> Result<ProjectType, String> {
        let has_railway_json = project_path.join("railway.json").exists();
        let has_railway_toml = project_path.join("railway.toml").exists();
        if !has_railway_json && !has_railway_toml {
            return Err("No railway manifest found".to_string());
        }
        Ok(ProjectType::Railway {
            has_railway_json,
            has_railway_toml,
        })
    }

    async fn detect_python(project_path: &Path) -> Result<ProjectType, String> {
        let has_requirements_txt = project_path.join("requirements.txt").exists();
        let has_pyproject_toml = project_path.join("pyproject.toml").exists();
        if !has_requirements_txt && !has_pyproject_toml {
            return Err("No python manifest found".to_string());
        }
        Ok(ProjectType::Python {
            has_requirements_txt,
            has_pyproject_toml,
        })
    }

    async fn detect_openapi(project_path: &Path) -> Result<ProjectType, String> {
        let names = [
            "openapi.yaml",
            "openapi.yml",
            "swagger.yaml",
            "swagger.yml",
            "swagger.json",
        ];
        let mut spec_files = Vec::new();
        for name in names {
            if project_path.join(name).exists() {
                spec_files.push(name.to_string());
            }
        }
        if spec_files.is_empty() {
            return Err("No OpenAPI spec found".to_string());
        }
        Ok(ProjectType::OpenApi { spec_files })
    }

    async fn detect_terraform(project_path: &Path) -> Result<ProjectType, String> {
        let tf_count = fs::read_dir(project_path)
            .map_err(|_| "Failed to read directory".to_string())?
            .filter_map(|e| e.ok())
            .filter(|e| {
                e.path()
                    .extension()
                    .and_then(|s| s.to_str())
                    .map(|ext| ext.eq_ignore_ascii_case("tf"))
                    .unwrap_or(false)
            })
            .count();
        if tf_count == 0 {
            return Err("No terraform files found".to_string());
        }
        Ok(ProjectType::Terraform {
            tf_file_count: tf_count,
        })
    }

    /// Detect Next.js project by looking for .next folder and next.js dependencies
    async fn detect_nextjs(project_path: &Path) -> Result<ProjectType, String> {
        let package_json_path = project_path.join("package.json");
        let next_config_path = project_path.join("next.config.js");
        let next_config_mjs_path = project_path.join("next.config.mjs");
        let next_dir = project_path.join(".next");

        if !package_json_path.exists() {
            return Err("No package.json found".to_string());
        }

        let package_json_info = Self::parse_package_json(&package_json_path)?;

        // Check if Next.js is in dependencies
        let has_next = package_json_info.dependencies.contains_key("next")
            || package_json_info.dev_dependencies.contains_key("next");

        if !has_next {
            return Err("Next.js not found in dependencies".to_string());
        }

        let has_next_config =
            next_config_path.exists() || next_config_mjs_path.exists() || next_dir.exists();

        Ok(ProjectType::NextJs {
            package_json: package_json_info,
            has_next_config,
        })
    }

    /// Detect Node.js project by looking for package.json
    async fn detect_nodejs(project_path: &Path) -> Result<ProjectType, String> {
        let package_json_path = project_path.join("package.json");

        if !package_json_path.exists() {
            return Err("No package.json found".to_string());
        }

        let package_json_info = Self::parse_package_json(&package_json_path)?;

        Ok(ProjectType::NodeJs {
            package_json: package_json_info,
        })
    }

    /// Detect Rust project by looking for Cargo.toml
    async fn detect_rust(project_path: &Path) -> Result<ProjectType, String> {
        let cargo_toml_path = project_path.join("Cargo.toml");

        if !cargo_toml_path.exists() {
            return Err("No Cargo.toml found".to_string());
        }

        let cargo_toml_info = Self::parse_cargo_toml(&cargo_toml_path)?;

        Ok(ProjectType::Rust {
            cargo_toml: cargo_toml_info,
        })
    }

    /// Parse package.json file and extract relevant information
    fn parse_package_json(path: &Path) -> Result<PackageJsonInfo, String> {
        let content =
            fs::read_to_string(path).map_err(|e| format!("Failed to read package.json: {}", e))?;

        let json: Value = serde_json::from_str(&content)
            .map_err(|e| format!("Failed to parse package.json: {}", e))?;

        let name = json["name"].as_str().unwrap_or("unknown").to_string();

        let version = json["version"].as_str().unwrap_or("0.0.0").to_string();

        let scripts = json["scripts"]
            .as_object()
            .map(|obj| {
                obj.iter()
                    .filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())))
                    .collect()
            })
            .unwrap_or_default();

        let dependencies = json["dependencies"]
            .as_object()
            .map(|obj| {
                obj.iter()
                    .filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())))
                    .collect()
            })
            .unwrap_or_default();

        let dev_dependencies = json["devDependencies"]
            .as_object()
            .map(|obj| {
                obj.iter()
                    .filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())))
                    .collect()
            })
            .unwrap_or_default();

        let main = json["main"].as_str().map(|s| s.to_string());

        Ok(PackageJsonInfo {
            name,
            version,
            scripts,
            dependencies,
            dev_dependencies,
            main,
        })
    }

    /// Parse Cargo.toml file and extract relevant information
    fn parse_cargo_toml(path: &Path) -> Result<CargoTomlInfo, String> {
        let content =
            fs::read_to_string(path).map_err(|e| format!("Failed to read Cargo.toml: {}", e))?;

        let toml_value: toml::Value =
            toml::from_str(&content).map_err(|e| format!("Failed to parse Cargo.toml: {}", e))?;

        let package = toml_value
            .get("package")
            .ok_or("No [package] section found in Cargo.toml")?;

        let name = package
            .get("name")
            .and_then(|v| v.as_str())
            .ok_or("No name found in [package] section")?
            .to_string();

        let version = package
            .get("version")
            .and_then(|v| v.as_str())
            .unwrap_or("0.0.0")
            .to_string();

        let description = package
            .get("description")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());

        let authors = package
            .get("authors")
            .and_then(|v| v.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|v| v.as_str())
                    .map(|s| s.to_string())
                    .collect()
            })
            .unwrap_or_default();

        let edition = package
            .get("edition")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());

        Ok(CargoTomlInfo {
            name,
            version,
            description,
            authors,
            edition,
        })
    }

    /// Get recommended deployment configuration based on project type
    pub fn get_deployment_recommendations(project_type: &ProjectType) -> DeploymentRecommendations {
        match project_type {
            ProjectType::DockerCompose { detected_ports, .. } => DeploymentRecommendations {
                build_command: Some("docker compose build".to_string()),
                start_command: Some("docker compose up -d".to_string()),
                install_command: None,
                default_port: detected_ports.first().copied().unwrap_or(80),
                process_name: None,
                requires_build: true,
            },
            ProjectType::Docker { .. } => DeploymentRecommendations {
                build_command: Some("docker build -t <image-name> .".to_string()),
                start_command: Some(
                    "docker run -p <host-port>:<container-port> <image-name>".to_string(),
                ),
                install_command: None,
                default_port: 80,
                process_name: None,
                requires_build: true,
            },
            ProjectType::Railway { .. } => DeploymentRecommendations {
                build_command: None,
                start_command: None,
                install_command: None,
                default_port: 8080,
                process_name: None,
                requires_build: false,
            },
            ProjectType::Python {
                has_requirements_txt,
                has_pyproject_toml,
            } => {
                let install_command = if *has_requirements_txt {
                    Some("pip install -r requirements.txt".to_string())
                } else if *has_pyproject_toml {
                    Some("pip install -e .".to_string())
                } else {
                    None
                };
                DeploymentRecommendations {
                    build_command: None,
                    start_command: None,
                    install_command,
                    default_port: 8000,
                    process_name: None,
                    requires_build: false,
                }
            }
            ProjectType::OpenApi { .. } => DeploymentRecommendations {
                build_command: None,
                start_command: None,
                install_command: None,
                default_port: 8080,
                process_name: None,
                requires_build: false,
            },
            ProjectType::Terraform { .. } => DeploymentRecommendations {
                build_command: None,
                start_command: None,
                install_command: None,
                default_port: 8080,
                process_name: None,
                requires_build: false,
            },
            ProjectType::NextJs { package_json, .. } => DeploymentRecommendations {
                build_command: Some("pnpm run build".to_string()),
                start_command: Some("pnpm run start".to_string()),
                install_command: Some("pnpm install".to_string()),
                default_port: 3000,
                process_name: Some(package_json.name.clone()),
                requires_build: true,
            },
            ProjectType::NodeJs { package_json } => {
                let start_cmd = package_json
                    .scripts
                    .get("start")
                    .map(|s| {
                        format!(
                            "pnpm run {}",
                            s.split_whitespace().next().unwrap_or("start")
                        )
                    })
                    .or_else(|| package_json.main.as_ref().map(|m| format!("node {}", m)))
                    .unwrap_or_else(|| "pnpm run start".to_string());

                DeploymentRecommendations {
                    build_command: package_json
                        .scripts
                        .get("build")
                        .map(|_| "pnpm run build".to_string()),
                    start_command: Some(start_cmd),
                    install_command: Some("pnpm install".to_string()),
                    default_port: 3000,
                    process_name: Some(package_json.name.clone()),
                    requires_build: package_json.scripts.contains_key("build"),
                }
            }
            ProjectType::Rust { cargo_toml } => DeploymentRecommendations {
                build_command: Some("cargo build --release".to_string()),
                start_command: Some(format!("./target/release/{}", cargo_toml.name)),
                install_command: None,
                default_port: 8080,
                process_name: Some(cargo_toml.name.clone()),
                requires_build: true,
            },
            ProjectType::Unknown => DeploymentRecommendations {
                build_command: None,
                start_command: None,
                install_command: None,
                default_port: 8080,
                process_name: None,
                requires_build: false,
            },
        }
    }
}

#[derive(Debug, Clone)]
pub struct DeploymentRecommendations {
    pub build_command: Option<String>,
    pub start_command: Option<String>,
    pub install_command: Option<String>,
    pub default_port: u16,
    pub process_name: Option<String>,
    pub requires_build: bool,
}