77@author: Richard Kellnberger
88"""
99import ast
10- import atexit
1110import collections
1211import logging
1312import os
@@ -660,10 +659,9 @@ def pylsp_code_actions(
660659 return actions
661660
662661
663- @atexit .register
664- def close () -> None :
662+ def close_tmpfile () -> None :
665663 """
666- Deltes the tempFile should it exist.
664+ Delete the tmpFile should it exist.
667665
668666 Returns
669667 -------
@@ -672,3 +670,66 @@ def close() -> None:
672670 """
673671 if tmpFile and tmpFile .name :
674672 os .unlink (tmpFile .name )
673+
674+
675+ def dmypy_stop (settings : dict [str , Any ]) -> None :
676+ """Possibly stop dmypy."""
677+ dmypy = settings .get ("dmypy" , False )
678+ if not dmypy :
679+ return
680+
681+ status_file = settings .get ("dmypy_status_file" , ".dmypy.json" )
682+ if not os .path .exists (status_file ):
683+ return
684+
685+ dmypy_command : list [str ] = get_cmd (settings , "dmypy" )
686+
687+ if dmypy_command :
688+ # dmypy exists on PATH or was provided by settings
689+ # -> use this dmypy
690+ completed_process = subprocess .run (
691+ [* dmypy_command , "--status-file" , status_file , "stop" ],
692+ capture_output = True ,
693+ ** windows_flag ,
694+ encoding = "utf-8" ,
695+ )
696+ output , errors = completed_process .stdout , completed_process .stderr
697+ exit_status = completed_process .returncode
698+ if exit_status != 0 :
699+ log .warning (
700+ "failed to stop dmypy via path; exit code: %d, message: %s" ,
701+ exit_status ,
702+ errors .strip (),
703+ )
704+ log .warning ("killing dmypy via path" )
705+ subprocess .run (
706+ [* dmypy_command , "--status-file" , status_file , "kill" ],
707+ capture_output = True ,
708+ ** windows_flag ,
709+ encoding = "utf-8" ,
710+ check = True ,
711+ )
712+ else :
713+ log .info ("dmypy stopped via path: %s" , output .strip ())
714+ else :
715+ # dmypy does not exist on PATH and was not provided by settings,
716+ # but must exist in the env pylsp-mypy is installed in
717+ # -> use dmypy via api
718+ output , errors , exit_status = mypy_api .run_dmypy (["--status-file" , status_file , "stop" ])
719+ if exit_status != 0 :
720+ log .warning (
721+ "failed to stop dmypy; exit code: %d, message: %s" ,
722+ exit_status ,
723+ errors .strip (),
724+ )
725+ log .warning ("killing dmypy" )
726+ mypy_api .run_dmypy (["--status-file" , status_file , "kill" ])
727+ else :
728+ log .info ("dmypy stopped: %s" , output .strip ())
729+
730+
731+ @hookimpl
732+ def pylsp_shutdown (config : Config , workspace : Workspace ) -> None :
733+ log .info ("shutdown requested" )
734+ close_tmpfile ()
735+ dmypy_stop (config .plugin_settings ("pylsp_mypy" ))
0 commit comments