Skip to content

cargo run --example completions break with nested example directories #8429

Closed

Description

@ian-h-chamberlain
$ fish --version 
fish, version 3.3.1

$ echo $version 
3.3.1

Cargo completions for --example seem to be a little off when there are subdirectories in the examples directory of a cargo project.

Example, running in a local checkout of this repository: https://github.com/bevyengine/bevy

$ cargo run --example # <tab>
2d       asset        game         reflection  ui    
3d       audio        hello_world  scene       wasm  
android  diagnostics  input        shader      window
app      ecs          ios          tools      

Expected result would include z_sort_debug, 3d_scene, and many more.
Directory names do not necessarily correlate to actual runnable example names, and file names do not necessarily correspond to example names, although they usually do by convention.

The problem seems to be in this function in cargo.fish:

function __list_cargo_examples
    if not test -d ./examples
        return
    end

    find ./examples -mindepth 1 -maxdepth 1 -type f -name "*.rs" -or -type d \
        | string replace -r './examples/(.*?)(?:.rs)?$' '$1'
end

I'm not sure exactly why the original implementation had -maxdepth 1 or -type d.

There are two options as far as I can tell, one would be to run cargo itself to list the examples, as a quick hack something like this seems to work pretty well:

cargo run --example 2>&1 | tail -n+3 | string trim

Alternately, more of a heuristic would be to modify the find command to be more robust, something like:

find ./examples -mindepth 1 -type f -name "*.rs" -exec basename '{}' \; | string replace '.rs' ''

I can open a PR for one or the other approach, depending on what seems preferable. The first approach is probably more likely to be correct, but could break depending on implementation changes in cargo, the second may be incorrect depending on a given project's structure, but probably matches convention fairly well.

Activity

  1. krobelus commented on Nov 11, 2021

    @krobelus
    Contributor

    Commit 0d3f4db ([cargo] Use filesystem for --example completions) gives the reason why we don't parse cargo run --example

    cargo run --example no longer lists examples and never listed examples that were not built.

    Reading https://doc.rust-lang.org/cargo/reference/cargo-targets.html#examples
    I found https://doc.rust-lang.org/cargo/guide/project-layout.html
    which suggests that only top-level directories are valid as examples. It's not explicit though.

    checking the cargo sources indicates that they only read examples/*, not any deeper

    fn clean_examples(
        features: &Features,
        toml_examples: Option<&Vec<TomlExampleTarget>>,
        package_root: &Path,
        edition: Edition,
        autodiscover: Option<bool>,
        warnings: &mut Vec<String>,
        errors: &mut Vec<String>,
    ) -> CargoResult<Vec<Target>> {
        let inferred = infer_from_directory(&package_root.join("examples"));
        ...
    }
    
    fn infer_from_directory(directory: &Path) -> Vec<(String, PathBuf)> {
        let entries = match fs::read_dir(directory) {
            Err(_) => return Vec::new(),
            Ok(dir) => dir,
        };
    
        entries
            .filter_map(|e| e.ok())
            .filter(is_not_dotfile)
            .filter_map(|d| infer_any(&d))
            .collect()
    }

    are you sure that cargo run --example 3d_scene works?

  2. ian-h-chamberlain commented on Nov 11, 2021

    @ian-h-chamberlain
    ContributorAuthor

    Ok, I looked a bit more, and it seems like the answer is that Cargo finds both top-level *.rs examples in the directory, and [[example]]s specified in Cargo.toml, as of the 2018 edition: https://doc.rust-lang.org/cargo/reference/cargo-targets.html#target-auto-discovery

    Edit: actually, I think there are three possibilities that are allowed, re-reading the docs: explicit [[example]] in Cargo.toml, examples/single_file.rs, and examples/multi_file/main.rs.

    I'm a little bit confused by the reason given in that commit,

    cargo run --example no longer lists examples and never listed examples that were not built.

    It appears that cargo actually gained that behavior as of this PR in 2019, rust-lang/cargo#6505 so I'm wondering if there was a regression at some point?

    On my macOS machine, this is what I see:

    $ cargo --version 
    cargo 1.56.0 (4ed5d137b 2021-10-04)
    
    $ cargo run --example 
    error: "--example" takes one argument.
    Available examples:
        3d_scene
        alien_cake_addict
        android
        array_texture
        asset_loading
    #...

    I verified as well that actually running the examples works, since they are listed as [[example]] in the manifest (e.g. https://github.com/bevyengine/bevy/blob/main/Cargo.toml#L133).

    The file-based heuristic is fine for many cases, I think, but it seems like the only truly correct way to enumerate examples would be to trust Cargo, or basically duplicate its features (parse Cargo.toml, look for files, etc.).

  3. krobelus commented on Nov 11, 2021

    @krobelus
    Contributor

    It appears that cargo actually gained that behavior as of this PR in 2019, rust-lang/cargo#6505 so I'm wondering if there was a regression at some point?

    Right, looks like cargo run --example now does list all examples!

    Ah I forgot about the [[examples]] from Cargo.toml (and was on rust 1.54 so bevy didn't work when I tried, fixed now with 1.56).
    We could write a small Python (?) snippet that pulls the [[examples]] out of Cargo.toml.
    This might prove tricky though, because we don't want to list library examples.
    Maybe that's easy to fix, but it feels more stable to parse the error output of cargo run --example.

  4. ian-h-chamberlain commented on Nov 12, 2021

    @ian-h-chamberlain
    ContributorAuthor

    Sounds good to me – I have a local version that seems be working for me, would you like me to open a PR to switch to using cargo run --example?

    Right now it's using tail but looks like it would be preferable not to for #6520 so I will see if I can fishify it before submitting a PR.

  5. krobelus commented on Nov 12, 2021

    @krobelus
    Contributor

    sure, PR is welcome, since it seems to be working for modern versions of cargo. I think using tail is fine but of course fish-fooding is always a good idea.

  6. added this to the fish 3.4.0 milestone on Nov 17, 2021
  7. added a commit that references this issue on Dec 12, 2021
  8. locked as resolved and limited conversation to collaborators on Nov 21, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions