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



commit 0b1fad285eaaa490844f20ba687ec919afdac946
Author: Veli Tasalı <veli tasali gmail com>
Date:   Sat Mar 19 16:20:38 2022 +0300

    plugin: stylelint: Migrate to IdeDiagnosticTool

 src/plugins/stylelint/stylelint_plugin.py | 88 ++++++-------------------------
 1 file changed, 15 insertions(+), 73 deletions(-)
---
diff --git a/src/plugins/stylelint/stylelint_plugin.py b/src/plugins/stylelint/stylelint_plugin.py
index 4bdd0d4eb..fdcbeef17 100644
--- a/src/plugins/stylelint/stylelint_plugin.py
+++ b/src/plugins/stylelint/stylelint_plugin.py
@@ -5,6 +5,7 @@
 #
 # Copyright 2017 Georg Vienna <georg vienna himbarsoft com>
 # Copyright 2017 Tobias Schönberg <tobias47n9e gmail 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
@@ -23,12 +24,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
@@ -39,65 +36,21 @@ SEVERITY_MAP = {
     "error": Ide.DiagnosticSeverity.ERROR
 }
 
+class StylelintDiagnosticProvider(Ide.DiagnosticTool):
+    def __init__(self, *args, **kwargs):
+        super().__init__(*args, **kwargs)
+        self.set_program_name('stylelint')
+        self.set_local_program_path(os.path.join('node_modules', '.bin', 'stylelint'))
 
-class StylelintDiagnosticProvider(Ide.Object, Ide.DiagnosticProvider):
-    @staticmethod
-    def _get_stylelint(srcdir):
-        local_stylelint = os.path.join(srcdir, 'node_modules', '.bin', 'stylelint')
-        if os.path.exists(local_stylelint):
-            return local_stylelint
+    def do_configure_launcher(self, launcher, file, contents):
+        launcher.push_args(('--formatter', 'json'))
+        if contents is not None:
+            launcher.push_args(('--stdin', '--stdin-filename=' + file.get_path()))
         else:
-            return 'stylelint'  # Just rely on PATH
+            launcher.push_argv(file.get_path())
 
-    def create_launcher(self):
-        context = self.get_context()
-        srcdir = context.ref_workdir().get_path()
-        launcher = None
-
-        if context.has_project():
-            build_manager = Ide.BuildManager.from_context(context)
-            pipeline = build_manager.get_pipeline()
-            if pipeline is not None:
-                srcdir = pipeline.get_srcdir()
-            runtime = pipeline.get_config().get_runtime()
-            launcher = runtime.create_launcher()
-
-        if launcher is None:
-            launcher = Ide.SubprocessLauncher.new(0)
-
-        launcher.set_flags(Gio.SubprocessFlags.STDIN_PIPE | Gio.SubprocessFlags.STDOUT_PIPE)
-        launcher.set_cwd(srcdir)
-
-        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='stylelint-thread').start()
-
-    def execute(self, task, launcher, srcdir, file, file_content):
+    def do_populate_diagnostics(self, diagnostics, file, stdout, stderr):
         try:
-            launcher.push_args((self._get_stylelint(srcdir), '--formatter', 'json'))
-
-            if file_content:
-                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('warnings', []):
@@ -108,20 +61,9 @@ class StylelintDiagnosticProvider(Ide.Object, Ide.DiagnosticProvider):
                     start = Ide.Location.new(file, start_line, start_col)
                     severity = SEVERITY_MAP[message['severity']]
                     diagnostic = Ide.Diagnostic.new(severity, message['text'], start)
-                    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 stylelint 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 stylelint json: {}'.format(e))
 
 
 class StylelintPreferencesAddin(GObject.Object, Ide.PreferencesAddin):


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