From 4dad1e360a270f2793937377b7875cebdb707a38 Mon Sep 17 00:00:00 2001 From: swlim9999 <350199194+swlim9999@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:15:41 +0800 Subject: [PATCH] Fix #144: completion uses the project's interpreter pylsp's Jedi used the Python that runs pylsp, so only packages of the plugin's own environment completed. Send plugins.jedi.environment with the project's interpreter (nbproject.python_path, Poetry, else a configured jedi.environment, else the default platform) when a server starts or restarts, when the project interpreter changes and when the LSP settings are saved. Missing interpreters and the default empty env_vars are not sent, because both break Jedi. Tests: PythonLspConfigurationTest, plus a real-pylsp integration test (-Dpython.lsp.test.executable). Co-Authored-By: Claude Opus 5.5 --- pom.xml | 1 + .../modules/python/PythonLspClient.java | 10 +- .../python/PythonLspConfiguration.java | 266 +++++++++++++ .../options/PythonLspServerConfigsPanel.java | 12 +- .../project/PythonProjectOpenedHook.java | 38 +- .../projectproperties/PythonGeneralPanel.java | 2 + .../python/PythonLspConfigurationTest.java | 360 ++++++++++++++++++ .../PythonLspInterpreterIntegrationTest.java | 140 +++++++ 8 files changed, 786 insertions(+), 43 deletions(-) create mode 100644 src/main/java/org/netbeans/modules/python/PythonLspConfiguration.java create mode 100644 src/test/java/org/netbeans/modules/python/PythonLspConfigurationTest.java create mode 100644 src/test/java/org/netbeans/modules/python/PythonLspInterpreterIntegrationTest.java diff --git a/pom.xml b/pom.xml index eece9e5..8b9ae98 100644 --- a/pom.xml +++ b/pom.xml @@ -314,6 +314,7 @@ true + ${project.build.directory}/test-userdir diff --git a/src/main/java/org/netbeans/modules/python/PythonLspClient.java b/src/main/java/org/netbeans/modules/python/PythonLspClient.java index cd87ffc..c2177da 100644 --- a/src/main/java/org/netbeans/modules/python/PythonLspClient.java +++ b/src/main/java/org/netbeans/modules/python/PythonLspClient.java @@ -5,6 +5,7 @@ */ import java.io.IOException; import org.netbeans.api.editor.mimelookup.MimeRegistration; +import org.netbeans.api.project.Project; import org.netbeans.modules.lsp.client.spi.LanguageServerProvider; import org.openide.util.Exceptions; import org.openide.util.Lookup; @@ -28,9 +29,16 @@ public LanguageServerDescription startServer(Lookup lkp) { ) .redirectError(ProcessBuilder.Redirect.INHERIT) .start(); - return LanguageServerDescription.create(p.getInputStream(), + LanguageServerDescription description = LanguageServerDescription.create(p.getInputStream(), p.getOutputStream(), p ); + try { + PythonLspConfiguration.serverStarted(lkp.lookup(Project.class), description); + } catch (RuntimeException | LinkageError ex) { + // The server still works, only without the project's interpreter. + Exceptions.printStackTrace(ex); + } + return description; } catch (IOException ex) { Exceptions.printStackTrace(ex); return null; diff --git a/src/main/java/org/netbeans/modules/python/PythonLspConfiguration.java b/src/main/java/org/netbeans/modules/python/PythonLspConfiguration.java new file mode 100644 index 0000000..99327ec --- /dev/null +++ b/src/main/java/org/netbeans/modules/python/PythonLspConfiguration.java @@ -0,0 +1,266 @@ +package org.netbeans.modules.python; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.ToNumberPolicy; +import com.google.gson.reflect.TypeToken; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Type; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; +import java.util.WeakHashMap; +import java.util.concurrent.ConcurrentHashMap; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.event.ChangeListener; +import org.eclipse.lsp4j.DidChangeConfigurationParams; +import org.netbeans.api.project.Project; +import org.netbeans.modules.lsp.client.LSPBindings; +import org.netbeans.modules.lsp.client.LanguageServerProviderAccessor; +import org.netbeans.modules.lsp.client.spi.LanguageServerProvider.LanguageServerDescription; +import org.netbeans.modules.python.project.PythonProject; +import org.openide.filesystems.FileObject; +import org.openide.util.Exceptions; +import org.openide.util.RequestProcessor; + +/** + * Sends pylsp its settings together with the interpreter of the project it + * serves, so that Jedi completes the packages installed in that interpreter + * instead of those of the plugin's own pylsp environment (#144). + */ +public final class PythonLspConfiguration { + + private static final Logger LOG = Logger.getLogger(PythonLspConfiguration.class.getName()); + private static final RequestProcessor WORKER = new RequestProcessor(PythonLspConfiguration.class.getName(), 1); + /** Running Python servers and the project each was started for (null for files outside projects). */ + private static final Map SERVERS = new WeakHashMap<>(); + /** Started servers that NetBeans has not initialized yet. */ + private static final Map PENDING = new ConcurrentHashMap<>(); + private static final Gson GSON = new GsonBuilder() + .setObjectToNumberStrategy(ToNumberPolicy.BIG_DECIMAL).create(); + private static final Type SETTINGS_TYPE = new TypeToken>() { + }.getType(); + + /** Held here because NetBeans keeps its change listeners only weakly. */ + private static final ChangeListener BINDINGS_LISTENER = event -> configurePendingServers(); + + static { + // NetBeans fires this after it has initialized a server and published its bindings. + LSPBindings.addChangeListener(BINDINGS_LISTENER); + } + + private PythonLspConfiguration() { + } + + /** Called by {@link PythonLspClient} for every start and restart of a server. */ + static void serverStarted(Project project, LanguageServerDescription description) { + PendingConfiguration pending = new PendingConfiguration(project); + PENDING.put(description, pending); + Process process = LanguageServerProviderAccessor.getINSTANCE().getProcess(description); + if (process != null) { + // Forget servers that exit, also those NetBeans never initialized. + process.onExit().thenRun(() -> { + PENDING.remove(description, pending); + LSPBindings bindings = pending.bindings; + if (bindings != null) { + synchronized (SERVERS) { + SERVERS.remove(bindings); + } + } + }); + } + } + + static void configurePendingServers() { + PENDING.forEach((description, pending) -> { + LSPBindings bindings = LanguageServerProviderAccessor.getINSTANCE().getBindings(description); + if (bindings != null && PENDING.remove(description, pending)) { + synchronized (SERVERS) { + pending.bindings = bindings; + Process process = LanguageServerProviderAccessor.getINSTANCE().getProcess(description); + if (process == null || process.isAlive()) { + SERVERS.put(bindings, pending.project); + } + } + WORKER.post(() -> { + try { + configure(bindings, pending.project, readSettings()); + } catch (IOException ex) { + Exceptions.printStackTrace(ex); + } + }); + } + }); + } + + /** Waits until the configuration posted so far has been sent; for tests. */ + static void waitForPendingUpdates() { + WORKER.post(() -> { }).waitFinished(); + } + + /** Sends the current interpreter to the running servers of a project, after its interpreter changed. */ + public static void configureProject(Project project) { + WORKER.post(() -> { + try { + Map settings = readSettings(); + running().forEach((bindings, server) -> { + if (server != null && server.getProjectDirectory().equals(project.getProjectDirectory())) { + configure(bindings, server, settings); + } + }); + } catch (IOException ex) { + Exceptions.printStackTrace(ex); + } + }); + } + + /** Sends changed global settings to all Python servers, each with its own project's interpreter. */ + public static void configureRunningServers(Map settings) { + WORKER.post(() -> running().forEach((bindings, project) -> configure(bindings, project, settings))); + } + + private static Map running() { + synchronized (SERVERS) { + return new HashMap<>(SERVERS); + } + } + + static void configure(LSPBindings bindings, Project project, Map settings) { + DidChangeConfigurationParams params = configuration(settings, interpreter(project, settings)); + try { + bindings.getWorkspaceService().didChangeConfiguration(params); + } catch (RuntimeException ex) { + // A server that has exited fails here; NetBeans starts and configures a new one when needed. + LOG.log(Level.FINE, "Cannot configure a Python language server", ex); + synchronized (SERVERS) { + SERVERS.remove(bindings); + } + } + } + + /** + * The interpreter Jedi should use: the one chosen for the project, else a + * {@code plugins.jedi.environment} set in the settings (returns null to keep + * it), else the default Python platform. Returns null for an interpreter + * that does not exist, because pylsp then fails every Jedi request. + */ + static String interpreter(Project project, Map settings) { + try { + String interpreter = projectInterpreter(project); + if (interpreter == null) { + if (configuredEnvironment(settings) != null) { + return null; + } + interpreter = PythonUtility.getPlatformPythonExe(); + } + if (interpreter == null || interpreter.isBlank()) { + return null; + } + if (!new File(interpreter).isFile()) { + LOG.log(Level.INFO, "Python interpreter {0} not found; completion uses the language server''s own" + + " environment", interpreter); + return null; + } + return interpreter; + } catch (IOException | RuntimeException ex) { + // For example a damaged platforms.json: keep pylsp's own environment. + Exceptions.printStackTrace(ex); + return null; + } + } + + /** The interpreter selected for the project, or null if none was selected. */ + static String projectInterpreter(Project project) throws IOException { + if (project == null) { + return null; + } + FileObject configuration = project.getProjectDirectory().getFileObject("nbproject/project.properties"); + if (configuration != null) { + Properties properties = new Properties(); + try (InputStream input = configuration.getInputStream()) { + properties.load(input); + } + String interpreter = properties.getProperty("nbproject.python_path"); + if (interpreter != null && !interpreter.isBlank()) { + return interpreter.strip(); + } + } + if (project instanceof PythonProject && PythonUtility.isPoetry((PythonProject) project)) { + String lspPython = PythonUtility.getLspPythonExe(); + String poetryPython = PythonUtility.getPoetryPythonPath(lspPython, project.getProjectDirectory()); + if (!poetryPython.equals(lspPython)) { + return poetryPython; + } + } + return null; + } + + /** + * The pylsp settings to send: the global settings with + * {@code plugins.jedi.environment} set to the given interpreter, if any. + * The global settings are not modified. + */ + static DidChangeConfigurationParams configuration(Map globalSettings, String interpreter) { + Map settings = new HashMap<>(globalSettings); + settings.remove("auto_pop_completion"); + Map plugins = copyMap(settings.get("plugins")); + Map jedi = copyMap(plugins.get("jedi")); + if (interpreter != null) { + jedi.put("environment", interpreter); + } + // The default settings have "env_vars": {}. Once an environment is set, + // Jedi starts its interpreter with exactly these variables, so an empty + // map would leave it without PATH, HOME or (on Windows) SYSTEMROOT. + // Without the key pylsp passes on its own environment. + if (jedi.get("env_vars") instanceof Map && ((Map) jedi.get("env_vars")).isEmpty()) { + jedi.remove("env_vars"); + } + if (!jedi.isEmpty()) { + plugins.put("jedi", jedi); + settings.put("plugins", plugins); + } + return new DidChangeConfigurationParams(Map.of("pylsp", settings)); + } + + private static Object configuredEnvironment(Map settings) { + Object environment = copyMap(copyMap(settings.get("plugins")).get("jedi")).get("environment"); + return environment instanceof String && !((String) environment).isBlank() ? environment : null; + } + + @SuppressWarnings("unchecked") + private static Map copyMap(Object value) { + return value instanceof Map ? new HashMap<>((Map) value) : new HashMap<>(); + } + + static Map readSettings() throws IOException { + String json; + if (PythonUtility.SETTINGS.isFile()) { + json = Files.readString(PythonUtility.SETTINGS.toPath()); + } else { + try (InputStream input = PythonLspConfiguration.class.getResourceAsStream("settings.json")) { + if (input == null) { + throw new IOException("Missing Python language server settings"); + } + json = new String(input.readAllBytes(), StandardCharsets.UTF_8); + } + } + Map settings = GSON.fromJson(json, SETTINGS_TYPE); + return settings == null ? Map.of() : settings; + } + + private static final class PendingConfiguration { + + final Project project; + /** Set once NetBeans has initialized the server; guarded by SERVERS. */ + LSPBindings bindings; + + PendingConfiguration(Project project) { + this.project = project; + } + } +} diff --git a/src/main/java/org/netbeans/modules/python/options/PythonLspServerConfigsPanel.java b/src/main/java/org/netbeans/modules/python/options/PythonLspServerConfigsPanel.java index 9a77cf9..1d558cc 100644 --- a/src/main/java/org/netbeans/modules/python/options/PythonLspServerConfigsPanel.java +++ b/src/main/java/org/netbeans/modules/python/options/PythonLspServerConfigsPanel.java @@ -25,9 +25,8 @@ import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import org.apache.commons.io.IOUtils; -import org.eclipse.lsp4j.DidChangeConfigurationParams; -import org.netbeans.modules.lsp.client.LSPBindings; import org.netbeans.modules.python.Installer; +import org.netbeans.modules.python.PythonLspConfiguration; import org.netbeans.modules.python.PythonUtility; import org.openide.util.Exceptions; import org.openide.util.NbPreferences; @@ -300,15 +299,10 @@ void store() { new TypeToken>() { }.getType()); if (settings != null) { - Map paramsObject = new HashMap<>(); NbPreferences.root().putBoolean("auto_pop_completion", (boolean) settings.getOrDefault("auto_pop_completion", true)); - settings.remove("auto_pop_completion"); - paramsObject.put("pylsp", settings); - DidChangeConfigurationParams params = new DidChangeConfigurationParams(paramsObject); - LSPBindings.getAllBindings().forEach(server -> { - server.getWorkspaceService().didChangeConfiguration(params); - }); + // Each server keeps its project's interpreter (#144). + PythonLspConfiguration.configureRunningServers(settings); } } catch (IOException ex) { Exceptions.printStackTrace(ex); diff --git a/src/main/java/org/netbeans/modules/python/project/PythonProjectOpenedHook.java b/src/main/java/org/netbeans/modules/python/project/PythonProjectOpenedHook.java index ccc84fa..3151dcc 100644 --- a/src/main/java/org/netbeans/modules/python/project/PythonProjectOpenedHook.java +++ b/src/main/java/org/netbeans/modules/python/project/PythonProjectOpenedHook.java @@ -1,20 +1,12 @@ package org.netbeans.modules.python.project; -import com.google.common.reflect.TypeToken; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.ToNumberPolicy; import java.io.File; import java.io.IOException; -import java.nio.file.Files; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.eclipse.lsp4j.DidChangeConfigurationParams; import org.netbeans.api.project.Project; import org.netbeans.api.project.ui.ProjectProblems; import org.netbeans.modules.lsp.client.LSPBindings; import org.netbeans.modules.parsing.api.indexing.IndexingManager; +import org.netbeans.modules.python.PythonLspConfiguration; import org.netbeans.modules.python.PythonUtility; import org.netbeans.spi.project.ui.ProjectOpenedHook; import org.openide.filesystems.FileObject; @@ -52,30 +44,10 @@ protected void projectOpened() { Exceptions.printStackTrace(ex); } - try { - LSPBindings.ensureServerRunning(project, PythonUtility.PYTHON_MIME_TYPE); - Gson create = new GsonBuilder() - .setObjectToNumberStrategy(ToNumberPolicy.BIG_DECIMAL).create(); - Map settings = create - .fromJson(Files.readString( - PythonUtility.SETTINGS.toPath()), - new TypeToken>() { - }.getType()); - if (settings != null) { - Map paramsObject = new HashMap<>(); - settings.remove("auto_pop_completion"); - paramsObject.put("pylsp", settings); - DidChangeConfigurationParams params = new DidChangeConfigurationParams(paramsObject); - List bindingsImpl = LSPBindings.getBindingsImpl(project, projectDir, - PythonUtility.PYTHON_MIME_TYPE); - for (LSPBindings lSPBindings : bindingsImpl) { - lSPBindings.getWorkspaceService() - .didChangeConfiguration(params); - } - } - } catch (IOException ex) { - Exceptions.printStackTrace(ex); - } + // A new server receives its settings and the project's interpreter once + // started; one that kept running gets them again here (#144). + LSPBindings.ensureServerRunning(project, PythonUtility.PYTHON_MIME_TYPE); + PythonLspConfiguration.configureProject(project); // GlobalPathRegistry.getDefault().register(ClassPath.SOURCE, new ClassPath[]{source}); if (ProjectProblems.isBroken(project)) { ProjectProblems.showAlert(project); diff --git a/src/main/java/org/netbeans/modules/python/projectproperties/PythonGeneralPanel.java b/src/main/java/org/netbeans/modules/python/projectproperties/PythonGeneralPanel.java index a38e757..92f9c60 100644 --- a/src/main/java/org/netbeans/modules/python/projectproperties/PythonGeneralPanel.java +++ b/src/main/java/org/netbeans/modules/python/projectproperties/PythonGeneralPanel.java @@ -11,6 +11,7 @@ import javax.swing.event.DocumentListener; import org.apache.commons.lang3.StringUtils; import org.javatuples.Quartet; +import org.netbeans.modules.python.PythonLspConfiguration; import org.netbeans.modules.python.PythonUtility; import org.netbeans.modules.python.options.PythonPlatformManager; import org.netbeans.modules.python.project.PythonProject; @@ -245,6 +246,7 @@ public static void setProperties(PythonProject project) { ? ((Pair) selectedItem).second().toString() : ""); prop.store(new FileWriter(FileUtil.toFile(project.getProjectDirectory() .getFileObject("nbproject/project.properties"))), null); + PythonLspConfiguration.configureProject(project); } catch (IOException ex) { Exceptions.printStackTrace(ex); } diff --git a/src/test/java/org/netbeans/modules/python/PythonLspConfigurationTest.java b/src/test/java/org/netbeans/modules/python/PythonLspConfigurationTest.java new file mode 100644 index 0000000..18e9c52 --- /dev/null +++ b/src/test/java/org/netbeans/modules/python/PythonLspConfigurationTest.java @@ -0,0 +1,360 @@ +package org.netbeans.modules.python; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.InputStream; +import java.io.OutputStream; +import java.lang.reflect.Constructor; +import java.lang.reflect.Proxy; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.concurrent.CompletableFuture; +import org.eclipse.lsp4j.DidChangeConfigurationParams; +import org.eclipse.lsp4j.DidChangeWatchedFilesParams; +import org.eclipse.lsp4j.InitializeResult; +import org.eclipse.lsp4j.ServerCapabilities; +import org.eclipse.lsp4j.services.LanguageServer; +import org.eclipse.lsp4j.services.WorkspaceService; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.netbeans.api.project.Project; +import org.netbeans.modules.lsp.client.LSPBindings; +import org.netbeans.modules.lsp.client.LanguageServerProviderAccessor; +import org.netbeans.modules.lsp.client.spi.LanguageServerProvider.LanguageServerDescription; +import org.openide.filesystems.FileObject; +import org.openide.filesystems.FileUtil; +import org.openide.util.Lookup; + +import static org.junit.Assert.*; + +/** Issue #144: pylsp must complete with the project's interpreter. */ +public class PythonLspConfigurationTest { + + /** Message lists of servers that behave as if they had exited. */ + private static final List> failing = new java.util.concurrent.CopyOnWriteArrayList<>(); + + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); + + @Test + public void configurationSetsTheInterpreterWithoutChangingTheGlobalSettings() { + Map global = Map.of("auto_pop_completion", true, + "plugins", Map.of("jedi", Map.of("extra_paths", List.of("shared sources")), + "jedi_completion", Map.of("enabled", true))); + + DidChangeConfigurationParams first = PythonLspConfiguration.configuration(global, "/first project/bin/python"); + DidChangeConfigurationParams second = PythonLspConfiguration.configuration(global, "C:\\second project\\python.exe"); + + assertEquals("/first project/bin/python", jedi(first).get("environment")); + assertEquals("C:\\second project\\python.exe", jedi(second).get("environment")); + assertEquals(List.of("shared sources"), jedi(first).get("extra_paths")); + assertEquals(Map.of("enabled", true), plugins(first).get("jedi_completion")); + assertFalse(settings(first).containsKey("auto_pop_completion")); + assertTrue(global.containsKey("auto_pop_completion")); + assertFalse(((Map) ((Map) global.get("plugins")).get("jedi")).containsKey("environment")); + } + + @Test + public void withoutAnInterpreterTheSettingsAreSentAsBefore() { + Map global = Map.of("plugins", Map.of("jedi", Map.of("environment", "/user choice/python"))); + assertEquals("/user choice/python", jedi(PythonLspConfiguration.configuration(global, null)).get("environment")); + assertEquals(Map.of("pylsp", Map.of()), PythonLspConfiguration.configuration(Map.of(), null).getSettings()); + } + + @Test + public void emptyEnvVarsOfTheDefaultSettingsAreNotSent() throws Exception { + Map defaults = PythonLspConfiguration.readSettings(); + assertEquals("The bundled settings.json has \"env_vars\": {}", Map.of(), + ((Map) ((Map) defaults.get("plugins")).get("jedi")).get("env_vars")); + Map jedi = jedi(PythonLspConfiguration.configuration(defaults, "/project/bin/python")); + assertFalse("Jedi would start the interpreter with no environment variables", jedi.containsKey("env_vars")); + assertEquals(List.of("numpy"), jedi.get("auto_import_modules")); + + Map custom = Map.of("plugins", Map.of("jedi", Map.of("env_vars", Map.of("A", "1")))); + assertEquals(Map.of("A", "1"), jedi(PythonLspConfiguration.configuration(custom, "/p/python")).get("env_vars")); + } + + @Test + public void projectInterpreterWinsOverTheSettingsAndDefault() throws Exception { + String python = interpreterFile("selected café interpreter with spaces"); + withDefaultPlatform(interpreterFile("default"), () -> { + Map userChoice = Map.of("plugins", Map.of("jedi", Map.of("environment", "/user/python"))); + assertEquals(python, PythonLspConfiguration.interpreter(project(python), userChoice)); + assertEquals(python, PythonLspConfiguration.interpreter(project(python), Map.of())); + }); + } + + @Test + public void withoutAProjectInterpreterTheSettingsThenTheDefaultPlatformAreUsed() throws Exception { + String defaultPython = interpreterFile("default"); + withDefaultPlatform(defaultPython, () -> { + Map userChoice = Map.of("plugins", Map.of("jedi", Map.of("environment", "/user/python"))); + assertNull("The environment in the settings is kept", PythonLspConfiguration.interpreter(project(""), userChoice)); + assertEquals(defaultPython, PythonLspConfiguration.interpreter(project(""), Map.of())); + assertEquals("Files outside projects", defaultPython, PythonLspConfiguration.interpreter(null, Map.of())); + Project withoutProperties = project(""); + withoutProperties.getProjectDirectory().getFileObject("nbproject/project.properties").delete(); + assertEquals(defaultPython, PythonLspConfiguration.interpreter(withoutProperties, Map.of())); + }); + } + + @Test + public void missingInterpreterIsNotSentBecauseJediWouldFailEveryRequest() throws Exception { + String deleted = temporaryFolder.getRoot().toPath().resolve("deleted venv/bin/python").toString(); + withDefaultPlatform(deleted, () -> { + assertNull(PythonLspConfiguration.interpreter(project(deleted), Map.of())); + assertNull(PythonLspConfiguration.interpreter(project(""), Map.of())); + assertNull("A folder is not an interpreter", + PythonLspConfiguration.interpreter(project(temporaryFolder.getRoot().toString()), Map.of())); + }); + } + + @Test + public void startedServerIsConfiguredOnceNetBeansHasInitializedIt() throws Exception { + String python = interpreterFile("first"); + List messages = new ArrayList<>(); + LanguageServerDescription description = description(); + PythonLspConfiguration.serverStarted(project(python), description); + PythonLspConfiguration.configurePendingServers(); + PythonLspConfiguration.waitForPendingUpdates(); + assertTrue("Nothing is sent before the server is initialized", messages.isEmpty()); + + LanguageServerProviderAccessor.getINSTANCE().setBindings(description, bindings(messages)); + PythonLspConfiguration.configurePendingServers(); + PythonLspConfiguration.waitForPendingUpdates(); + assertEquals(1, messages.size()); + assertEquals(python, jedi(messages.get(0)).get("environment")); + + PythonLspConfiguration.configurePendingServers(); + PythonLspConfiguration.waitForPendingUpdates(); + assertEquals("Startup configuration is sent once", 1, messages.size()); + } + + @Test + public void settingsAndInterpreterChangesKeepEachProjectsInterpreter() throws Exception { + String firstPython = interpreterFile("first"); + String secondPython = interpreterFile("second"); + String updatedPython = interpreterFile("updated first"); + Project firstProject = project(firstPython); + Project secondProject = project(secondPython); + List firstMessages = new ArrayList<>(); + List secondMessages = new ArrayList<>(); + start(firstProject, firstMessages); + start(secondProject, secondMessages); + + writeInterpreter(firstProject, updatedPython); + PythonLspConfiguration.configureProject(firstProject); + PythonLspConfiguration.waitForPendingUpdates(); + assertEquals(updatedPython, jedi(last(firstMessages)).get("environment")); + assertEquals("Another project's server is not touched", 1, secondMessages.size()); + + PythonLspConfiguration.configureRunningServers(Map.of("plugins", + Map.of("jedi_completion", Map.of("enabled", false)))); + PythonLspConfiguration.waitForPendingUpdates(); + assertEquals(updatedPython, jedi(last(firstMessages)).get("environment")); + assertEquals(secondPython, jedi(last(secondMessages)).get("environment")); + assertEquals(Map.of("enabled", false), plugins(last(firstMessages)).get("jedi_completion")); + + List restartMessages = new ArrayList<>(); + start(firstProject, restartMessages); + assertEquals("A restarted server gets the interpreter again", + updatedPython, jedi(restartMessages.get(0)).get("environment")); + } + + @Test + public void serverThatHasExitedDoesNotStopTheOthersFromBeingConfigured() throws Exception { + String python = interpreterFile("alive"); + List dead = new ArrayList<>(); + List alive = new ArrayList<>(); + start(project(python), dead); + start(project(python), alive); + dead.clear(); + alive.clear(); + failing.add(dead); + try { + PythonLspConfiguration.configureRunningServers(Map.of()); + PythonLspConfiguration.waitForPendingUpdates(); + PythonLspConfiguration.configureRunningServers(Map.of()); + PythonLspConfiguration.waitForPendingUpdates(); + } finally { + failing.removeIf(list -> list == dead); + } + assertEquals(2, alive.size()); + assertEquals("The exited server is forgotten after its first failure", 1, dead.size()); + } + + @Test + public void serverThatExitsAfterInitializationIsForgotten() throws Exception { + Process process = process(); + LanguageServerDescription description = LanguageServerDescription.create( + process.getInputStream(), process.getOutputStream(), process); + Project project = project(interpreterFile("exits later")); + List messages = new ArrayList<>(); + PythonLspConfiguration.serverStarted(project, description); + LanguageServerProviderAccessor.getINSTANCE().setBindings(description, bindings(messages)); + PythonLspConfiguration.configurePendingServers(); + PythonLspConfiguration.waitForPendingUpdates(); + assertEquals(1, messages.size()); + process.destroy(); + PythonLspConfiguration.configureProject(project); + PythonLspConfiguration.waitForPendingUpdates(); + assertEquals("An exited server gets no more settings", 1, messages.size()); + } + + @Test + public void damagedPlatformListFallsBackToTheServersOwnEnvironment() throws Exception { + Path platforms = PythonUtility.PLATFORMS.toPath(); + byte[] previous = Files.exists(platforms) ? Files.readAllBytes(platforms) : null; + try { + Files.createDirectories(platforms.getParent()); + Files.writeString(platforms, "[{\"cmd\": "); + assertNull(PythonLspConfiguration.interpreter(project(""), Map.of())); + } finally { + if (previous == null) { + Files.deleteIfExists(platforms); + } else { + Files.write(platforms, previous); + } + } + } + + @Test + public void serverThatExitsBeforeInitializationIsForgotten() throws Exception { + Process process = process(); + LanguageServerDescription description = LanguageServerDescription.create( + process.getInputStream(), process.getOutputStream(), process); + PythonLspConfiguration.serverStarted(project(interpreterFile("exited")), description); + process.destroy(); + List messages = new ArrayList<>(); + LanguageServerProviderAccessor.getINSTANCE().setBindings(description, bindings(messages)); + PythonLspConfiguration.configurePendingServers(); + PythonLspConfiguration.waitForPendingUpdates(); + assertTrue("A failed server must not receive startup configuration", messages.isEmpty()); + } + + private static Process process() { + CompletableFuture exited = new CompletableFuture<>(); + return new Process() { + @Override public InputStream getInputStream() { return InputStream.nullInputStream(); } + @Override public InputStream getErrorStream() { return InputStream.nullInputStream(); } + @Override public OutputStream getOutputStream() { return OutputStream.nullOutputStream(); } + @Override public int waitFor() { return 0; } + @Override public int exitValue() { return 0; } + @Override public boolean isAlive() { return !exited.isDone(); } + @Override public void destroy() { exited.complete(this); } + @Override public CompletableFuture onExit() { return exited; } + }; + } + + private void start(Project project, List messages) throws Exception { + LanguageServerDescription description = description(); + PythonLspConfiguration.serverStarted(project, description); + LanguageServerProviderAccessor.getINSTANCE().setBindings(description, bindings(messages)); + PythonLspConfiguration.configurePendingServers(); + PythonLspConfiguration.waitForPendingUpdates(); + } + + private interface Check { + void run() throws Exception; + } + + private static void withDefaultPlatform(String python, Check check) throws Exception { + Path platforms = PythonUtility.PLATFORMS.toPath(); + byte[] previous = Files.exists(platforms) ? Files.readAllBytes(platforms) : null; + try { + Files.createDirectories(platforms.getParent()); + Files.writeString(platforms, "[{\"cmd\":\"" + python.replace("\\", "\\\\") + "\",\"state\":\"true\"}]"); + check.run(); + } finally { + if (previous == null) { + Files.deleteIfExists(platforms); + } else { + Files.write(platforms, previous); + } + } + } + + private String interpreterFile(String name) throws Exception { + File file = new File(temporaryFolder.newFolder(name, "bin"), "python"); + assertTrue(file.createNewFile()); + return file.getPath(); + } + + private static Project project(String interpreter) throws Exception { + FileObject directory = FileUtil.createMemoryFileSystem().getRoot().createFolder("project"); + Project project = new Project() { + @Override public FileObject getProjectDirectory() { return directory; } + @Override public Lookup getLookup() { return Lookup.EMPTY; } + }; + writeInterpreter(project, interpreter); + return project; + } + + private static void writeInterpreter(Project project, String interpreter) throws Exception { + Properties properties = new Properties(); + properties.setProperty("nbproject.python_path", interpreter); + try (OutputStream output = FileUtil.createData(project.getProjectDirectory(), + "nbproject/project.properties").getOutputStream()) { + properties.store(output, null); + } + } + + private static LanguageServerDescription description() { + return LanguageServerDescription.create(new ByteArrayInputStream(new byte[0]), new ByteArrayOutputStream(), null); + } + + /** LSPBindings has a private constructor: (server, result, process) on NetBeans 29, plus a LanguageIdResolver on 31. */ + private static LSPBindings bindings(List messages) throws Exception { + WorkspaceService workspace = new WorkspaceService() { + @Override public void didChangeConfiguration(DidChangeConfigurationParams params) { + messages.add(params); + if (failing.stream().anyMatch(list -> list == messages)) { + // As lsp4j does when the server's stream is closed. + throw new IllegalStateException("server exited"); + } + } + @Override public void didChangeWatchedFiles(DidChangeWatchedFilesParams params) { } + }; + LanguageServer server = (LanguageServer) Proxy.newProxyInstance(LanguageServer.class.getClassLoader(), + new Class[]{LanguageServer.class}, (proxy, method, args) -> + "getWorkspaceService".equals(method.getName()) ? workspace : null); + for (Constructor constructor : LSPBindings.class.getDeclaredConstructors()) { + Class[] types = constructor.getParameterTypes(); + if (types.length >= 3 && types[0] == LanguageServer.class && types[1] == InitializeResult.class + && types[2] == Process.class) { + Object[] arguments = new Object[types.length]; + arguments[0] = server; + arguments[1] = new InitializeResult(new ServerCapabilities()); + constructor.setAccessible(true); + return (LSPBindings) constructor.newInstance(arguments); + } + } + throw new AssertionError(Arrays.toString(LSPBindings.class.getDeclaredConstructors())); + } + + private static DidChangeConfigurationParams last(List messages) { + return messages.get(messages.size() - 1); + } + + @SuppressWarnings("unchecked") + static Map settings(DidChangeConfigurationParams params) { + return (Map) ((Map) params.getSettings()).get("pylsp"); + } + + @SuppressWarnings("unchecked") + private static Map plugins(DidChangeConfigurationParams params) { + return (Map) settings(params).get("plugins"); + } + + @SuppressWarnings("unchecked") + private static Map jedi(DidChangeConfigurationParams params) { + return (Map) plugins(params).get("jedi"); + } +} diff --git a/src/test/java/org/netbeans/modules/python/PythonLspInterpreterIntegrationTest.java b/src/test/java/org/netbeans/modules/python/PythonLspInterpreterIntegrationTest.java new file mode 100644 index 0000000..7c8cc79 --- /dev/null +++ b/src/test/java/org/netbeans/modules/python/PythonLspInterpreterIntegrationTest.java @@ -0,0 +1,140 @@ +package org.netbeans.modules.python; + +import java.lang.reflect.Proxy; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import org.eclipse.lsp4j.ClientCapabilities; +import org.eclipse.lsp4j.CompletionItem; +import org.eclipse.lsp4j.CompletionParams; +import org.eclipse.lsp4j.DidOpenTextDocumentParams; +import org.eclipse.lsp4j.InitializeParams; +import org.eclipse.lsp4j.InitializedParams; +import org.eclipse.lsp4j.Position; +import org.eclipse.lsp4j.TextDocumentIdentifier; +import org.eclipse.lsp4j.TextDocumentItem; +import org.eclipse.lsp4j.jsonrpc.Launcher; +import org.eclipse.lsp4j.launch.LSPLauncher; +import org.eclipse.lsp4j.services.LanguageClient; +import org.eclipse.lsp4j.services.LanguageServer; +import org.junit.Assume; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import static org.junit.Assert.*; + +/** + * Issue #144 with a real pylsp. Run with + * -Dpython.lsp.test.executable=/absolute/path/to/python-with-pylsp. + */ +public class PythonLspInterpreterIntegrationTest { + + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); + + @Test + public void sharedServerCompletesLibraryInstalledOnlyInSelectedProjectEnvironment() throws Exception { + String serverPython = System.getProperty("python.lsp.test.executable"); + Assume.assumeTrue("Set python.lsp.test.executable to run the real pylsp integration test", + serverPython != null && !serverPython.isBlank()); + Path root = temporaryFolder.newFolder("project with spaces").toPath(); + Path environment = root.resolve("project environment"); + run(serverPython, "-m", "venv", "--without-pip", environment.toString()); + String projectPython = environment.resolve(System.getProperty("os.name").startsWith("Windows") + ? "Scripts/python.exe" : "bin/python").toString(); + Path packages = Path.of(run(projectPython, "-c", "import sysconfig; print(sysconfig.get_path('purelib'))").strip()); + Files.createDirectories(packages); + Files.writeString(packages.resolve("nb_project_only_library.py"), "project_only_symbol = 42\n"); + assertEquals("None", run(projectPython, "-c", "import importlib.util; print(importlib.util.find_spec('pylsp'))").strip()); + assertEquals("None", run(serverPython, "-c", "import importlib.util; print(importlib.util.find_spec('nb_project_only_library'))").strip()); + + Process process = new ProcessBuilder(serverPython, "-m", "pylsp") + .directory(root.toFile()).redirectError(root.resolve("pylsp.log").toFile()).start(); + Future listening = null; + LanguageServer server = null; + try { + LanguageClient client = (LanguageClient) Proxy.newProxyInstance(LanguageClient.class.getClassLoader(), + new Class[]{LanguageClient.class}, (proxy, method, args) -> + CompletableFuture.class.isAssignableFrom(method.getReturnType()) + ? CompletableFuture.completedFuture(null) : null); + Launcher launcher = LSPLauncher.createClientLauncher(client, + process.getInputStream(), process.getOutputStream()); + listening = launcher.startListening(); + server = launcher.getRemoteProxy(); + InitializeParams initialize = new InitializeParams(); + initialize.setRootUri(root.toUri().toString()); + initialize.setCapabilities(new ClientCapabilities()); + server.initialize(initialize).get(30, TimeUnit.SECONDS); + server.initialized(new InitializedParams()); + String source = "import nb_project_only_library\nnb_project_only_library.project_"; + String uri = root.resolve("lesson.py").toUri().toString(); + server.getTextDocumentService().didOpen(new DidOpenTextDocumentParams( + new TextDocumentItem(uri, "python", 1, source))); + CompletionParams completion = new CompletionParams(new TextDocumentIdentifier(uri), + new Position(1, "nb_project_only_library.project_".length())); + + Map defaults = PythonLspConfiguration.readSettings(); + server.getWorkspaceService().didChangeConfiguration(PythonLspConfiguration.configuration(defaults, null)); + assertFalse("Without the interpreter the server reproduces issue #144", + labels(server, completion).contains("project_only_symbol")); + server.getWorkspaceService().didChangeConfiguration( + PythonLspConfiguration.configuration(defaults, projectPython)); + assertTrue("Completion must find the selected interpreter's installed module", + labels(server, completion).contains("project_only_symbol")); + + server.getWorkspaceService().didChangeConfiguration( + PythonLspConfiguration.configuration(defaults, serverPython)); + assertFalse("Switching interpreters must stop using the previous environment", + labels(server, completion).contains("project_only_symbol")); + } finally { + if (server != null && process.isAlive()) { + try { + server.shutdown().get(5, TimeUnit.SECONDS); + server.exit(); + } catch (Exception ignored) { + // The process is still terminated below if startup or a request failed. + } + } + if (!process.waitFor(5, TimeUnit.SECONDS)) { + process.destroyForcibly(); + process.waitFor(5, TimeUnit.SECONDS); + } + if (listening != null) { + listening.cancel(true); + } + } + } + + private List labels(LanguageServer server, CompletionParams params) throws Exception { + var result = server.getTextDocumentService().completion(params).get(30, TimeUnit.SECONDS); + List items = result.isLeft() ? result.getLeft() : result.getRight().getItems(); + List labels = new ArrayList<>(); + for (CompletionItem item : items) { + labels.add(item.getLabel()); + } + return labels; + } + + private String run(String... command) throws Exception { + Path output = temporaryFolder.newFile().toPath(); + Process process = new ProcessBuilder(command).redirectErrorStream(true).redirectOutput(output.toFile()).start(); + try { + assertTrue("Python command timed out", process.waitFor(30, TimeUnit.SECONDS)); + String text = Files.readString(output, StandardCharsets.UTF_8); + assertEquals(text, 0, process.exitValue()); + return text; + } finally { + if (process.isAlive()) { + process.destroyForcibly(); + process.waitFor(5, TimeUnit.SECONDS); + } + } + } +}