cargo-e 0.3.2

e is for Example. A command-line tool for running and exploring source, examples, and binaries from Rust projects. It will run the first example, if no options are given.
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
// src/e_discovery.rs
use std::{
    fs,
    fs::File,
    io::{self, BufRead, BufReader},
    path::{Path, PathBuf},
};

use crate::e_target::{CargoTarget, TargetKind};
use anyhow::{anyhow, Context, Result};

pub fn scan_tests_directory(manifest_path: &Path) -> Result<Vec<String>> {
    // Determine the project root from the manifest's parent directory.
    let project_root = manifest_path
        .parent()
        .ok_or_else(|| anyhow!("Unable to determine project root from manifest"))?;

    // Construct the path to the tests directory.
    let tests_dir = project_root.join("tests");
    let mut tests = Vec::new();

    // Only scan if the tests directory exists and is a directory.
    if tests_dir.exists() && tests_dir.is_dir() {
        for entry in fs::read_dir(tests_dir)? {
            let entry = entry?;
            let path = entry.path();
            // Only consider files with a `.rs` extension.
            if path.is_file() {
                if let Some(ext) = path.extension() {
                    if ext == "rs" {
                        if let Some(stem) = path.file_stem() {
                            tests.push(stem.to_string_lossy().to_string());
                        }
                    }
                }
            }
        }
    }

    Ok(tests)
}

pub fn scan_examples_directory(
    manifest_path: &Path,
    examples_folder: &str,
) -> Result<Vec<CargoTarget>> {
    // Determine the project root from the manifest's parent directory.
    let project_root = manifest_path
        .parent()
        .ok_or_else(|| anyhow::anyhow!("Unable to determine project root"))?;
    let examples_dir = project_root.join(examples_folder);
    let mut targets = Vec::new();

    if examples_dir.exists() && examples_dir.is_dir() {
        for entry in fs::read_dir(&examples_dir)
            .with_context(|| format!("Reading directory {:?}", examples_dir))?
        {
            let entry = entry?;
            let path = entry.path();
            if path.is_file() {
                // Assume that any .rs file in examples/ is an example.
                if let Some(ext) = path.extension() {
                    if ext == "rs" {
                        if let Some(stem) = path.file_stem() {
                            if let Some(target) = CargoTarget::from_source_file(
                                stem,
                                &path,
                                manifest_path,
                                true,
                                false,
                            ) {
                                targets.push(target);
                            }
                        }
                    }
                }
            } else if path.is_dir() {
                if let Some(target) = CargoTarget::from_folder(&path, &manifest_path, true, true) {
                    if target.kind == TargetKind::Unknown {
                        continue;
                    }
                    targets.push(target);
                }
            }
        }
    }

    Ok(targets)
}

/// Try to detect a “script” kind by reading *one* first line.
/// Returns Ok(Some(...)) if it matches either marker, Ok(None) otherwise.
/// Any I/O error is propagated.
fn detect_script_kind(path: &Path) -> io::Result<Option<TargetKind>> {
    let file = File::open(path)?;
    let mut reader = BufReader::new(file);
    let mut first_line = String::new();
    reader.read_line(&mut first_line)?;

    // must start with `#`
    if !first_line.starts_with('#') {
        return Ok(None);
    }
    // now check your two markers
    if first_line.contains("scriptisto") {
        return Ok(Some(TargetKind::ScriptScriptisto));
    }
    if first_line.contains("rust-script") {
        return Ok(Some(TargetKind::ScriptRustScript));
    }
    Ok(None)
}

/// Determines the target kind and (optionally) an updated manifest path based on:
/// - Tauri configuration: If the parent directory of the original manifest contains a
///   "tauri.conf.json", and also a Cargo.toml exists in that same directory, then update the manifest path
///   and return ManifestTauri.
/// - Dioxus markers: If the file contents contain any Dioxus markers, return either ManifestDioxusExample
///   (if `example` is true) or ManifestDioxus.
/// - Otherwise, if the file contains "fn main", decide based on the candidate's parent folder name.
///   If the parent is "examples" (or "bin"), return the corresponding Example/Binary (or extended variant).
/// - If none of these conditions match, return Example as a fallback.
///
/// Returns a tuple of (TargetKind, updated_manifest_path).
pub fn determine_target_kind_and_manifest(
    manifest_path: &Path,
    candidate: &Path,
    file_contents: &str,
    example: bool,
    extended: bool,
    _toml_specified: bool,
    incoming_kind: Option<TargetKind>,
) -> (TargetKind, PathBuf) {
    // Start with the original manifest path.
    let mut new_manifest = manifest_path.to_path_buf();

    if let Ok(Some(script_kind)) = detect_script_kind(candidate) {
        return (script_kind, new_manifest);
    }
    // If the incoming kind is already known (Test or Bench), return it.
    if let Some(kind) = incoming_kind {
        if kind == TargetKind::Test || kind == TargetKind::Bench {
            return (kind, new_manifest);
        }
    }
    // Tauri detection: check if the manifest's parent or candidate's parent contains tauri config.
    let tauri_detected = manifest_path
        .parent()
        .and_then(|p| p.file_name())
        .map(|s| s.to_string_lossy().eq_ignore_ascii_case("src-tauri"))
        .unwrap_or(false)
        || manifest_path
            .parent()
            .map(|p| p.join("tauri.conf.json"))
            .map_or(false, |p| p.exists())
        || manifest_path
            .parent()
            .map(|p| p.join("src-tauri"))
            .map_or(false, |p| p.exists())
        || candidate
            .parent()
            .map(|p| p.join("tauri.conf.json"))
            .map_or(false, |p| p.exists());

    // println!(
    //     "{} {} {} {}",
    //     manifest_path.display(),
    //     candidate.display(),
    //     tauri_detected,
    //     toml_specified
    // );
    if tauri_detected {
        if example {
            return (TargetKind::ManifestTauriExample, new_manifest);
        }
        // If the candidate's parent contains tauri.conf.json, update the manifest path if there's a Cargo.toml there.
        if let Some(candidate_parent) = candidate.parent() {
            let candidate_manifest = candidate_parent.join("Cargo.toml");
            if candidate_manifest.exists() {
                new_manifest = candidate_manifest;
            }
        }
        return (TargetKind::ManifestTauri, new_manifest);
    }

    // Dioxus detection
    if file_contents.contains("dioxus::") {
        let kind = if example {
            TargetKind::ManifestDioxusExample
        } else {
            TargetKind::ManifestDioxus
        };
        return (kind, new_manifest);
    }

    // leptos detection
    if file_contents.contains("leptos::") {
        return (TargetKind::ManifestLeptos, new_manifest);
    }

    // Check if the file contains "fn main"
    if file_contents.contains("fn main") {
        let kind = if example {
            if extended {
                TargetKind::ExtendedExample
            } else {
                TargetKind::Example
            }
        } else if extended {
            TargetKind::ExtendedBinary
        } else {
            TargetKind::Binary
        };
        return (kind, new_manifest);
    }
    // Check if the file contains a #[test] attribute; if so, mark it as a test.
    if file_contents.contains("#[test]") {
        return (TargetKind::Test, new_manifest);
    }

    let kind = if example {
        if extended {
            TargetKind::UnknownExtendedExample
        } else {
            TargetKind::UnknownExample
        }
    } else if extended {
        TargetKind::UnknownExtendedBinary
    } else {
        TargetKind::UnknownBinary
    };
    (kind, new_manifest)
    // Default fallback.
    // (TargetKind::Unknown, "errorNOfnMAIN".into())
}

/// Returns true if the candidate file is not located directly in the project root.
pub fn is_extended_target(manifest_path: &Path, candidate: &Path) -> bool {
    if let Some(project_root) = manifest_path.parent() {
        // If the candidate's parent is not the project root, it's nested (i.e. extended).
        candidate
            .parent()
            .map(|p| p != project_root)
            .unwrap_or(false)
    } else {
        false
    }
}

// #[cfg(test)]
// mod tests {
//     use super::*;
//     use std::fs;
//     use tempfile::tempdir;

//     #[test]
//     fn test_discover_targets_no_manifest() {
//         let temp = tempdir().unwrap();
//         // With no Cargo.toml, we expect an empty list.
//         let targets = discover_targets(temp.path()).unwrap();
//         assert!(targets.is_empty());
//     }

//     #[test]
//     fn test_discover_targets_with_manifest_and_example() {
//         let temp = tempdir().unwrap();
//         // Create a dummy Cargo.toml.
//         let manifest_path = temp.path().join("Cargo.toml");
//         fs::write(&manifest_path, "[package]\nname = \"dummy\"\n").unwrap();

//         // Create an examples directory with a dummy example file.
//         let examples_dir = temp.path().join("examples");
//         fs::create_dir(&examples_dir).unwrap();
//         let example_file = examples_dir.join("example1.rs");
//         fs::write(&example_file, "fn main() {}").unwrap();

//         let targets = discover_targets(temp.path()).unwrap();
//         // Expect at least two targets: one for the manifest and one for the example.
//         assert!(targets.len() >= 2);

//         let example_target = targets
//             .iter()
//             .find(|t| t.kind == TargetKind::Example && t.name == "example1");
//         assert!(example_target.is_some());
//     }
// }

pub fn scan_directory_for_targets(scan_dir: &Path, be_silent: bool) -> Vec<CargoTarget> {
    let mut targets = Vec::new();
    let mut dirs_to_visit = vec![scan_dir.to_path_buf()]; // Use a stack for iterative traversal

    // Collect all manifest paths found in the directory tree
    let mut manifest_paths = Vec::new();

    while let Some(current_dir) = dirs_to_visit.pop() {
        if let Ok(entries) = fs::read_dir(&current_dir) {
            for entry in entries.flatten() {
                let path = entry.path();
                if path.is_dir() {
                    // // Skip directories that contain ".." or the system separator in their path
                    // if path.to_string_lossy().contains(&format!("..{}", std::path::MAIN_SEPARATOR)) {
                    //     if let Ok(current_dir) = std::env::current_dir() {
                    //         // Avoid infinite recursion if the scan_dir is the current working directory
                    //         println!(
                    //             "DEBUG: scan_dir = {}, current_dir = {}, path = {}",
                    //             scan_dir.display(),
                    //             current_dir.display(),
                    //             path.display()
                    //         );
                    //         // and we're traversing into it again (e.g., via symlink or path confusion)
                    //         if path == current_dir {
                    //             continue;
                    //         }
                    //     }
                    // }
                    // Skip irrelevant directories
                    if path.file_name().map_or(false, |name| {
                        name == "node_modules" || name == "target" || name == "build"
                    }) {
                        continue;
                    }
                    dirs_to_visit.push(path); // Add subdirectory to stack
                } else if path.file_name().map_or(false, |name| name == "Cargo.toml") {
                    manifest_paths.push(Some(path));
                }
            }
        } else if !be_silent {
            eprintln!("Failed to read directory: {}", current_dir.display());
        }
    }
    // Print the manifest paths and wait for 5 seconds
    if !be_silent {
        for manifest in &manifest_paths {
            if let Some(path) = manifest {
                println!("Found Cargo.toml at: {}", path.display());
            }
        }
    }
    // Now call the parallel collector if any manifests were found
    if !manifest_paths.is_empty() {
        #[cfg(feature = "concurrent")]
        {
            let file_targets = crate::e_collect::collect_all_targets_parallel(
                manifest_paths,
                false, // workspace
                std::thread::available_parallelism()
                    .map(|n| n.get())
                    .unwrap_or(4),
                be_silent,
            )
            .unwrap_or_default();

            if !be_silent {
                println!(
                    "Found {} targets in scanned directories",
                    file_targets.len()
                );
            }
            targets.extend(file_targets);
        }
        #[cfg(not(feature = "concurrent"))]
        {
            for manifest in manifest_paths {
                if let Some(path) = manifest {
                    match crate::e_collect::collect_all_targets(
                        Some(path.clone()),
                        false, // workspace
                        std::thread::available_parallelism()
                            .map(|n| n.get())
                            .unwrap_or(4),
                        false, // be_silent
                        false, // print_parent
                    ) {
                        Ok(file_targets) => {
                            if !be_silent {
                                println!(
                                    "Found {} targets in {}",
                                    file_targets.len(),
                                    path.display()
                                );
                            }
                            targets.extend(file_targets);
                        }
                        Err(e) => {
                            eprintln!("Error processing {}: {}", path.display(), e);
                        }
                    }
                }
            }
        }
    }

    targets
}
//                     dirs_to_visit.push(path); // Add subdirectory to stack
//                 } else if path.file_name().map_or(false, |name| name == "Cargo.toml") {
//                     if !be_silent {
//                       println!("Found Cargo.toml at: {}", path.display());
//                     }
//                     match crate::e_collect::collect_all_targets(
//                         Some(path.clone()),
//                         false,
//                         std::thread::available_parallelism().map(|n| n.get()).unwrap_or(4),
//                         false,
//                     ) {
//                         Ok(file_targets) => {
//                             if !be_silent {
//                             println!(
//                                 "Found {} targets in {}",
//                                 file_targets.len(),
//                                 path.display()
//                             );
//                             }
//                             targets.extend(file_targets);
//                         }
//                         Err(e) => {
//                             eprintln!("Error processing {}: {}", path.display(), e);
//                         }
//                     }
//                 }
//             }
//         } else {
//             eprintln!("Failed to read directory: {}", current_dir.display());
//         }
//     }

//     targets

// }