logbrew-cli 0.1.27

Public command-line interface for LogBrew.
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
606
607
608
609
610
611
612
613
614
615
616
617
//! Local SDK setup planning.

use std::path::Path;

/// Maximum directory depth scanned for nearby project manifests.
const MAX_SCAN_DEPTH: usize = 3;
/// Maximum parent levels checked when setup is run from a project subdirectory.
const MAX_PARENT_SCAN_DEPTH: usize = 3;
/// Next step when setup finds a supported project.
const SDK_NEXT_STEP: &str = "install the matching LogBrew SDK package when packages are ready; \
                             send release and environment with logs, issues, actions, and traces";
/// Public Swift package URL used by a non-mutating install plan.
const SWIFT_PACKAGE_URL: &str = "https://github.com/LogBrewCo/sdk.git";
/// Public Swift package product consumed by application targets.
const SWIFT_PRODUCT: &str = "LogBrew";
/// Minimum public Swift package release required by this setup plan.
const SWIFT_MINIMUM_VERSION: &str = "0.1.6";
/// `SwiftPM` requirement that accepts compatible releases before version 1.0.0.
const SWIFT_VERSION_REQUIREMENT: &str = "up_to_next_major";
/// Next step when a public Swift package can be planned truthfully.
const SWIFT_NEXT_STEP: &str =
    "add the LogBrew Swift package from the install plan; no files were changed";
/// Next step when setup cannot find a supported project.
const EMPTY_NEXT_STEP: &str = "run logbrew setup from a project containing package.json, \
                               pyproject.toml, Pipfile, Cargo.toml, Package.swift, project.yml, \
                               project.yaml, .xcodeproj, .xcworkspace, go.mod, or composer.json.";

/// Writes the non-mutating setup plan.
pub(crate) fn write_setup_plan<W: std::io::Write>(
    root: Option<&Path>,
    auto: bool,
    yes: bool,
    json: bool,
    output: &mut W,
) -> Result<(), std::io::Error> {
    let root = root.unwrap_or_else(|| Path::new("."));
    let plan = SetupPlan::detect(root, auto, yes);

    if json {
        let dependency_declaration = swift_dependency_declaration();
        let detected = plan
            .detected
            .iter()
            .map(|detection| {
                serde_json::json!({
                    "runtime": detection.runtime,
                    "package_manager": detection.package_manager,
                    "manifest": detection.manifest,
                })
            })
            .collect::<Vec<_>>();
        let install_plan = plan.swift_install_ready().then(|| {
            serde_json::json!({
                "mode": "non_mutating",
                "ecosystem": "swiftpm",
                "package_url": SWIFT_PACKAGE_URL,
                "product": SWIFT_PRODUCT,
                "version": SWIFT_MINIMUM_VERSION,
                "version_requirement": {
                    "kind": SWIFT_VERSION_REQUIREMENT,
                    "minimum_version": SWIFT_MINIMUM_VERSION,
                },
                "dependency_declaration": dependency_declaration,
                "next_action": {
                    "code": "add_swift_package_dependency",
                    "target": "project_manifest",
                }
            })
        });
        let body = serde_json::json!({
            "ok": true,
            "auto": plan.auto,
            "yes": plan.yes,
            "install_ready": plan.swift_install_ready(),
            "install_plan": install_plan,
            "detected": detected,
            "next": plan.next_step(),
        });
        return writeln!(output, "{body}");
    }

    writeln!(output, "LogBrew setup plan")?;
    writeln!(output, "Mode: non-mutating plan")?;
    if plan.auto || plan.yes {
        writeln!(output, "Preferences: auto={}, yes={}", plan.auto, plan.yes)?;
    }
    writeln!(output, "No files changed.")?;
    if plan.swift_install_ready() {
        writeln!(output, "Install: ready")?;
        writeln!(output, "Package: {SWIFT_PACKAGE_URL}")?;
        writeln!(output, "Product: {SWIFT_PRODUCT}")?;
        writeln!(output, "Minimum version: {SWIFT_MINIMUM_VERSION}")?;
        writeln!(output, "Dependency: {}", swift_dependency_declaration())?;
    } else {
        writeln!(output, "Install: not ready")?;
    }
    if plan.detected.is_empty() {
        writeln!(output, "No supported project manifest found.")?;
    } else {
        writeln!(output, "Detected runtimes:")?;
        for detection in &plan.detected {
            writeln!(
                output,
                "- {} ({}) at {}",
                display_runtime(detection.runtime),
                detection.package_manager,
                detection.manifest
            )?;
        }
    }
    writeln!(output, "Next: {}", plan.next_step())
}

/// Builds the copyable `SwiftPM` dependency declaration from canonical fields.
fn swift_dependency_declaration() -> String {
    format!(r#".package(url: "{SWIFT_PACKAGE_URL}", from: "{SWIFT_MINIMUM_VERSION}")"#)
}

/// Non-mutating SDK setup plan.
#[derive(Debug, Clone, PartialEq, Eq)]
struct SetupPlan {
    /// Whether automatic setup was requested.
    auto: bool,
    /// Whether confirmation prompts should be skipped.
    yes: bool,
    /// Detected project manifests, at most one per runtime.
    detected: Vec<ProjectDetection>,
}

impl SetupPlan {
    /// Builds a setup plan by scanning the project root.
    fn detect(root: &Path, auto: bool, yes: bool) -> Self {
        Self {
            auto,
            yes,
            detected: detect_projects(root),
        }
    }

    /// Returns the setup follow-up step.
    fn next_step(&self) -> &'static str {
        if self.detected.is_empty() {
            EMPTY_NEXT_STEP
        } else if self.swift_install_ready() {
            SWIFT_NEXT_STEP
        } else {
            SDK_NEXT_STEP
        }
    }

    /// Returns whether detection supports the public non-mutating Swift plan.
    fn swift_install_ready(&self) -> bool {
        self.detected.iter().any(|detection| {
            matches!(
                detection.package_manager,
                "swift package manager" | "xcodegen"
            )
        })
    }
}

/// One detected project manifest.
#[derive(Debug, Clone, PartialEq, Eq)]
struct ProjectDetection {
    /// Stable runtime key.
    runtime: &'static str,
    /// Package manager or ecosystem used by the runtime.
    package_manager: &'static str,
    /// Manifest path relative to the scanned root.
    manifest: String,
}

/// Detects supported project manifests under a root.
fn detect_projects(root: &Path) -> Vec<ProjectDetection> {
    let mut detected = Vec::new();
    collect_manifests(root, root, 0, &mut detected);
    if detected.is_empty() {
        collect_parent_manifests(root, &mut detected);
    }
    detected.sort_by(|left, right| {
        manifest_depth(left.manifest.as_str())
            .cmp(&manifest_depth(right.manifest.as_str()))
            .then_with(|| left.runtime.cmp(right.runtime))
            .then_with(|| {
                manifest_priority(left.manifest.as_str())
                    .cmp(&manifest_priority(right.manifest.as_str()))
            })
            .then_with(|| left.manifest.cmp(&right.manifest))
    });
    dedupe_by_runtime(detected)
}

/// Collects project manifests from nearby parent directories.
fn collect_parent_manifests(root: &Path, detected: &mut Vec<ProjectDetection>) {
    let mut current = root;
    for _ in 0..MAX_PARENT_SCAN_DEPTH {
        let Some(parent) = current.parent() else {
            return;
        };
        collect_direct_manifests(root, parent, detected);
        if !detected.is_empty() {
            return;
        }
        current = parent;
    }
}

/// Collects supported manifest entries directly inside one directory.
fn collect_direct_manifests(root: &Path, directory: &Path, detected: &mut Vec<ProjectDetection>) {
    let Ok(entries) = std::fs::read_dir(directory) else {
        return;
    };

    for entry in entries {
        let Ok(entry) = entry else {
            continue;
        };
        if let Some(detection) = manifest_detection(root, entry.path().as_path()) {
            detected.push(detection);
        }
    }
}

/// Recursively collects supported manifests.
fn collect_manifests(
    root: &Path,
    directory: &Path,
    depth: usize,
    detected: &mut Vec<ProjectDetection>,
) {
    if depth > MAX_SCAN_DEPTH {
        return;
    }

    let Ok(entries) = std::fs::read_dir(directory) else {
        return;
    };

    for entry in entries {
        let Ok(entry) = entry else {
            continue;
        };
        let path = entry.path();
        let Ok(file_type) = entry.file_type() else {
            continue;
        };

        if let Some(detection) = manifest_detection(root, path.as_path()) {
            detected.push(detection);
            if file_type.is_dir() {
                continue;
            }
        }

        if file_type.is_dir() && depth < MAX_SCAN_DEPTH && !should_skip_dir(path.as_path()) {
            collect_manifests(root, path.as_path(), depth + 1, detected);
        }
    }
}

/// Builds a project manifest detection when a path is a supported manifest.
fn manifest_detection(root: &Path, path: &Path) -> Option<ProjectDetection> {
    let (runtime, package_manager) = manifest_runtime(path)?;
    Some(ProjectDetection {
        runtime,
        package_manager,
        manifest: relative_manifest(root, path),
    })
}

/// Returns whether a directory should be skipped during setup detection.
fn should_skip_dir(path: &Path) -> bool {
    path.file_name()
        .and_then(std::ffi::OsStr::to_str)
        .is_some_and(|name| {
            matches!(
                name,
                ".build"
                    | ".git"
                    | ".swiftpm"
                    | ".venv"
                    | "DerivedData"
                    | "node_modules"
                    | "target"
                    | "vendor"
                    | "venv"
            )
        })
}

/// Maps a manifest path to a runtime and package manager.
fn manifest_runtime(path: &Path) -> Option<(&'static str, &'static str)> {
    let file_name = path.file_name().and_then(std::ffi::OsStr::to_str)?;
    match file_name {
        "Cargo.toml" => Some(("rust", "cargo")),
        "Package.swift" => Some(("swift", "swift package manager")),
        "composer.json" => Some(("php", "composer")),
        "go.mod" => Some(("go", "go")),
        "package.json" => Some(("node", node_package_manager(path))),
        "Pipfile" => Some(("python", "pipenv")),
        "project.yml" | "project.yaml" => Some(("swift-ios", "xcodegen")),
        "pyproject.toml" => Some(("python", python_package_manager(path))),
        _ if file_name.ends_with(".xcodeproj") => Some(("swift-ios", "xcode")),
        _ if file_name.ends_with(".xcworkspace") => Some(("swift-ios", "xcode workspace")),
        _ => None,
    }
}

/// Detects the Node package manager from sibling lockfiles.
fn node_package_manager(package_json: &Path) -> &'static str {
    let Some(directory) = package_json.parent() else {
        return "npm";
    };
    if directory.join("pnpm-lock.yaml").exists() {
        "pnpm"
    } else if directory.join("yarn.lock").exists() {
        "yarn"
    } else if directory.join("bun.lockb").exists() || directory.join("bun.lock").exists() {
        "bun"
    } else {
        "npm"
    }
}

/// Detects the Python package manager from sibling lockfiles.
fn python_package_manager(pyproject: &Path) -> &'static str {
    let Some(directory) = pyproject.parent() else {
        return "pip";
    };
    if directory.join("uv.lock").exists() {
        "uv"
    } else if directory.join("poetry.lock").exists() {
        "poetry"
    } else if directory.join("Pipfile.lock").exists() || directory.join("Pipfile").exists() {
        "pipenv"
    } else {
        "pip"
    }
}

/// Returns a manifest path relative to the project root.
fn relative_manifest(root: &Path, path: &Path) -> String {
    if let Ok(relative) = path.strip_prefix(root) {
        return display_path(relative);
    }
    relative_path(root, path).unwrap_or_else(|| display_path(path))
}

/// Returns a portable display path with forward slashes.
fn display_path(path: &Path) -> String {
    path.to_string_lossy()
        .replace(std::path::MAIN_SEPARATOR, "/")
}

/// Builds a relative path from the setup directory to an ancestor manifest.
fn relative_path(root: &Path, path: &Path) -> Option<String> {
    let root_components = root.components().collect::<Vec<_>>();
    let path_components = path.components().collect::<Vec<_>>();
    let common = root_components
        .iter()
        .zip(path_components.iter())
        .take_while(|(left, right)| left == right)
        .count();
    if common == 0 {
        return None;
    }

    let mut parts = Vec::new();
    for _ in common..root_components.len() {
        parts.push(String::from(".."));
    }
    for component in &path_components[common..] {
        parts.push(component.as_os_str().to_string_lossy().into_owned());
    }

    if parts.is_empty() {
        Some(String::from("."))
    } else {
        Some(parts.join("/"))
    }
}

/// Returns an approximate path depth for nearest-manifest sorting.
fn manifest_depth(path: &str) -> usize {
    path.split('/').count()
}

/// Returns the source-of-truth preference when several manifests describe one runtime.
fn manifest_priority(path: &str) -> usize {
    if matches!(path, "project.yml" | "project.yaml")
        || path.ends_with("/project.yml")
        || path.ends_with("/project.yaml")
    {
        0
    } else if path.ends_with(".xcworkspace") {
        1
    } else if path.ends_with(".xcodeproj") {
        2
    } else {
        3
    }
}

/// Keeps the nearest manifest for each runtime.
fn dedupe_by_runtime(detected: Vec<ProjectDetection>) -> Vec<ProjectDetection> {
    let mut runtimes = Vec::new();
    let mut deduped = Vec::new();
    for detection in detected {
        if runtimes.contains(&detection.runtime) {
            continue;
        }
        runtimes.push(detection.runtime);
        deduped.push(detection);
    }
    deduped
}

/// Returns human-readable runtime names.
fn display_runtime(runtime: &str) -> &'static str {
    match runtime {
        "go" => "Go",
        "node" => "Node",
        "php" => "PHP",
        "python" => "Python",
        "rust" => "Rust",
        "swift" => "Swift",
        "swift-ios" => "Swift/iOS",
        _ => "Project",
    }
}

#[cfg(test)]
mod tests {
    use std::fs;
    use std::path::PathBuf;

    use super::{ProjectDetection, detect_projects};

    #[test]
    fn detects_nearest_manifest_per_runtime() -> Result<(), Box<dyn std::error::Error>> {
        let root = fixture("nearest")?;
        fs::write(root.join("Cargo.toml"), "")?;
        fs::create_dir_all(root.join("crates/logbrew"))?;
        fs::write(root.join("crates/logbrew/Cargo.toml"), "")?;
        fs::write(root.join("package.json"), "{}")?;

        let detected = detect_projects(root.as_path());

        assert_eq!(
            detected,
            vec![
                ProjectDetection {
                    runtime: "node",
                    package_manager: "npm",
                    manifest: String::from("package.json"),
                },
                ProjectDetection {
                    runtime: "rust",
                    package_manager: "cargo",
                    manifest: String::from("Cargo.toml"),
                },
            ]
        );
        Ok(())
    }

    #[test]
    fn detects_node_package_manager_from_lockfile() -> Result<(), Box<dyn std::error::Error>> {
        for (lockfile, package_manager) in [
            ("pnpm-lock.yaml", "pnpm"),
            ("yarn.lock", "yarn"),
            ("bun.lockb", "bun"),
            ("package-lock.json", "npm"),
        ] {
            let root = fixture(lockfile)?;
            fs::write(root.join("package.json"), "{}")?;
            fs::write(root.join(lockfile), "")?;

            let detected = detect_projects(root.as_path());

            assert_eq!(
                detected,
                vec![ProjectDetection {
                    runtime: "node",
                    package_manager,
                    manifest: String::from("package.json"),
                }]
            );
        }
        Ok(())
    }

    #[test]
    fn detects_python_package_manager_from_lockfile() -> Result<(), Box<dyn std::error::Error>> {
        for (lockfile, package_manager) in [
            ("uv.lock", "uv"),
            ("poetry.lock", "poetry"),
            ("Pipfile.lock", "pipenv"),
        ] {
            let root = fixture(lockfile)?;
            fs::write(root.join("pyproject.toml"), "")?;
            fs::write(root.join(lockfile), "")?;

            let detected = detect_projects(root.as_path());

            assert_eq!(
                detected,
                vec![ProjectDetection {
                    runtime: "python",
                    package_manager,
                    manifest: String::from("pyproject.toml"),
                }]
            );
        }
        Ok(())
    }

    #[test]
    fn detects_pipfile_as_python_project() -> Result<(), Box<dyn std::error::Error>> {
        let root = fixture("pipfile")?;
        fs::write(root.join("Pipfile"), "")?;

        let detected = detect_projects(root.as_path());

        assert_eq!(
            detected,
            vec![ProjectDetection {
                runtime: "python",
                package_manager: "pipenv",
                manifest: String::from("Pipfile"),
            }]
        );
        Ok(())
    }

    #[test]
    fn detects_xcodegen_ios_project_manifest() -> Result<(), Box<dyn std::error::Error>> {
        for manifest in ["project.yml", "project.yaml"] {
            let root = fixture(manifest)?;
            fs::write(root.join(manifest), "name: Checkout\n")?;

            let detected = detect_projects(root.as_path());

            assert_eq!(
                detected,
                vec![ProjectDetection {
                    runtime: "swift-ios",
                    package_manager: "xcodegen",
                    manifest: String::from(manifest),
                }]
            );
        }
        Ok(())
    }

    #[test]
    fn detects_xcode_project_directories() -> Result<(), Box<dyn std::error::Error>> {
        for (manifest, package_manager) in [
            ("Checkout.xcodeproj", "xcode"),
            ("Checkout.xcworkspace", "xcode workspace"),
        ] {
            let root = fixture(manifest)?;
            fs::create_dir_all(root.join(manifest))?;

            let detected = detect_projects(root.as_path());

            assert_eq!(
                detected,
                vec![ProjectDetection {
                    runtime: "swift-ios",
                    package_manager,
                    manifest: String::from(manifest),
                }]
            );
        }
        Ok(())
    }

    #[test]
    fn prefers_xcodegen_manifest_over_generated_xcode_containers()
    -> Result<(), Box<dyn std::error::Error>> {
        let root = fixture("xcodegen-preference")?;
        fs::write(root.join("project.yaml"), "name: Checkout\n")?;
        fs::create_dir_all(root.join("Checkout.xcodeproj"))?;
        fs::create_dir_all(root.join("Checkout.xcworkspace"))?;

        let detected = detect_projects(root.as_path());

        assert_eq!(
            detected,
            vec![ProjectDetection {
                runtime: "swift-ios",
                package_manager: "xcodegen",
                manifest: String::from("project.yaml"),
            }]
        );
        Ok(())
    }

    fn fixture(name: &str) -> Result<PathBuf, std::io::Error> {
        let root = std::env::temp_dir().join(format!(
            "logbrew-cli-setup-module-{name}-{}",
            std::process::id()
        ));
        remove_dir_if_exists(root.as_path())?;
        fs::create_dir_all(&root)?;
        Ok(root)
    }

    fn remove_dir_if_exists(path: &std::path::Path) -> Result<(), std::io::Error> {
        match fs::remove_dir_all(path) {
            Ok(()) => Ok(()),
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
            Err(error) => Err(error),
        }
    }
}