дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-28 13:32:29 +02:00
Порівняти коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
b372c21e6f | ||
|
|
97177486e9 | ||
|
|
57d35ecdb4 |
No files matched your search
@@ -143,7 +143,7 @@ fn nvm_bins(dir: &Path) -> Vec<PathBuf> {
|
||||
}
|
||||
|
||||
/// `v22.10.1` as `[22, 10, 1]`: v22 is newer than v9, v20.10 newer than v20.9.
|
||||
fn version_key(name: &str) -> Vec<u64> {
|
||||
pub fn version_key(name: &str) -> Vec<u64> {
|
||||
name.trim_start_matches('v').split('.').map(|n| n.parse().unwrap_or(0)).collect()
|
||||
}
|
||||
|
||||
|
||||
@@ -52,6 +52,14 @@ pub fn sdk_python_effective(host: &Host, window: &str) -> IdeResult<Option<ide_c
|
||||
Ok(ide_sdk::apply::python_interpreter(&project.root, &project.settings.effective()).map(Into::into))
|
||||
}
|
||||
|
||||
/// The PHP interpreter chosen in Settings › Languages & Frameworks › PHP; `None`: the `php` on `PATH`.
|
||||
pub fn sdk_php_effective(host: &Host, window: &str) -> IdeResult<Option<ide_core::IpcPath>> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
let settings = project.settings.effective();
|
||||
Ok(ide_sdk::apply::setting_path(&project.root, &settings.languages.php.interpreter).map(Into::into))
|
||||
}
|
||||
|
||||
/// The PHP language level of the project `path` belongs to (a workspace member, by path, as
|
||||
/// the language server configuration picks it).
|
||||
#[derive(Clone, Debug, serde::Serialize, specta::Type)]
|
||||
@@ -198,6 +206,7 @@ pub async fn sdk_python_pip(
|
||||
pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("sdk_detect", |c| async move { sdk_detect(&c.host, &c.window, c.arg("kind")?).await });
|
||||
d.add("sdk_python_effective", |c| async move { sdk_python_effective(&c.host, &c.window) });
|
||||
d.add("sdk_php_effective", |c| async move { sdk_php_effective(&c.host, &c.window) });
|
||||
d.add(
|
||||
"sdk_php_language_level",
|
||||
|c| async move { sdk_php_language_level(&c.host, &c.window, c.arg("path")?).await },
|
||||
|
||||
@@ -282,8 +282,38 @@ pub(crate) fn php_source(path: &Path, home: Option<&Path>) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
/// `php` CLIs: every one on `PATH`, Homebrew's versioned formulae, PHP version managers,
|
||||
/// Laravel Herd, and the usual Windows distributions (XAMPP, Laragon).
|
||||
/// A PHP CLI named with its version, as Debian / Ubuntu (`ppa:ondrej/php`) install them:
|
||||
/// `php8.1`, `php81`. Not `php-cgi8.1`, `phpize8.1` or `phpdbg8.1`.
|
||||
pub(crate) fn is_versioned_php_name(name: &str) -> bool {
|
||||
let name = name.strip_suffix(".exe").unwrap_or(name);
|
||||
let Some(version) = name.strip_prefix("php") else { return false };
|
||||
let mut parts = version.splitn(2, '.');
|
||||
let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
|
||||
parts.next().is_some_and(digits) && parts.next().is_none_or(digits)
|
||||
}
|
||||
|
||||
/// The versioned PHP CLIs in `dirs`, in `PATH` order (sorted by name within a directory).
|
||||
pub(crate) fn versioned_php_in(dirs: impl IntoIterator<Item = PathBuf>) -> Vec<PathBuf> {
|
||||
let mut found = Vec::new();
|
||||
for dir in dirs {
|
||||
if version_managers::is_shims_dir(&dir) {
|
||||
continue;
|
||||
}
|
||||
let mut names: Vec<String> = std::fs::read_dir(&dir)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.map(|e| e.file_name().to_string_lossy().into_owned())
|
||||
.filter(|n| is_versioned_php_name(n))
|
||||
.collect();
|
||||
names.sort();
|
||||
found.extend(names.into_iter().map(|n| dir.join(n)).filter(|p| p.is_file()));
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// `php` CLIs: every one on `PATH` (also versioned ones, `php8.1`), Homebrew's versioned
|
||||
/// formulae, PHP version managers, Laravel Herd, and the usual Windows distributions (XAMPP, Laragon).
|
||||
fn php() -> Vec<Sdk> {
|
||||
let mut found: Vec<(PathBuf, &'static str)> = Vec::new();
|
||||
let home = home_dir();
|
||||
@@ -294,6 +324,11 @@ fn php() -> Vec<Sdk> {
|
||||
let source = php_source(&p, home.as_deref());
|
||||
found.push((p, source));
|
||||
}
|
||||
// After the plain `php`: deduplication keeps `/usr/bin/php` over the `php8.3` it links to.
|
||||
for p in versioned_php_in(std::env::split_paths(&search_path())) {
|
||||
let source = php_source(&p, home.as_deref());
|
||||
found.push((p, source));
|
||||
}
|
||||
let named = |dir: &Path, prefix: &str| -> Vec<PathBuf> {
|
||||
subdirs(dir)
|
||||
.into_iter()
|
||||
@@ -332,7 +367,7 @@ fn php() -> Vec<Sdk> {
|
||||
}
|
||||
}
|
||||
let found = dedupe_by_real_path(found);
|
||||
par_map(&found, |(path, source)| {
|
||||
let mut sdks = par_map(&found, |(path, source)| {
|
||||
let version = query(path, &["-r", "echo PHP_VERSION;"], VERSION_TIMEOUT)?;
|
||||
let version = version.trim().to_owned();
|
||||
if version.is_empty() {
|
||||
@@ -346,7 +381,16 @@ fn php() -> Vec<Sdk> {
|
||||
home: path.parent().and_then(Path::parent).map(Into::into),
|
||||
extra: None,
|
||||
})
|
||||
})
|
||||
});
|
||||
newest_first(&mut sdks);
|
||||
sdks
|
||||
}
|
||||
|
||||
/// Newest version first, number by number (8.3.12 before 8.3.9); stable, so on equal
|
||||
/// versions the `PATH` install stays first.
|
||||
pub(crate) fn newest_first(sdks: &mut [Sdk]) {
|
||||
let key = |s: &Sdk| ide_core::tool_path::version_key(s.version.as_deref().unwrap_or(""));
|
||||
sdks.sort_by_key(|s| std::cmp::Reverse(key(s)));
|
||||
}
|
||||
|
||||
fn node() -> Vec<Sdk> {
|
||||
|
||||
@@ -1322,9 +1322,50 @@ fn php_sources_and_selected_interpreter() {
|
||||
assert_eq!(source("/opt/homebrew/opt/[email protected]/bin/php"), "homebrew");
|
||||
assert_eq!(source("/home/me/bin/php"), "path");
|
||||
|
||||
use crate::discover::{is_versioned_php_name, newest_first, versioned_php_in};
|
||||
let sdk = |path: &str, version: &str| crate::Sdk {
|
||||
path: std::path::PathBuf::from(path).into(),
|
||||
name: format!("PHP {version}"),
|
||||
version: Some(version.into()),
|
||||
source: "path".into(),
|
||||
home: None,
|
||||
extra: None,
|
||||
};
|
||||
let mut sdks = vec![
|
||||
sdk("/opt/homebrew/bin/php", "8.4.1"),
|
||||
sdk("/opt/homebrew/opt/[email protected]/bin/php", "8.1.31"),
|
||||
sdk("/opt/homebrew/opt/[email protected]/bin/php", "8.2.20"),
|
||||
sdk("/home/me/.phpbrew/php/php-8.3.9/bin/php", "8.3.9"),
|
||||
sdk("/home/me/.phpbrew/php/php-8.3.12/bin/php", "8.3.12"),
|
||||
sdk("/home/me/.phpbrew/php/php-7.4.33/bin/php", "7.4.33"),
|
||||
sdk("/usr/bin/php", "8.4.1"),
|
||||
];
|
||||
newest_first(&mut sdks);
|
||||
let order: Vec<_> = sdks.iter().map(|s| s.version.clone().unwrap()).collect();
|
||||
assert_eq!(order, ["8.4.1", "8.4.1", "8.3.12", "8.3.9", "8.2.20", "8.1.31", "7.4.33"]);
|
||||
// Stable: on equal versions the PATH install stays first.
|
||||
assert_eq!(sdks[0].path.0, std::path::PathBuf::from("/opt/homebrew/bin/php"));
|
||||
for name in ["php8.1", "php81", "php8", "php8.3.exe"] {
|
||||
assert!(is_versioned_php_name(name), "{name}");
|
||||
}
|
||||
for name in ["php", "php-cgi8.1", "phpize8.1", "phpdbg8.1", "php-fpm8.1", "php8.", "php.8", "php8.1.2x", "phpunit"]
|
||||
{
|
||||
assert!(!is_versioned_php_name(name), "{name}");
|
||||
}
|
||||
|
||||
if cfg!(windows) {
|
||||
return; // Unix paths
|
||||
}
|
||||
let bins = tempfile::tempdir().unwrap();
|
||||
for name in ["php", "php8.3", "php8.1", "php-cgi8.1", "phpize8.1", "phpdbg8.1"] {
|
||||
std::fs::write(bins.path().join(name), "").unwrap();
|
||||
}
|
||||
std::fs::create_dir(bins.path().join("php9.0")).unwrap();
|
||||
assert_eq!(
|
||||
versioned_php_in([bins.path().to_path_buf()]),
|
||||
vec![bins.path().join("php8.1"), bins.path().join("php8.3")]
|
||||
);
|
||||
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut s = Settings::default();
|
||||
assert_eq!(crate::apply::php_dir(tmp.path(), &s), None);
|
||||
|
||||
@@ -398,6 +398,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
tools::jdk_download,
|
||||
sdk::sdk_detect,
|
||||
sdk::sdk_python_effective,
|
||||
sdk::sdk_php_effective,
|
||||
sdk::sdk_php_language_level,
|
||||
sdk::sdk_project_libraries,
|
||||
sdk::sdk_locate_tools,
|
||||
|
||||
@@ -24,6 +24,13 @@ pub fn sdk_python_effective(window: Window, state: State<'_, AppState>) -> IdeRe
|
||||
ide_host::ops::sdk::sdk_python_effective(&state.host, window.label())
|
||||
}
|
||||
|
||||
/// The PHP interpreter chosen in Settings › Languages & Frameworks › PHP; `None`: the `php` on `PATH`.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn sdk_php_effective(window: Window, state: State<'_, AppState>) -> IdeResult<Option<ide_core::IpcPath>> {
|
||||
ide_host::ops::sdk::sdk_php_effective(&state.host, window.label())
|
||||
}
|
||||
|
||||
/// The PHP language level of the project `path` belongs to: the effective one and Auto's.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
|
||||
@@ -772,6 +772,8 @@ export const commands = {
|
||||
sdkDetect: (kind: SdkKind) => typedError<Sdk[], IdeError>(__TAURI_INVOKE("sdk_detect", { kind })),
|
||||
/** The interpreter the project uses: the configured one, else its virtualenv. */
|
||||
sdkPythonEffective: () => typedError<string | null, IdeError>(__TAURI_INVOKE("sdk_python_effective")),
|
||||
/** The PHP interpreter chosen in Settings › Languages & Frameworks › PHP; `None`: the `php` on `PATH`. */
|
||||
sdkPhpEffective: () => typedError<string | null, IdeError>(__TAURI_INVOKE("sdk_php_effective")),
|
||||
/** The PHP language level of the project `path` belongs to: the effective one and Auto's. */
|
||||
sdkPhpLanguageLevel: (path: string) => typedError<PhpLanguageLevels, IdeError>(__TAURI_INVOKE("sdk_php_language_level", { path })),
|
||||
/**
|
||||
|
||||
@@ -98,7 +98,13 @@ export async function produceResolved(input: ContextInput, dir = false): Promise
|
||||
// Project configurations (tests, cargo, gradle…) need no runtime lookup.
|
||||
if (named.config && !named.config.id.startsWith("context:file:")) return named;
|
||||
const lang = scriptLanguage(input.path, input.content);
|
||||
const env = await toolEnv(neededTools(fresh), input.path, fresh.root, lang === "python" || lang === "shebang");
|
||||
const env = await toolEnv(
|
||||
neededTools(fresh),
|
||||
input.path,
|
||||
fresh.root,
|
||||
lang === "python" || lang === "shebang",
|
||||
lang === "php" || lang === "shebang",
|
||||
);
|
||||
return produceContext(fresh, env);
|
||||
}
|
||||
|
||||
|
||||
@@ -226,6 +226,15 @@ describe("single-file producers (scratches)", () => {
|
||||
it("Ruby, PHP, Perl, Lua, R, Swift, Dart, Elixir, Scala CLI, Kotlin script", () => {
|
||||
expect(run(scratch("a.rb"))).toMatchObject({ command: "/bin/ruby", args: ["a.rb"] });
|
||||
expect(run(scratch("a.php"))).toMatchObject({ command: "/bin/php", args: ["a.php"] });
|
||||
// The PHP chosen in Settings wins over the PATH one, also with no PHP on PATH (#1555).
|
||||
const php81 = "/opt/homebrew/opt/[email protected]/bin/php";
|
||||
expect(run(scratch("a.php"), { ...ALL, php: php81 })).toMatchObject({ command: php81, args: ["a.php"] });
|
||||
expect(run(scratch("a.php"), env({}, { php: php81 }))).toMatchObject({ command: php81, args: ["a.php"] });
|
||||
expect(run(scratch("tool", "#!/usr/bin/env php\n<?php echo 1;"), { ...ALL, php: php81 })).toMatchObject({
|
||||
command: php81,
|
||||
args: ["tool"],
|
||||
});
|
||||
expect(produceContext(scratch("a.php"), env({}))!.missing!.body).toMatch(/Settings › Languages & Frameworks › PHP/);
|
||||
expect(run(scratch("a.pl"))).toMatchObject({ command: "/bin/perl" });
|
||||
expect(run(scratch("a.lua"))).toMatchObject({ command: "/bin/lua" });
|
||||
expect(run(scratch("a.R"))).toMatchObject({ command: "/bin/Rscript", args: ["a.R"] });
|
||||
|
||||
@@ -38,6 +38,8 @@ export interface ToolEnv {
|
||||
windows?: boolean;
|
||||
/** The project interpreter from settings (Python). */
|
||||
python?: string | null;
|
||||
/** The PHP interpreter chosen in settings (else the `php` on `PATH`). */
|
||||
php?: string | null;
|
||||
/** The project root has `deno.json(c)` / `bun.lock(b)`. */
|
||||
deno?: boolean;
|
||||
bun?: boolean;
|
||||
@@ -288,7 +290,7 @@ const INSTALL: Record<string, string> = {
|
||||
js: "Install Node.js from https://nodejs.org (or `brew install node`).",
|
||||
python: "Install Python (`brew install python`) or choose an interpreter in Settings › Python Interpreter.",
|
||||
ruby: "Install Ruby (`brew install ruby`).",
|
||||
php: "Install PHP (`brew install php`).",
|
||||
php: "Install PHP (`brew install php`) or choose an interpreter in Settings › Languages & Frameworks › PHP.",
|
||||
perl: "Install Perl (`brew install perl`).",
|
||||
lua: "Install Lua (`brew install lua`).",
|
||||
r: "Install R (`brew install r`) so that `Rscript` is on the PATH.",
|
||||
@@ -762,6 +764,8 @@ export function produceFile(input: ContextInput, env: ToolEnv): Produced | null
|
||||
config: fileConfig(s, "python", py.command, [...py.prefix, s.arg], "debugpy"),
|
||||
};
|
||||
}
|
||||
if (interp === "php" && env.php)
|
||||
return { name: s.file, scope: "file", config: fileConfig(s, "php", env.php, [...sb.slice(1), s.arg]) };
|
||||
const t = sb[0]!.startsWith("/") ? { command: sb[0]!, name: interp } : pick(env, [interp]);
|
||||
if (!t) return { name: s.file, scope: "file", missing: missing(lang, s.file, [interp]) };
|
||||
const kind = /^(ba|z|k|da|fi)?sh$/.test(interp) ? "shell" : interp === "node" ? "node" : interp;
|
||||
@@ -805,6 +809,8 @@ export function produceFile(input: ContextInput, env: ToolEnv): Produced | null
|
||||
// Sources roots go on the load path (`-Ilib`), as `rake test` does; paths are project-relative.
|
||||
return simple(lang, s, env, lang, () => [...(s.inProject ? rubyLoadPath(currentRoots()) : []), s.arg]);
|
||||
case "php":
|
||||
if (env.php) return { name: s.file, scope: "file", config: fileConfig(s, "php", env.php, [s.arg]) };
|
||||
return simple(lang, s, env, lang, () => [s.arg]);
|
||||
case "perl":
|
||||
case "lua":
|
||||
case "swift":
|
||||
|
||||
@@ -86,6 +86,14 @@ async function projectPython(): Promise<string | null> {
|
||||
}
|
||||
}
|
||||
|
||||
async function projectPhp(): Promise<string | null> {
|
||||
try {
|
||||
return await call(commands.sdkPhpEffective());
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function rootMarkers(root: string | null): Promise<{ deno: boolean; bun: boolean }> {
|
||||
if (!root) return { deno: false, bun: false };
|
||||
try {
|
||||
@@ -106,10 +114,12 @@ export async function toolEnv(
|
||||
file: string | null,
|
||||
root: string | null,
|
||||
python: boolean,
|
||||
php = false,
|
||||
): Promise<ToolEnv> {
|
||||
const [tools, py, markers] = await Promise.all([
|
||||
const [tools, py, phpInterpreter, markers] = await Promise.all([
|
||||
locateTools(names, file),
|
||||
python ? projectPython() : Promise.resolve(null),
|
||||
php ? projectPhp() : Promise.resolve(null),
|
||||
names.includes("deno") || names.includes("bun") ? rootMarkers(root) : Promise.resolve({ deno: false, bun: false }),
|
||||
]);
|
||||
return {
|
||||
@@ -117,6 +127,7 @@ export async function toolEnv(
|
||||
compileDir: compileDir ?? "/tmp/openidea-run",
|
||||
windows: isWindows(),
|
||||
python: py,
|
||||
php: phpInterpreter,
|
||||
...markers,
|
||||
};
|
||||
}
|
||||
@@ -78,7 +78,9 @@ describe("languages settings", () => {
|
||||
}
|
||||
expect(PHP_LANGUAGE_LEVELS[0]).toBe("");
|
||||
expect(PHP_LANGUAGE_LEVELS).toContain("5.6");
|
||||
expect(PHP_LANGUAGE_LEVELS.at(-1)).toBe("8.5");
|
||||
// Newest first after Auto (#1557).
|
||||
expect(PHP_LANGUAGE_LEVELS[1]).toBe("8.5");
|
||||
expect(PHP_LANGUAGE_LEVELS.at(-1)).toBe("5.6");
|
||||
});
|
||||
|
||||
it("finds the PHP page by its language level", () => {
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
* Build Tools › Maven: the toolchain each language's server and run configurations
|
||||
* use (applied by `ide-sdk` when language servers start and when run configurations load).
|
||||
*/
|
||||
import { useId, useMemo } from "react";
|
||||
import { useEffect, useId, useMemo, useState } from "react";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { IconButton, Input, type SelectOption } from "@/ui";
|
||||
import { PHP_LANGUAGE_LEVELS } from "@/platform/languageSettings";
|
||||
import { GlobListEditor, Row, Section, Select, Toggle } from "../components/Form";
|
||||
@@ -117,13 +118,31 @@ const PHP_LEVEL_OPTIONS: SelectOption[] = PHP_LANGUAGE_LEVELS.map((level) =>
|
||||
level ? { value: level, label: level } : { value: "", label: "Auto", detail: "from composer.json" },
|
||||
);
|
||||
|
||||
/** The `php` on `PATH` (what the Default interpreter runs), looked up while `enabled`. */
|
||||
function usePathPhp(enabled: boolean): string | null {
|
||||
const [path, setPath] = useState<string | null>(null);
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
let live = true;
|
||||
call(commands.sdkLocateTools(["php"], null))
|
||||
.then((r) => live && setPath(r.tools[0]?.path ?? null))
|
||||
.catch(() => {});
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
}, [enabled]);
|
||||
return path;
|
||||
}
|
||||
|
||||
export function PhpPage() {
|
||||
const [interpreter] = useSetting<string>("languages.php.interpreter");
|
||||
const [level, setLevel] = useSetting<string>("languages.php.languageLevel");
|
||||
const [includePaths, setIncludePaths] = useSetting<string[]>("languages.php.includePaths");
|
||||
const [stubs, setStubs] = useSetting<string[]>("languages.php.stubs");
|
||||
const { list } = useDetected("php");
|
||||
const selected = list.find((s) => s.path === interpreter) ?? (interpreter ? undefined : list[0]);
|
||||
const pathPhp = usePathPhp(!interpreter);
|
||||
// Default runs the `php` on PATH: the list is newest first, so it isn't necessarily `list[0]`.
|
||||
const selected = list.find((s) => s.path === (interpreter || pathPhp));
|
||||
return (
|
||||
<div className={styles.page}>
|
||||
<Section>
|
||||
|
||||
@@ -62,21 +62,21 @@ const DEFAULT_RUFF_FORMATTER: ExternalFormatterValid = {
|
||||
languages: ["python"],
|
||||
};
|
||||
|
||||
/** `languages.php.languageLevel` values; `""` = Auto (from `composer.json`). */
|
||||
/** `languages.php.languageLevel` values, newest first; `""` = Auto (from `composer.json`). */
|
||||
export const PHP_LANGUAGE_LEVELS = [
|
||||
"",
|
||||
"5.6",
|
||||
"7.0",
|
||||
"7.1",
|
||||
"7.2",
|
||||
"7.3",
|
||||
"7.4",
|
||||
"8.0",
|
||||
"8.1",
|
||||
"8.2",
|
||||
"8.3",
|
||||
"8.4",
|
||||
"8.5",
|
||||
"8.4",
|
||||
"8.3",
|
||||
"8.2",
|
||||
"8.1",
|
||||
"8.0",
|
||||
"7.4",
|
||||
"7.3",
|
||||
"7.2",
|
||||
"7.1",
|
||||
"7.0",
|
||||
"5.6",
|
||||
] as const;
|
||||
|
||||
export interface LanguagesValid {
|
||||
|
||||
Reference in new issue
Заблокувати користувача