@@ -5,7 +5,9 @@ use std::{
55 io:: { ErrorKind , Read , Write , stderr} ,
66 iter, mem,
77 path:: { Path , PathBuf } ,
8- sync:: { Arc , Mutex } ,
8+ process:: Child ,
9+ sync:: { Arc , Mutex , mpsc} ,
10+ thread:: JoinHandle ,
911 time:: Duration ,
1012} ;
1113
@@ -136,6 +138,9 @@ impl TsGoLintState {
136138 self
137139 }
138140
141+ /// Runs `tsgolint` on `paths` to completion. Equivalent to [`Self::start`] followed by
142+ /// [`TsGoLintRun::finish`].
143+ ///
139144 /// # Panics
140145 /// - when `stdin` of subprocess cannot be opened
141146 /// - when `stdout` of subprocess cannot be opened
@@ -152,15 +157,35 @@ impl TsGoLintState {
152157 diff_manager : & Arc < DiffManager > ,
153158 rule_timing_store : Option < & RuleTimingStore > ,
154159 ) -> Result < ( ) , String > {
160+ self . start ( paths) . finish (
161+ disable_directives_map,
162+ error_sender,
163+ file_system,
164+ diff_manager,
165+ rule_timing_store,
166+ )
167+ }
168+
169+ /// Spawns `tsgolint` for `paths` and decodes its output on a background thread, so it can
170+ /// run while the regular lint pass does.
171+ ///
172+ /// Nothing is reported until [`TsGoLintRun::finish`], which must run after the regular pass:
173+ /// diagnostics are filtered by the disable directives that pass collects. Spawn errors are
174+ /// reported by `finish` as well.
175+ ///
176+ /// # Panics
177+ /// - when `stdin` of subprocess cannot be opened
178+ /// - when `stdout` of subprocess cannot be opened
179+ pub fn start ( self , paths : & [ Arc < OsStr > ] ) -> TsGoLintRun {
155180 if paths. is_empty ( ) {
156- return Ok ( ( ) ) ;
181+ return TsGoLintRun { started : None } ;
157182 }
158183
159184 let mut resolved_configs: FxHashMap < PathBuf , ResolvedLinterState > = FxHashMap :: default ( ) ;
160185
161186 let json_input = self . json_input ( paths, None , & mut resolved_configs) ;
162187 if json_input. configs . is_empty ( ) {
163- return Ok ( ( ) ) ;
188+ return TsGoLintRun { started : None } ;
164189 }
165190
166191 let all_paths = {
@@ -174,29 +199,97 @@ impl TsGoLintState {
174199 paths_buff
175200 } ;
176201
177- let should_fix = self . fix || self . fix_suggestions ;
178- let cwd = self . cwd . clone ( ) ;
202+ let process = self . spawn_tsgolint ( & json_input) . map ( |mut child| {
203+ let stdout = child. stdout . take ( ) . expect ( "Failed to open tsgolint stdout" ) ;
204+ let ( sender, messages) = mpsc:: channel ( ) ;
205+ // Drain stdout as it is written so `tsgolint` never blocks on a full pipe. Message
206+ // processing stops at the first error, so stop reading there too.
207+ let reader = std:: thread:: spawn ( move || {
208+ for msg in TsGoLintMessageStream :: new ( stdout) {
209+ let is_error = !matches ! (
210+ msg,
211+ Ok ( TsGoLintMessage :: Diagnostic ( _) | TsGoLintMessage :: Timing ( _) )
212+ ) ;
213+ if sender. send ( msg) . is_err ( ) || is_error {
214+ break ;
215+ }
216+ }
217+ } ) ;
218+ TsGoLintProcess { child, messages, reader }
219+ } ) ;
220+
221+ TsGoLintRun {
222+ started : Some ( StartedRun { state : self , resolved_configs, all_paths, process } ) ,
223+ }
224+ }
225+ }
226+
227+ /// A `tsgolint` run started by [`TsGoLintState::start`].
228+ pub struct TsGoLintRun {
229+ /// `None` when there was nothing to lint.
230+ started : Option < StartedRun > ,
231+ }
232+
233+ struct StartedRun {
234+ state : TsGoLintState ,
235+ resolved_configs : FxHashMap < PathBuf , ResolvedLinterState > ,
236+ all_paths : Vec < PathBuf > ,
237+ /// The spawned process, or the error from spawning it.
238+ process : Result < TsGoLintProcess , String > ,
239+ }
240+
241+ struct TsGoLintProcess {
242+ child : Child ,
243+ /// Messages decoded from stdout by `reader`, in the order `tsgolint` wrote them.
244+ messages : mpsc:: Receiver < Result < TsGoLintMessage , String > > ,
245+ reader : JoinHandle < ( ) > ,
246+ }
247+
248+ impl TsGoLintRun {
249+ /// Waits for `tsgolint` to exit and reports its diagnostics, filtered by the disable
250+ /// directives that the regular lint pass collected, then applies its fixes.
251+ ///
252+ /// # Panics
253+ /// - when `tsgolint` process cannot be awaited
254+ ///
255+ /// # Errors
256+ /// A human-readable error message indicating why the linting failed.
257+ pub fn finish (
258+ mut self ,
259+ disable_directives_map : Arc < Mutex < FxHashMap < PathBuf , DisableDirectives > > > ,
260+ error_sender : DiagnosticSender ,
261+ file_system : & ( dyn crate :: RuntimeFileSystem + Sync + Send ) ,
262+ diff_manager : & Arc < DiffManager > ,
263+ rule_timing_store : Option < & RuleTimingStore > ,
264+ ) -> Result < ( ) , String > {
265+ let Some ( StartedRun { state, resolved_configs, all_paths, process } ) = self . started . take ( )
266+ else {
267+ return Ok ( ( ) ) ;
268+ } ;
269+
270+ let should_fix = state. fix || state. fix_suggestions ;
271+ let cwd = state. cwd . clone ( ) ;
179272 let sender_for_fixes = error_sender. clone ( ) ;
180273
181274 let diff_manager_clone_to_ts_go = Arc :: < DiffManager > :: clone ( diff_manager) ;
182275
183276 let handler = std:: thread:: spawn ( move || {
184- let mut child = self . spawn_tsgolint ( & json_input) ?;
185-
186- let stdout = child. stdout . take ( ) . expect ( "Failed to open tsgolint stdout" ) ;
277+ let TsGoLintProcess { mut child, messages, reader } = process?;
187278
188- // Process stdout stream in a separate thread to send diagnostics as they arrive
279+ // Process messages in a separate thread to send diagnostics as they arrive
189280 let stdout_handler = std:: thread:: spawn ( move || -> Result < TsGoLintOutput , String > {
190281 let disable_directives_map =
191282 disable_directives_map. lock ( ) . expect ( "disable_directives_map mutex poisoned" ) ;
192283
193- let mut diagnostic_handler =
194- DiagnosticHandler :: new ( self . cwd . clone ( ) , self . silent , should_fix, error_sender) ;
284+ let mut diagnostic_handler = DiagnosticHandler :: new (
285+ state. cwd . clone ( ) ,
286+ state. silent ,
287+ should_fix,
288+ error_sender,
289+ ) ;
195290 let mut timings = vec ! [ ] ;
196291
197- let msg_iter = TsGoLintMessageStream :: new ( stdout) ;
198-
199- for msg in msg_iter {
292+ for msg in messages {
200293 match msg {
201294 Ok ( TsGoLintMessage :: Error ( err) ) => {
202295 return Err ( err. error ) ;
@@ -260,6 +353,12 @@ impl TsGoLintState {
260353 }
261354 }
262355
356+ // The channel also closes when decoding panicked. Fail this thread then, as it
357+ // did when it decoded stdout itself.
358+ if let Err ( panic) = reader. join ( ) {
359+ std:: panic:: resume_unwind ( panic) ;
360+ }
361+
263362 Ok ( TsGoLintOutput {
264363 messages_requiring_fixes : diagnostic_handler
265364 . into_messages_requiring_fixes ( & diff_manager_clone_to_ts_go, all_paths) ,
@@ -356,7 +455,20 @@ impl TsGoLintState {
356455 Err ( err) => Err ( format ! ( "Error running tsgolint: {err:?}" ) ) ,
357456 }
358457 }
458+ }
359459
460+ impl Drop for TsGoLintRun {
461+ /// Stops `tsgolint` when the run is dropped without [`TsGoLintRun::finish`] (e.g. the regular
462+ /// pass unwound), so the process does not outlive the run.
463+ fn drop ( & mut self ) {
464+ if let Some ( StartedRun { process : Ok ( process) , .. } ) = & mut self . started {
465+ let _ = process. child . kill ( ) ;
466+ let _ = process. child . wait ( ) ;
467+ }
468+ }
469+ }
470+
471+ impl TsGoLintState {
360472 /// Spawn the tsgolint process with the given input.
361473 fn spawn_tsgolint ( & self , json_input : & Payload ) -> Result < std:: process:: Child , String > {
362474 let mut cmd = std:: process:: Command :: new ( & self . executable_path ) ;
0 commit comments