From bee5e2ed1fc7061be8a5c067e600b53babd1e1c8 Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Tue, 24 Nov 2026 22:10:31 +0900 Subject: [PATCH] fix(http-client): let the selected environment override file variables (#5532) The ide-http resolver looked up @name file variables before the environment, so selecting an environment had no effect on a name the .http file also defines. As in the JetBrains HTTP Client (environment variables rank above in-place variables), the order with an environment selected is now private env, public env, $shared, then file variables; without one, file variables still come before $shared. Go to Declaration on {{name}} lists targets in the same order; the guide (en, zh) documents it. Fixes #5530. Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- crates/ide-http/src/env.rs | 32 ++++++++++++------- crates/ide-http/src/exec.rs | 14 +++++++- docs/en/guide/http-client.mdx | 10 +++--- docs/zh/guide/http-client.mdx | 10 +++--- .../http-client/variableNavigation.ts | 8 ++--- 5 files changed, 49 insertions(+), 25 deletions(-) diff --git a/crates/ide-http/src/env.rs b/crates/ide-http/src/env.rs index 276250d150..15510ade9a 100644 --- a/crates/ide-http/src/env.rs +++ b/crates/ide-http/src/env.rs @@ -5,8 +5,10 @@ //! { "$shared": { "version": "v1" }, "dev": { "host": "localhost:8080" } } //! ``` //! -//! Lookup order for `{{name}}`: file variables (`@name = …`), the private -//! environment, the public environment, private `$shared`, public `$shared`. +//! Lookup order for `{{name}}` with an environment selected: the private +//! environment, the public environment, private `$shared`, public `$shared`, then +//! file variables (`@name = …`), as in the JetBrains HTTP Client. Without one, file +//! variables come before `$shared`. //! Dynamic variables: `$uuid` / `$random.uuid`, `$timestamp`, `$isoTimestamp`, //! `$randomInt` / `$random.integer`. @@ -267,17 +269,19 @@ fn iso8601(secs: u64) -> String { pub struct Resolver<'a> { pub file_vars: &'a [(String, String)], pub env: HashMap, + /// An environment is selected: its values override file variables. + pub env_first: bool, } impl Resolver<'_> { fn lookup(&self, name: &str, depth: u32, missing: &mut BTreeSet) -> Option { - if let Some((_, v)) = self.file_vars.iter().rev().find(|(k, _)| k == name) { - return Some(if depth < 8 { self.substitute_inner(v, depth + 1, missing) } else { v.clone() }); + let file = || self.file_vars.iter().rev().find(|(k, _)| k == name).map(|(_, v)| v); + let env = || self.env.get(name); + let found = if self.env_first { env().or_else(file) } else { file().or_else(env) }; + match found { + Some(v) => Some(if depth < 8 { self.substitute_inner(v, depth + 1, missing) } else { v.clone() }), + None => dynamic(name), } - if let Some(v) = self.env.get(name) { - return Some(if depth < 8 { self.substitute_inner(v, depth + 1, missing) } else { v.clone() }); - } - dynamic(name) } fn substitute_inner(&self, text: &str, depth: u32, missing: &mut BTreeSet) -> String { @@ -346,7 +350,7 @@ mod tests { let envs = Environments::from_json(&json, "").unwrap(); let vars = envs.variables(Some("dev")); assert_eq!(vars["value"], token); - let resolver = Resolver { file_vars: &[], env: vars }; + let resolver = Resolver { file_vars: &[], env: vars, env_first: true }; let mut missing = BTreeSet::new(); assert_eq!(resolver.substitute("{\"value\":{{value}}}", &mut missing), format!(r#"{{"value":{token}}}"#)); assert!(missing.is_empty()); @@ -449,11 +453,15 @@ mod tests { #[test] fn substitutes_file_env_and_dynamic_variables() { - let file_vars = vec![("base".to_owned(), "https://{{host}}".to_owned())]; + let file_vars = + vec![("host".to_owned(), "localhost".to_owned()), ("base".to_owned(), "https://{{host}}".to_owned())]; let env = HashMap::from([("host".to_owned(), "example.com".to_owned())]); - let r = Resolver { file_vars: &file_vars, env }; + let r = Resolver { file_vars: &file_vars, env: env.clone(), env_first: true }; let mut missing = BTreeSet::new(); + // The environment's `host` overrides the file's, also inside a file variable. assert_eq!(r.substitute("{{ base }}/a?x={{nope}}", &mut missing), "https://example.com/a?x={{nope}}"); + let file_first = Resolver { file_vars: &file_vars, env, env_first: false }; + assert_eq!(file_first.substitute("{{base}}", &mut BTreeSet::new()), "https://localhost"); assert_eq!(missing.into_iter().collect::>(), vec!["nope"]); let mut missing = BTreeSet::new(); let id = r.substitute("{{$uuid}}", &mut missing); @@ -465,7 +473,7 @@ mod tests { #[test] fn self_reference_terminates() { let file_vars = vec![("a".to_owned(), "{{a}}".to_owned())]; - let r = Resolver { file_vars: &file_vars, env: HashMap::new() }; + let r = Resolver { file_vars: &file_vars, env: HashMap::new(), env_first: true }; let mut missing = BTreeSet::new(); assert_eq!(r.substitute("{{a}}", &mut missing), "{{a}}"); } diff --git a/crates/ide-http/src/exec.rs b/crates/ide-http/src/exec.rs index c51d53b1e8..3fa7455e78 100644 --- a/crates/ide-http/src/exec.rs +++ b/crates/ide-http/src/exec.rs @@ -77,7 +77,7 @@ pub fn prepare( env: Option<&str>, base_dir: Option<&Path>, ) -> IdeResult { - let resolver = Resolver { file_vars, env: envs.variables(env) }; + let resolver = Resolver { file_vars, env: envs.variables(env), env_first: env.is_some() }; let mut missing = BTreeSet::new(); let url = resolver.substitute(&raw.block.url, &mut missing); let headers: Vec<(String, String)> = @@ -290,6 +290,18 @@ mod tests { assert_eq!(p.body.as_deref(), Some("{\"id\": \"{{id}}\"}")); } + #[test] + fn selected_environment_overrides_file_variables() { + let f = parse("@host = localhost:8080\n@path = {{host}}/v1\nGET http://{{path}}/x?env={{name}}\n"); + let envs = + Environments::from_json(r#"{"$shared":{"host":"shared","name":"none"},"dev":{"host":"dev.test"}}"#, "") + .unwrap(); + let url = |env| prepare(&f.requests[0], &f.variables, &envs, env, None).unwrap().url; + assert_eq!(url(Some("dev")), "http://dev.test/v1/x?env=none"); + // No environment: the file's value wins over `$shared`. + assert_eq!(url(None), "http://localhost:8080/v1/x?env=none"); + } + #[test] fn reports_unresolved_variables() { let f = parse("GET https://{{host}}/x\n"); diff --git a/docs/en/guide/http-client.mdx b/docs/en/guide/http-client.mdx index c9d5811201..7ff16c9dec 100644 --- a/docs/en/guide/http-client.mdx +++ b/docs/en/guide/http-client.mdx @@ -50,10 +50,12 @@ Content-Type: application/json Write `{{name}}` anywhere in the URL, headers or body. A name is looked up in this order: -1. File variables: `@name = value` lines. They apply to the whole file; a later definition wins. -2. The selected environment in `http-client.private.env.json`. -3. The selected environment in `http-client.env.json`. -4. `$shared` in the private file, then `$shared` in the public file. +1. The selected environment in `http-client.private.env.json`. +2. The selected environment in `http-client.env.json`. +3. `$shared` in the private file, then `$shared` in the public file. +4. File variables: `@name = value` lines. They apply to the whole file; a later definition wins. + +So a selected environment overrides a file variable of the same name, as in the JetBrains HTTP Client. With no environment selected, file variables come before `$shared`. Variables can refer to other variables. A request with an unresolved variable is not sent; the error lists the missing names. Variables inside a file inserted with `<` are not substituted. diff --git a/docs/zh/guide/http-client.mdx b/docs/zh/guide/http-client.mdx index e05e8eb5b0..7ea414c396 100644 --- a/docs/zh/guide/http-client.mdx +++ b/docs/zh/guide/http-client.mdx @@ -50,10 +50,12 @@ Content-Type: application/json 在 URL、请求头或请求体中写 `{{name}}`。变量按以下顺序查找: -1. 文件变量:`@name = value` 行。对整个文件生效,后定义的覆盖先定义的。 -2. `http-client.private.env.json` 中所选环境。 -3. `http-client.env.json` 中所选环境。 -4. 私有文件中的 `$shared`,然后是公共文件中的 `$shared`。 +1. `http-client.private.env.json` 中所选环境。 +2. `http-client.env.json` 中所选环境。 +3. 私有文件中的 `$shared`,然后是公共文件中的 `$shared`。 +4. 文件变量:`@name = value` 行。对整个文件生效,后定义的覆盖先定义的。 + +因此所选环境中的值会覆盖同名的文件变量,与 JetBrains HTTP Client 一致。未选择环境时,文件变量先于 `$shared`。 变量可以引用其他变量。有未解析变量的请求不会发送,错误信息会列出缺少的变量名。用 `<` 插入的文件中的变量不会替换。 diff --git a/src/features/http-client/variableNavigation.ts b/src/features/http-client/variableNavigation.ts index 4d463167f0..f9f8895678 100644 --- a/src/features/http-client/variableNavigation.ts +++ b/src/features/http-client/variableNavigation.ts @@ -1,7 +1,7 @@ /** - * Navigate › Declaration (⌘-click, ⌘B) on `{{name}}` in a `.http` file: the `@name = …` line of - * the same file, then the key `name` in each environment of the nearest - * `http-client.private.env.json` and `http-client.env.json` — the variable lookup order. + * Navigate › Declaration (⌘-click, ⌘B) on `{{name}}` in a `.http` file: the key `name` in each + * environment of the nearest `http-client.private.env.json` and `http-client.env.json`, then the + * `@name = …` line of the same file — the variable lookup order with an environment selected. */ import type { Text } from "@codemirror/state"; import { registerNavigationProvider } from "@/editor/api"; @@ -49,6 +49,6 @@ export function registerVariableNavigation(): () => void { } catch { // No project or unreadable environment files: the file's own definitions still count. } - return { from: at.from, to: at.to, targets: [...inFile, ...inEnv] }; + return { from: at.from, to: at.to, targets: [...inEnv, ...inFile] }; }); }