Search code examples
rust-cargovscode-devcontainercodespacesgithub-codespacesdevcontainer

Cargo not found after installing in a devcontainer


I have a .devcontainer.json for GitHub Codespaces but when I run cargo in the postCreateCommand it states that cargo isn't found.

Below is my .devcontainer.json:

{
    "name": "Cargo",
    "image": "mcr.microsoft.com/devcontainers/base:jammy",

    // Install Cargo when the devcontainer is made
    "onCreateCommand": "curl https://sh.rustup.rs -sSf | sh -s -- -y",

    // Install Cargo dependencies after the devcontainer is made
    "postCreateCommand": "cargo install aftman",
}

The specific log from the creation.log:

2024-03-24 21:44:44.709Z: cargo install aftman
2024-03-24 21:44:44.771Z: /bin/sh: 1: cargo: not found
2024-03-24 21:44:44.797Z: postCreateCommand failed with exit code 127. Skipping any further user-provided commands.

When I run cargo in the codespace's terminal it works fine and I can install cargo dependencies there but I want it to install cargo automatically when I open the codespace.

Note that the codespace works fine and doesn't go into recovery mode at all so nothing else should be wrong.

I tried making it so that bash terminal restarts but that just made it so my codespace never loaded.


Solution

  • I was able to use . $HOME/.cargo/env to check whether or not cargo was setup before running it which fixed the problem.

    The issue was cargo install was ran before cargo was actually installed.

    Below is the new code with the fix.

    {
        "name": "Cargo",
        "image": "mcr.microsoft.com/devcontainers/base:jammy",
    
        // Install Cargo when the devcontainer is made
        "onCreateCommand": "curl https://sh.rustup.rs -sSf | sh -s -- -y",
    
        // Install Cargo dependencies after the devcontainer is made
        "postCreateCommand": ". $HOME/.cargo/env && cargo install aftman",
    }