[gnome-builder] plugin: eslint: Migrate to IdeDiagnosticTool



commit 8656bc76b0ac332752f56604bd14d3ec71e18293
Author: Veli Tasalı <veli tasali gmail com>
Date:   Sun Mar 20 19:44:33 2022 +0300

    plugin: eslint: Migrate to IdeDiagnosticTool

 src/plugins/eslint/eslint_plugin.py | 147 +++++-------------------------------
 1 file changed, 20 insertions(+), 127 deletions(-)
---
diff --git a/src/plugins/eslint/eslint_plugin.py b/src/plugins/eslint/eslint_plugin.py
index 6f3a55b71..073ba784c 100644
--- a/src/plugins/eslint/eslint_plugin.py
+++ b/src/plugins/eslint/eslint_plugin.py
@@ -4,6 +4,7 @@
 # __init__.py
 #
 # Copyright 2017 Georg Vienna <georg vienna himbarsoft com>
+# Copyright 2022 Veli Tasalı <me velitasali com>
 #
 # This program is free software: you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by
@@ -22,12 +23,8 @@
 import os
 import gi
 import json
-import threading
 
-from gi.repository import GLib
 from gi.repository import GObject
-from gi.repository import Gio
-from gi.repository import Gtk
 from gi.repository import Ide
 
 _ = Ide.gettext
@@ -41,116 +38,24 @@ SEVERITY_MAP = {
 # Comes from typescript-language-server
 BUNDLED_ESLINT = 
'/app/lib/yarn/global/node_modules/typescript-language-server/node_modules/eslint/bin/eslint.js'
 
-class ESLintDiagnosticProvider(Ide.Object, Ide.DiagnosticProvider):
-
-    def create_launcher(self):
-        flags = (Gio.SubprocessFlags.STDIN_PIPE | Gio.SubprocessFlags.STDOUT_PIPE | 
Gio.SubprocessFlags.STDERR_SILENCE)
-
-        context = self.get_context()
-        srcdir = context.ref_workdir().get_path()
-
-        build_manager = None
-        pipeline = None
-        launcher = None
-        host = None
-
-        # We prefer to use the eslint from the projeects node_modules
-        local_eslint = os.path.join(srcdir, 'node_modules', '.bin', 'eslint')
-
-        # If we have a project, use the pipeline to access the build container
-        if context.has_project():
-            build_manager = Ide.BuildManager.from_context(context)
-            pipeline = build_manager.get_pipeline()
-            host = Ide.RuntimeManager.from_context(context).get_runtime('host')
-            srcdir = pipeline.get_srcdir()
-
-        if os.path.exists(local_eslint):
-            # If we have a project, use the build container to execute
-            if pipeline is not None:
-                launcher = pipeline.create_launcher()
-                launcher.set_flags(flags)
-                launcher.set_cwd(srcdir)
-                launcher.push_argv(local_eslint)
-                return launcher
-
-            # There is no project, so just try to execute within the host
-            # environment since that is likely where things were installed
-            # and likely need access to host libraries/etc at known
-            # locations/paths.
-            if host is not None:
-                launcher = host.create_launcher()
-                launcher.set_flags(flags)
-            else:
-                launcher = Ide.SubprocessLauncher.new(flags)
-                launcher.set_run_on_host(True)
-            launcher.set_cwd(srcdir)
-            launcher.push_argv(local_eslint)
-            return launcher
-
-        # At this point we want to see if we can run 'eslint' on the host
-        # since the developer does not have eslint setup within their
-        # node_modules directory. We can only ensure this if a project
-        # is loaded, otherwise we'll have to fallback to something bundled.
-        if host is not None and host.contains_program_in_path('eslint', None):
-            launcher = host.create_launcher()
-            launcher.set_flags(flags)
-            launcher.set_cwd(srcdir)
-            launcher.push_argv('eslint')
-            return launcher
-
-        # We can hit this if we're not running in Flatpak or if we
-        # have eslint bundled (we do but not in $PATH under flatpak).
-        if GLib.find_program_in_path('eslint'):
-            launcher = Ide.SubprocessLauncher.new(flags)
-            launcher.set_cwd(srcdir)
-            launcher.push_argv('eslint')
-            return launcher
-
-        # Okay, last resort. Try to get this thing working from our
-        # bundled typescript-language-server.
-        if os.path.exists('/.flatpak-info'):
-            launcher = Ide.SubprocessLauncher.new(flags)
-            launcher.set_cwd(srcdir)
-            launcher.push_argv(BUNDLED_ESLINT)
-            return launcher
-
-        # Meh, not much hope, but give a launcher anyway
-        launcher = Ide.SubprocessLauncher.new(flags)
-        launcher.set_cwd(srcdir)
-        launcher.push_argv('eslint')
-        return launcher
-
-    def do_diagnose_async(self, file, file_content, lang_id, cancellable, callback, user_data):
-        self.diagnostics_list = []
-        task = Gio.Task.new(self, cancellable, callback)
-        task.diagnostics_list = []
-
-        launcher = self.create_launcher()
-        srcdir = launcher.get_cwd()
-
-        threading.Thread(target=self.execute, args=(task, launcher, srcdir, file, file_content),
-                         name='eslint-thread').start()
+class ESLintDiagnosticProvider(Ide.DiagnosticTool):
+    def __init__(self, *args, **kwargs):
+        super().__init__(*args, **kwargs)
+        self.set_program_name('eslint')
+        self.set_bundled_program_path(BUNDLED_ESLINT)
+        self.set_local_program_path(os.path.join('node_modules', '.bin', 'eslint'))
+
+    def do_configure_launcher(self, launcher, file, contents):
+        launcher.push_args(('-f', 'json',
+            '--ignore-pattern', '!node_modules/*',
+            '--ignore-pattern', '!bower_components/*'))
+        if contents is not None:
+            launcher.push_args(('--stdin', '--stdin-filename=' + file.get_path()))
+        else:
+            launcher.push_argv(file.get_path())
 
-    def execute(self, task, launcher, srcdir, file, file_content):
+    def do_populate_diagnostics(self, diagnostics, file, stdout, stderr):
         try:
-            launcher.push_args(('-f', 'json',
-                                '--ignore-pattern', '!node_modules/*',
-                                '--ignore-pattern', '!bower_components/*'))
-
-            if file_content:
-                launcher.push_argv('--stdin')
-                launcher.push_argv('--stdin-filename=' + file.get_path())
-            else:
-                launcher.push_argv(file.get_path())
-
-            sub_process = launcher.spawn()
-            stdin = file_content.get_data().decode('UTF-8')
-            success, stdout, stderr = sub_process.communicate_utf8(stdin, None)
-
-            if not success:
-                task.return_boolean(False)
-                return
-
             results = json.loads(stdout)
             for result in results:
                 for message in result.get('messages', []):
@@ -177,21 +82,9 @@ class ESLintDiagnosticProvider(Ide.Object, Ide.DiagnosticProvider):
                         # fixit = Ide.Fixit.new(range_, message['fix']['text'])
                         # diagnostic.take_fixit(fixit)
 
-                    task.diagnostics_list.append(diagnostic)
-        except GLib.Error as err:
-            task.return_error(err)
-        except (json.JSONDecodeError, UnicodeDecodeError, IndexError) as e:
-            task.return_error(GLib.Error('Failed to decode eslint json: {}'.format(e)))
-        else:
-            task.return_boolean(True)
-
-    def do_diagnose_finish(self, result):
-        if result.propagate_boolean():
-            diagnostics = Ide.Diagnostics()
-            for diag in result.diagnostics_list:
-                diagnostics.add(diag)
-            return diagnostics
-
+                    diagnostics.add(diagnostic)
+        except Exception as e:
+            Ide.warning('Failed to decode eslint json: {}'.format(e))
 
 class ESLintPreferencesAddin(GObject.Object, Ide.PreferencesAddin):
     def do_load(self, preferences):


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]