rust-analyzer icon indicating copy to clipboard operation
rust-analyzer copied to clipboard

Set cargo path

Open hadim opened this issue 1 year ago • 12 comments

Would it be possible to add a configuration to be able to set the path to cargo?

Related to https://github.com/rust-lang/rust-analyzer/issues/3154

Setting PATH would not work for my use case. I am using pixi to set up and install the dev environment. This tool installs cargo and all the deps inside {{ workspace_folder }}/.pixi/env.

hadim avatar Dec 27 '23 19:12 hadim

In this setup, how do you invoke cargo on the CLI? You are not typing the entire ~/.pixi/env/bin/cargo, right? Is it still just cargo on the CLI?

matklad avatar Dec 30 '23 12:12 matklad

Pixi allows you to run arbitrary commands within the new env:

  • pixi run cargo build
  • pixi run <your_command>
  • pixi shell (spawn a new shell with all the paths set correctly)

hadim avatar Dec 30 '23 12:12 hadim

Ah, interesting! Yeah, currently rust-analyzer assumes that it can invoke cargo using just binary name (so, /path/to/cargo), and it doesn't support complex command like pixi run cargo. Which arguably is a design bug! We should have treated cargo as Vec<OsString>, not as PathBuf! But oh well, this now is wired up pretty thoroughly.

So, the best fix here would probably be just:

https://github.com/rust-lang/rust-analyzer/issues/3154#issuecomment-943678481

The current work-around would be to launch VS Code from pixi shell environment.

Alternatively, perhaps there could be a VS Code extension for pixi that cares to run pixi shell automatically? Not sure if VS Code exposes necessary hooks though.

matklad avatar Dec 30 '23 12:12 matklad

Yes, being able to set something like CARGO pointing to ./pixi/env/cargo would be enough, but I also like the idea of being able to set pixi run cargo as well.

The current work-around would be to launch VS Code from pixi shell environment.

It would work but it's not ideal.

Alternatively, perhaps there could be a VS Code extension for pixi that cares to run pixi shell automatically? Not sure if VS Code exposes necessary hooks though

pixi is quite close to conda (but more general). The vscode team is already working to generalize conda support in vscode (xref https://github.com/microsoft/vscode-python/issues/20919).

hadim avatar Dec 30 '23 15:12 hadim

@matklad would that require a lot of work to implement your proposal? I am still learning rust, but would be happy to give it a shot if it's a low-hanging fruit. It's also a general solution that would benefit beyond pixi.

hadim avatar Dec 30 '23 15:12 hadim

Ah, interesting! Yeah, currently rust-analyzer assumes that it can invoke cargo using just binary name (so, /path/to/cargo), and it doesn't support complex command like pixi run cargo. Which arguably is a design bug! We should have treated cargo as Vec<OsString>, not as PathBuf! But oh well, this now is wired up pretty thoroughly.

For what it's worth, I hacked up something similar for the rust-analyzer server path (which only really lives in the extension...), allowing the path to rust-analyzer be specified using something like arc rust-analyzer. While the change was a little tedious, it wasn't hard. I've been meaning to switch over to a Vec<OsString> for Cargo as well, so I'm glad my impulse wasn't ill-founded.

davidbarsky avatar Dec 30 '23 20:12 davidbarsky

Facing the same problem. Is there any progress?

Haskely avatar Jul 15 '24 12:07 Haskely

I belive you can now use config like the fololwing

"rust-analyzer.server.extraEnv": {
    "CARGO": "/your/project/.pixi/env/cargo"
}

(I havin't actually tried this, so it might need adjustmeents, but something like that should work)

matklad avatar Jul 15 '24 13:07 matklad

I belive you can now use config like the fololwing

"rust-analyzer.server.extraEnv": {
    "CARGO": "/your/project/.pixi/env/cargo"
}

(I havin't actually tried this, so it might need adjustmeents, but something like that should work)

Your configuration won't work directly, but setting "extraEnv" is indeed a feasible idea.

The underlying logic of switching environments in pixi is to set a series of specific environment variables and run some specific "activation" scripts if necessary. Detailed information can be found at: https://pixi.sh/latest/features/environment/#activation

Therefore, I can run "pixi shell-hook" to check the environment variables needed for activation and then manually add them to "rust-analyzer.cargo.extraEnv".


In fact, the result I get from executing "pixi shell-hook" is:

# pixi shell-hook

export PATH="/Users/nova/rust-learn/my_rust_project/.pixi/envs/default/bin:/Users/nova/.nvm/versions/node/v21.6.2/bin:/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/System/Cryptexes/App/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/local/bin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/bin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/appleinternal/bin:/Users/nova/.cargo/bin:/Users/nova/.rye/shims:/Users/nova/.nvm/versions/node/v21.6.2/bin:/opt/homebrew/bin:/opt/homebrew/sbin"
export CONDA_PREFIX="/Users/nova/rust-learn/my_rust_project/.pixi/envs/default"
export PIXI_PROMPT="(my_rust_project) "
export PIXI_PROJECT_VERSION="0.1.0"
export PIXI_PROJECT_NAME="my_rust_project"
export PIXI_EXE="/opt/homebrew/bin/pixi"
export PIXI_ENVIRONMENT_PLATFORMS="osx-arm64"
export PIXI_PROJECT_ROOT="/Users/nova/rust-learn/my_rust_project"
export PIXI_PROJECT_MANIFEST="/Users/nova/rust-learn/my_rust_project/pixi.toml"
export PIXI_IN_SHELL="1"
export PIXI_ENVIRONMENT_NAME="default"
export CONDA_DEFAULT_ENV="my_rust_project"

Among these, the truly important part is export PATH="/Users/nova/rust-learn/my_rust_project/.pixi/envs/default/bin:<other paths>".

Therefore, I can set "rust-analyzer.cargo.extraEnv" at the "workspace level":

image

{
    "rust-analyzer.server.extraEnv": {
        "PATH": "/Users/nova/rust-learn/my_rust_project/.pixi/envs/default/bin:$PATH"
    }
}

After setting this, restart the rust-analyzer plugin or reload VSCode, and you will find that the rust-analyzer plugin can check the syntax of .rs files.


However, this is still not a perfect solution. For example, clicking the RUN button still prompts:

image

 *  Executing task: cargo run --package my_rust_project --bin my_rust_project 


 *  The terminal process failed to launch: Path to shell executable "cargo" does not exist. 

Moreover, this method of manually setting the PATH is not only cumbersome (you have to set it manually for each new workspace, because pixi creates separate environment folders for each new project. ) but also inconvenient for switching between multiple Rust environments(nightly beta etc.).

A better solution is still needed!

Haskely avatar Jul 16 '24 05:07 Haskely

@hadim @matklad the latest version meets this problem again. As follows:

The terminal process failed to launch: Path to shell executable "cargo" does not exist.

Actually,Both rustc and cargo is located at $HOME/.cargo/bin:$PATH. So I revert to last week's version.

ai-chen2050 avatar Jul 23 '24 02:07 ai-chen2050

Any fix?

b0c1 avatar Oct 07 '24 12:10 b0c1

@b0c1 reopen vscode process, maybe can fix.

ai-chen2050 avatar Oct 07 '24 14:10 ai-chen2050

I belive you can now use config like the fololwing

"rust-analyzer.server.extraEnv": {
    "CARGO": "/your/project/.pixi/env/cargo"
}

(I havin't actually tried this, so it might need adjustmeents, but something like that should work)

Your configuration won't work directly, but setting "extraEnv" is indeed a feasible idea.

The underlying logic of switching environments in pixi is to set a series of specific environment variables and run some specific "activation" scripts if necessary. Detailed information can be found at: https://pixi.sh/latest/features/environment/#activation

Therefore, I can run "pixi shell-hook" to check the environment variables needed for activation and then manually add them to "rust-analyzer.cargo.extraEnv".


In fact, the result I get from executing "pixi shell-hook" is:

# pixi shell-hook

export PATH="/Users/nova/rust-learn/my_rust_project/.pixi/envs/default/bin:/Users/nova/.nvm/versions/node/v21.6.2/bin:/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/System/Cryptexes/App/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/local/bin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/bin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/appleinternal/bin:/Users/nova/.cargo/bin:/Users/nova/.rye/shims:/Users/nova/.nvm/versions/node/v21.6.2/bin:/opt/homebrew/bin:/opt/homebrew/sbin"
export CONDA_PREFIX="/Users/nova/rust-learn/my_rust_project/.pixi/envs/default"
export PIXI_PROMPT="(my_rust_project) "
export PIXI_PROJECT_VERSION="0.1.0"
export PIXI_PROJECT_NAME="my_rust_project"
export PIXI_EXE="/opt/homebrew/bin/pixi"
export PIXI_ENVIRONMENT_PLATFORMS="osx-arm64"
export PIXI_PROJECT_ROOT="/Users/nova/rust-learn/my_rust_project"
export PIXI_PROJECT_MANIFEST="/Users/nova/rust-learn/my_rust_project/pixi.toml"
export PIXI_IN_SHELL="1"
export PIXI_ENVIRONMENT_NAME="default"
export CONDA_DEFAULT_ENV="my_rust_project"

Among these, the truly important part is export PATH="/Users/nova/rust-learn/my_rust_project/.pixi/envs/default/bin:<other paths>".

Therefore, I can set "rust-analyzer.cargo.extraEnv" at the "workspace level":

image

{
    "rust-analyzer.server.extraEnv": {
        "PATH": "/Users/nova/rust-learn/my_rust_project/.pixi/envs/default/bin:$PATH"
    }
}

After setting this, restart the rust-analyzer plugin or reload VSCode, and you will find that the rust-analyzer plugin can check the syntax of .rs files.


However, this is still not a perfect solution. For example, clicking the RUN button still prompts:

image

 *  Executing task: cargo run --package my_rust_project --bin my_rust_project 


 *  The terminal process failed to launch: Path to shell executable "cargo" does not exist. 

Moreover, this method of manually setting the PATH is not only cumbersome (you have to set it manually for each new workspace, because pixi creates separate environment folders for each new project. ) but also inconvenient for switching between multiple Rust environments(nightly beta etc.).

A better solution is still needed!

Did you solve the RUN button click issue? Now I'm same like you. Please help

DevelopJKong avatar Oct 27 '24 08:10 DevelopJKong

In a similar place over here; I use mise, yet another "install multiple copies of tools and dynamically select from them per-project" tool ala rbenv or nodenv or asdf. As with most cases, this interacts with VScode extensions very poorly, as they tend to implement their own binary-locating logic instead of invoking an entire shell.

I tried the above workaround:

I believe you can now use config like the following

{
   "rust-analyzer.server.extraEnv": {
      "PATH": "/Users/ec/.local/share/mise/installs/rust/1.87.0/bin:$PATH"
   }
}

… but still run into issues; I think possibly because other parts don't use server.extraEnv?

2025-05-16T18:19:04.311301-05:00 ERROR failed fetching toolchain version for ManifestPath { file: AbsPathBuf("/Users/ec/Sync/Code/twag/Cargo.toml") } workspace e=Failed to query rust toolchain version via `cd "/Users/ec/Sync/Code/twag" && "/Users/ec/.local/share/mise/installs/rust/1.87.0/bin/cargo" "--version"`, is your toolchain setup correctly?
2025-05-16T18:19:04.332685-05:00 ERROR failed fetching data layout for ManifestPath { file: AbsPathBuf("/Users/ec/Sync/Code/twag/Cargo.toml") } workspace e=unable to fetch target-data-layout via `cd "/Users/ec/Sync/Code/twag" && RUSTC_BOOTSTRAP="1" "/Users/ec/.local/share/mise/installs/rust/1.87.0/bin/rustc" "-Z" "unstable-options" "--print" "target-spec-json"`
2025-05-16T18:19:04.353237-05:00 ERROR FetchWorkspaceError: rust-analyzer failed to load workspace: Failed to load the project at /Users/ec/Sync/Code/twag/Cargo.toml: Failed to read Cargo metadata from Cargo.toml file /Users/ec/Sync/Code/twag/Cargo.toml, None: Failed to run `cd "/Users/ec/Sync/Code/twag" && "/Users/ec/.local/share/mise/installs/rust/1.87.0/bin/cargo" "metadata" "--format-version" "1" "--manifest-path" "/Users/ec/Sync/Code/twag/Cargo.toml"`: `cargo metadata` exited with an error: error: rustup could not choose a version of cargo to run, because one wasn't specified explicitly, and no default is configured.
help: run 'rustup default stable' to download the latest stable release of Rust and set it as your default toolchain.

This is especially odd, as both of those commands work fine in an interactive shell:

Output:
$ (cd "/Users/ec/Sync/Code/twag" && "/Users/ec/.local/share/mise/installs/rust/1.87.0/bin/cargo" "--version")
cargo 1.87.0 (99624be96 2025-05-06)

$ (cd "/Users/ec/Sync/Code/twag" && RUSTC_BOOTSTRAP="1" "/Users/ec/.local/share/mise/installs/rust/1.87.0/bin/rustc" "-Z" "unstable-options" "--print" "target-spec-json")                                                                                                       
{
  "abi-return-struct-as-int": true,
  "arch": "x86_64",
  "archive-format": "darwin",
  "binary-format": "mach-o",
  "cpu": "penryn",
  "crt-objects-fallback": "false",
  "data-layout": "e-m:o-p270:32:32-p271:32:32-p272:64:64-i64:64-i128:128-f80:128-n8:16:32:64-S128",
  "debuginfo-kind": "dwarf-dsym",
  "dll-suffix": ".dylib",
  "dynamic-linking": true,
  "eh-frame-header": false,
  "emit-debug-gdb-scripts": false,
  "frame-pointer": "always",
  "function-sections": false,
  "has-rpath": true,
  "has-thread-local": true,
  "is-like-osx": true,
  "link-env": [
    "ZERO_AR_DATE=1"
  ],
  "link-env-remove": [
    "IPHONEOS_DEPLOYMENT_TARGET",
    "TVOS_DEPLOYMENT_TARGET",
    "XROS_DEPLOYMENT_TARGET"
  ],
  "linker-flavor": "darwin-cc",
  "linker-is-gnu": false,
  "lld-flavor": "darwin",
  "llvm-floatabi": "hard",
  "llvm-target": "x86_64-apple-macosx",
  "max-atomic-width": 128,
  "metadata": {
    "description": "x86_64 Apple macOS (10.12+, Sierra+)",
    "host_tools": true,
    "std": true,
    "tier": 1
  },
  "os": "macos",
  "split-debuginfo": "packed",
  "stack-probes": {
    "kind": "inline"
  },
  "supported-sanitizers": [
    "address",
    "leak",
    "thread",
    "cfi"
  ],
  "supported-split-debuginfo": [
    "packed",
    "unpacked",
    "off"
  ],
  "target-family": [
    "unix"
  ],
  "target-mcount": "\u0001mcount",
  "target-pointer-width": "64",
  "vendor": "apple"
}

Are there any other workarounds?


Notably, Mise "just" uses rustup, bypassing all of its own usual logic in the case of Rust; so I'm a little surprised this didn't work out-of-the-box (although my expectations with VScode extensions handling path-wrangling well are very low; it's a surprisingly difficult problem to solve …)

ELLIOTTCABLE avatar May 16 '25 23:05 ELLIOTTCABLE

In a similar place over here; I use mise, yet another "install multiple copies of tools and dynamically select from them per-project" tool ala rbenv or nodenv or asdf. As with most cases, this interacts with VScode extensions very poorly, as they tend to implement their own binary-locating logic instead of invoking an entire shell.

I tried the above workaround:

I believe you can now use config like the following { "rust-analyzer.server.extraEnv": { "PATH": "/Users/ec/.local/share/mise/installs/rust/1.87.0/bin:$PATH" } }

… but still run into issues; I think possibly because other parts don't use server.extraEnv?

2025-05-16T18:19:04.311301-05:00 ERROR failed fetching toolchain version for ManifestPath { file: AbsPathBuf("/Users/ec/Sync/Code/twag/Cargo.toml") } workspace e=Failed to query rust toolchain version via `cd "/Users/ec/Sync/Code/twag" && "/Users/ec/.local/share/mise/installs/rust/1.87.0/bin/cargo" "--version"`, is your toolchain setup correctly?
2025-05-16T18:19:04.332685-05:00 ERROR failed fetching data layout for ManifestPath { file: AbsPathBuf("/Users/ec/Sync/Code/twag/Cargo.toml") } workspace e=unable to fetch target-data-layout via `cd "/Users/ec/Sync/Code/twag" && RUSTC_BOOTSTRAP="1" "/Users/ec/.local/share/mise/installs/rust/1.87.0/bin/rustc" "-Z" "unstable-options" "--print" "target-spec-json"`
2025-05-16T18:19:04.353237-05:00 ERROR FetchWorkspaceError: rust-analyzer failed to load workspace: Failed to load the project at /Users/ec/Sync/Code/twag/Cargo.toml: Failed to read Cargo metadata from Cargo.toml file /Users/ec/Sync/Code/twag/Cargo.toml, None: Failed to run `cd "/Users/ec/Sync/Code/twag" && "/Users/ec/.local/share/mise/installs/rust/1.87.0/bin/cargo" "metadata" "--format-version" "1" "--manifest-path" "/Users/ec/Sync/Code/twag/Cargo.toml"`: `cargo metadata` exited with an error: error: rustup could not choose a version of cargo to run, because one wasn't specified explicitly, and no default is configured.
help: run 'rustup default stable' to download the latest stable release of Rust and set it as your default toolchain.

This is especially odd, as both of those commands work fine in an interactive shell: Output:

Are there any other workarounds?

Notably, Mise "just" uses rustup, bypassing all of its own usual logic in the case of Rust; so I'm a little surprised this didn't work out-of-the-box (although my expectations with VScode extensions handling path-wrangling well are very low; it's a surprisingly difficult problem to solve …)

I am in the same situation as you - getting weird errors like %1 is not a valid Win32-Application. (ps error 193) (I translated this, as it's in Dutch fro me)

ThaDaVos avatar Aug 22 '25 15:08 ThaDaVos

Moreover, this method of manually setting the PATH is not only cumbersome (you have to set it manually for each new workspace, because pixi creates separate environment folders for each new project. ) but also inconvenient for switching between multiple Rust environments(nightly beta etc.).

A better solution is still needed!

The following settings work for me (both as user and workspace settings):

{
  "rust-analyzer.cargo.extraEnv": {
    "PATH": "${workspaceFolder}/.pixi/envs/default/bin:$PATH"
  },
  "rust-analyzer.runnables.command": "pixi run start"
}

With the following pixi.toml:

[workspace]
channels = ["conda-forge"]
name = "my_project"
platforms = ["osx-arm64"]
version = "0.1.0"

[tasks]
start = "cargo run"

[dependencies]
rust = ">=1.91.0,<1.92"
rust-src = ">=1.91.0,<1.92"
  • Using ${workspaceFolder} makes the setting a bit more generic
  • Running via vscode works
  • Formatting via vscode works

gmhewett avatar Nov 10 '25 04:11 gmhewett