-
-
Notifications
You must be signed in to change notification settings - Fork 951
Expand file tree
/
Copy pathtsgolint.rs
More file actions
1593 lines (1416 loc) · 57.8 KB
/
tsgolint.rs
File metadata and controls
1593 lines (1416 loc) · 57.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::{
borrow::Cow,
collections::BTreeSet,
ffi::OsStr,
io::{ErrorKind, Read, Write, stderr},
iter, mem,
path::{Path, PathBuf},
sync::{Arc, Mutex},
};
use oxc_allocator::Allocator;
use rustc_hash::FxHashMap;
use serde::{Deserialize, Serialize};
use oxc_diagnostics::{DiagnosticSender, DiagnosticService, OxcDiagnostic, Severity};
use oxc_span::{SourceType, Span};
use super::{AllowWarnDeny, ConfigStore, DisableDirectives, ResolvedLinterState, read_to_string};
use crate::{CompositeFix, FixKind, Fixer, Message, PossibleFixes, WEBSITE_BASE_RULES_URL};
/// State required to initialize the `tsgolint` linter.
#[derive(Debug, Clone)]
pub struct TsGoLintState {
/// The path to the `tsgolint` executable (at least our best guess at it).
executable_path: PathBuf,
/// Current working directory, used for rendering paths in diagnostics.
cwd: PathBuf,
/// The configuration store for `tsgolint` (used to resolve configurations outside of `oxc_linter`)
config_store: ConfigStore,
/// If `oxlint` will output the diagnostics or not.
/// When `silent` is true, we do not need to access the file system for nice diagnostics messages.
silent: bool,
/// If `true`, request that fixes be returned from `tsgolint`.
fix: bool,
/// If `true`, request that suggestions be returned from `tsgolint`.
fix_suggestions: bool,
/// If `true`, include TypeScript compiler syntactic and semantic diagnostics.
type_check: bool,
}
impl TsGoLintState {
pub fn new(cwd: &Path, config_store: ConfigStore, fix_kind: FixKind) -> Self {
let executable_path =
try_find_tsgolint_executable(cwd).unwrap_or(PathBuf::from("tsgolint"));
TsGoLintState {
config_store,
executable_path,
cwd: cwd.to_path_buf(),
silent: false,
fix: fix_kind.contains(FixKind::Fix),
fix_suggestions: fix_kind.contains(FixKind::Suggestion),
type_check: false,
}
}
/// Try to create a new TsGoLintState, returning an error if the executable cannot be found.
///
/// # Errors
/// Returns an error if the tsgolint executable cannot be found.
pub fn try_new(
cwd: &Path,
config_store: ConfigStore,
fix_kind: FixKind,
) -> Result<Self, String> {
let executable_path = try_find_tsgolint_executable(cwd)?;
Ok(TsGoLintState {
config_store,
executable_path,
cwd: cwd.to_path_buf(),
silent: false,
fix: fix_kind.contains(FixKind::Fix),
fix_suggestions: fix_kind.contains(FixKind::Suggestion),
type_check: false,
})
}
/// Set to `true` to skip file system reads.
/// When `silent` is true, we do not need to access the file system for nice diagnostics messages.
///
/// Default is `false`.
#[must_use]
pub fn with_silent(mut self, yes: bool) -> Self {
self.silent = yes;
self
}
/// Set to `true` to include TypeScript compiler syntactic and semantic diagnostics.
///
/// Default is `false`.
#[must_use]
pub fn with_type_check(mut self, yes: bool) -> Self {
self.type_check = yes;
self
}
/// # Panics
/// - when `stdin` of subprocess cannot be opened
/// - when `stdout` of subprocess cannot be opened
/// - when `tsgolint` process cannot be awaited
///
/// # Errors
/// A human-readable error message indicating why the linting failed.
pub fn lint(
self,
paths: &[Arc<OsStr>],
disable_directives_map: Arc<Mutex<FxHashMap<PathBuf, DisableDirectives>>>,
error_sender: DiagnosticSender,
file_system: &(dyn crate::RuntimeFileSystem + Sync + Send),
) -> Result<(), String> {
if paths.is_empty() {
return Ok(());
}
let mut resolved_configs: FxHashMap<PathBuf, ResolvedLinterState> = FxHashMap::default();
let json_input = self.json_input(paths, None, &mut resolved_configs);
if json_input.configs.is_empty() {
return Ok(());
}
let should_fix = self.fix || self.fix_suggestions;
let cwd = self.cwd.clone();
let sender_for_fixes = error_sender.clone();
let handler = std::thread::spawn(move || {
let mut child = self.spawn_tsgolint(&json_input)?;
let stdout = child.stdout.take().expect("Failed to open tsgolint stdout");
// Process stdout stream in a separate thread to send diagnostics as they arrive
let stdout_handler = std::thread::spawn(
move || -> Result<Vec<(PathBuf, String, Vec<Message>)>, String> {
let disable_directives_map = disable_directives_map
.lock()
.expect("disable_directives_map mutex poisoned");
let mut diagnostic_handler = DiagnosticHandler::new(
self.cwd.clone(),
self.silent,
should_fix,
error_sender,
);
let msg_iter = TsGoLintMessageStream::new(stdout);
for msg in msg_iter {
match msg {
Ok(TsGoLintMessage::Error(err)) => {
return Err(err.error);
}
Ok(TsGoLintMessage::Diagnostic(tsgolint_diagnostic)) => {
match tsgolint_diagnostic {
TsGoLintDiagnostic::Rule(tsgolint_diagnostic) => {
let path = &tsgolint_diagnostic.file_path;
let severity = resolved_configs
.get(path)
.or_else(|| {
debug_assert!(false, "resolved_configs should have an entry for every file we linted {tsgolint_diagnostic:?}");
None
})
.and_then(|resolved_config| {
resolved_config
.rules
.iter()
.find(|(rule, _)| {
rule.name() == tsgolint_diagnostic.rule
})
.map(|(_, status)| *status)
})
.or_else(|| {
debug_assert!(false, "resolved_config should have a matching rule for every diagnostic we received {tsgolint_diagnostic:?}");
None
});
let Some(severity) = severity else {
// If the severity is not found, we should not report
// the diagnostic
continue;
};
if should_skip_diagnostic(
&disable_directives_map,
path,
&tsgolint_diagnostic,
) {
continue;
}
diagnostic_handler
.handle_rule_diagnostic(tsgolint_diagnostic, severity);
}
TsGoLintDiagnostic::Internal(e) => {
diagnostic_handler.handle_internal_diagnostic(e);
}
}
}
Err(e) => {
return Err(e);
}
}
}
Ok(diagnostic_handler.into_messages_requiring_fixes())
},
);
// Wait for process to complete and stdout processing to finish
let exit_status = child.wait().expect("Failed to wait for tsgolint process");
let stdout_result = stdout_handler.join();
if !exit_status.success() {
return Err(
if let Some(err) = &stdout_result.ok().and_then(std::result::Result::err) {
format!("exit status: {exit_status}, error: {err}")
} else {
format!("exit status: {exit_status}")
},
);
}
match stdout_result {
Ok(Ok(messages)) => Ok(messages),
Ok(Err(err)) => Err(format!("exit status: {exit_status}, error: {err}")),
Err(_) => Err("Failed to join stdout processing thread".to_string()),
}
});
match handler.join() {
Ok(Ok(messages_requiring_fixes)) => {
for (path, source_text, messages) in messages_requiring_fixes {
let source_type = SourceType::from_path(&path)
.ok()
.map(|st| if st.is_javascript() { st.with_jsx(true) } else { st });
let fix_result = Fixer::new(&source_text, messages, source_type).fix();
if fix_result.fixed {
file_system
.write_file(&path, &fix_result.fixed_code)
.expect("Failed to write fixed file");
}
if !fix_result.messages.is_empty() {
let source_for_diagnostics: &str =
if fix_result.fixed { &fix_result.fixed_code } else { &source_text };
let diagnostics = DiagnosticService::wrap_diagnostics(
&cwd,
&path,
source_for_diagnostics,
fix_result.messages.into_iter().map(Into::into).collect(),
);
sender_for_fixes.send(diagnostics).expect("Failed to send diagnostics");
}
}
Ok(())
}
Ok(Err(err)) => Err(format!("Error running tsgolint: {err:?}")),
Err(err) => Err(format!("Error running tsgolint: {err:?}")),
}
}
/// Spawn the tsgolint process with the given input.
fn spawn_tsgolint(&self, json_input: &Payload) -> Result<std::process::Child, String> {
let mut cmd = std::process::Command::new(&self.executable_path);
cmd.arg("headless")
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(stderr());
if self.fix {
cmd.arg("-fix");
}
if self.fix_suggestions {
cmd.arg("-fix-suggestions");
}
if let Ok(trace_file) = std::env::var("OXLINT_TSGOLINT_TRACE") {
cmd.arg(format!("-trace={trace_file}"));
}
if let Ok(cpuprof_file) = std::env::var("OXLINT_TSGOLINT_CPU") {
cmd.arg(format!("-cpuprof={cpuprof_file}"));
}
if let Ok(heap_file) = std::env::var("OXLINT_TSGOLINT_HEAP") {
cmd.arg(format!("-heap={heap_file}"));
}
if let Ok(allocs_file) = std::env::var("OXLINT_TSGOLINT_ALLOCS") {
cmd.arg(format!("-allocs={allocs_file}"));
}
let mut child = match cmd.spawn() {
Ok(c) => c,
Err(e) => {
return Err(format!(
"Failed to spawn tsgolint from path `{}`, with error: {e}",
self.executable_path.display()
));
}
};
let mut stdin = child.stdin.take().expect("Failed to open tsgolint stdin");
let json = serde_json::to_string(json_input).expect("Failed to serialize JSON");
if let Err(e) = stdin.write_all(json.as_bytes())
&& e.kind() != ErrorKind::BrokenPipe
{
return Err(format!("Failed to write to tsgolint stdin: {e}"));
}
drop(stdin);
Ok(child)
}
/// # Panics
/// - when `stdin` of subprocess cannot be opened
/// - when `stdout` of subprocess cannot be opened
/// - when `tsgolint` process cannot be awaited
///
/// # Errors
/// A human-readable error message indicating why the linting failed.
pub fn lint_source(
&self,
paths: &[Arc<OsStr>],
file_system: &(dyn crate::RuntimeFileSystem + Sync + Send),
disable_directives_map: Arc<Mutex<FxHashMap<PathBuf, DisableDirectives>>>,
) -> Result<Vec<Message>, String> {
if paths.is_empty() {
return Ok(vec![]);
}
let mut resolved_configs: FxHashMap<PathBuf, ResolvedLinterState> = FxHashMap::default();
let mut source_overrides: FxHashMap<String, String> = FxHashMap::default();
let allocator = Allocator::default();
// Read all sources into overrides
for path in paths {
let path_ref = Path::new(path.as_ref());
let Ok(source_text) = file_system.read_to_arena_str(path_ref, &allocator) else {
return Err(format!(
"Failed to read source text for file: {}",
path.to_string_lossy()
));
};
source_overrides.insert(path.to_string_lossy().to_string(), source_text.to_string());
}
let json_input =
self.json_input(paths, Some(source_overrides.clone()), &mut resolved_configs);
// Get the file name of the first path for internal diagnostic filtering
let path_file_name =
Path::new(paths[0].as_ref()).file_name().unwrap_or_default().to_os_string();
let mut child = self.spawn_tsgolint(&json_input)?;
let handler = std::thread::spawn(move || {
let stdout = child.stdout.take().expect("Failed to open tsgolint stdout");
let stdout_handler = std::thread::spawn(move || -> Result<Vec<Message>, String> {
let disable_directives_map =
disable_directives_map.lock().expect("disable_directives_map mutex poisoned");
let msg_iter = TsGoLintMessageStream::new(stdout);
let mut result = vec![];
for msg in msg_iter {
match msg {
Ok(TsGoLintMessage::Error(err)) => {
return Err(err.error);
}
Ok(TsGoLintMessage::Diagnostic(tsgolint_diagnostic)) => {
match tsgolint_diagnostic {
TsGoLintDiagnostic::Rule(tsgolint_diagnostic) => {
let path = tsgolint_diagnostic.file_path.clone();
let Some(resolved_config) = resolved_configs.get(&path) else {
// If we don't have a resolved config for this path, skip it. We should always
// have a resolved config though, since we processed them already above.
continue;
};
let severity =
resolved_config.rules.iter().find_map(|(rule, status)| {
if rule.name() == tsgolint_diagnostic.rule {
Some(*status)
} else {
None
}
});
let Some(severity) = severity else {
// If the severity is not found, we should not report the diagnostic
continue;
};
if should_skip_diagnostic(
&disable_directives_map,
&path,
&tsgolint_diagnostic,
) {
continue;
}
// Use the corresponding source override text
let Some(source_text_owned) = source_overrides
.get(&path.to_string_lossy().to_string())
.cloned()
else {
// should never happen, because we populated source_overrides above
continue;
};
let mut message = Message::from_tsgo_lint_diagnostic(
tsgolint_diagnostic,
&source_text_owned,
);
message.error.severity = if severity == AllowWarnDeny::Deny {
Severity::Error
} else {
Severity::Warning
};
result.push(message);
}
TsGoLintDiagnostic::Internal(e) => {
let span = e
.file_path
.as_ref()
.is_some_and(|f| {
f.file_name().unwrap_or_default() == path_file_name
})
.then_some(e.span)
.flatten()
.unwrap_or_default();
let mut diagnostic: OxcDiagnostic = e.into();
diagnostic = diagnostic.with_label(span);
result.push(Message::new(diagnostic, PossibleFixes::None));
}
}
}
Err(e) => {
return Err(e);
}
}
}
Ok(result)
});
// Wait for process to complete and stdout processing to finish
let exit_status = child.wait().expect("Failed to wait for tsgolint process");
let stdout_result = stdout_handler.join();
if !exit_status.success() {
let err_msg = stdout_result.ok().and_then(Result::err).unwrap_or_default();
return Err(format!(
"tsgolint process exited with status: {exit_status}, {err_msg}"
));
}
match stdout_result {
Ok(Ok(diagnostics)) => Ok(diagnostics),
Ok(Err(err)) => Err(err),
Err(_) => Err("Failed to join stdout processing thread".to_string()),
}
});
match handler.join() {
Ok(Ok(diagnostics)) => {
// Successfully ran tsgolint
Ok(diagnostics)
}
Ok(Err(err)) => Err(format!("Error running tsgolint: {err:?}")),
Err(err) => Err(format!("Error running tsgolint: {err:?}")),
}
}
/// Create a JSON input for STDIN of tsgolint in this format:
///
/// ```json
/// {
/// "files": [
/// {
/// "file_path": "/absolute/path/to/file.ts",
/// "rules": ["rule-1", "another-rule"]
/// }
/// ]
/// }
/// ```
#[inline]
fn json_input(
&self,
paths: &[Arc<OsStr>],
source_overrides: Option<FxHashMap<String, String>>,
resolved_configs: &mut FxHashMap<PathBuf, ResolvedLinterState>,
) -> Payload {
let mut config_groups: FxHashMap<BTreeSet<Rule>, Vec<String>> = FxHashMap::default();
for path in paths {
if SourceType::from_path(Path::new(path)).is_ok() {
let path_buf = PathBuf::from(path);
let file_path = path.to_string_lossy().to_string();
let resolved_config = resolved_configs
.entry(path_buf.clone())
.or_insert_with(|| self.config_store.resolve(&path_buf));
let rules: BTreeSet<Rule> = resolved_config
.rules
.iter()
.filter_map(|(rule, status)| {
if status.is_warn_deny() && rule.is_tsgolint_rule() {
let rule_name = rule.name().to_string();
let options = match rule.to_configuration() {
Some(Ok(config)) => Some(config),
Some(Err(_)) | None => None,
};
Some(Rule { name: rule_name, options })
} else {
None
}
})
.collect();
config_groups.entry(rules).or_default().push(file_path);
}
}
Payload {
version: 2,
configs: config_groups
.into_iter()
.map(|(rules, file_paths)| Config {
file_paths,
rules: rules.into_iter().collect(),
})
.collect(),
source_overrides,
report_syntactic: self.type_check,
report_semantic: self.type_check,
}
}
}
/// Represents the input JSON to `tsgolint`, like:
///
/// ```json
/// {
/// "version": 2,
/// "configs": [
/// {
/// "file_paths": ["/absolute/path/to/file.ts", "/another/file.ts"],
/// "rules": [
/// { "name": "rule-1" },
/// { "name": "another-rule" },
/// ]
/// }
/// ]
/// }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Payload {
pub version: i32,
pub configs: Vec<Config>,
pub source_overrides: Option<FxHashMap<String, String>>,
pub report_syntactic: bool,
pub report_semantic: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
/// Absolute path to the file to lint
pub file_paths: Vec<String>,
/// List of rules to apply to this file
/// Example: `["no-floating-promises"]`
pub rules: Vec<Rule>,
}
#[derive(Debug, Clone, Serialize, Deserialize, Hash, Eq, PartialEq)]
pub struct Rule {
pub name: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub options: Option<serde_json::Value>,
}
impl PartialOrd for Rule {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Rule {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
// First compare by name
match self.name.cmp(&other.name) {
std::cmp::Ordering::Equal => {
// If names are equal, compare by serialized options
// Serialize to canonical JSON string for comparison
let self_options = self.options.as_ref().map(|v| serde_json::to_string(v).ok());
let other_options = other.options.as_ref().map(|v| serde_json::to_string(v).ok());
self_options.cmp(&other_options)
}
other_ordering => other_ordering,
}
}
}
/// Diagnostic kind discriminator
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum DiagnosticKind {
Rule = 0,
Internal = 1,
}
impl Serialize for DiagnosticKind {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_u8(*self as u8)
}
}
impl<'de> Deserialize<'de> for DiagnosticKind {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let value = u8::deserialize(deserializer)?;
match value {
0 => Ok(DiagnosticKind::Rule),
1 => Ok(DiagnosticKind::Internal),
_ => Err(serde::de::Error::custom(format!("Invalid DiagnosticKind value: {value}"))),
}
}
}
/// Represents the raw output binary data from `tsgolint`.
#[derive(Debug, Clone, Serialize, Deserialize)]
struct TsGoLintDiagnosticPayload {
pub kind: DiagnosticKind,
pub range: Option<Range>,
pub message: RuleMessage,
pub file_path: Option<String>,
// Only for kind="rule"
#[serde(skip_serializing_if = "Option::is_none")]
pub rule: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub fixes: Vec<Fix>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub suggestions: Vec<Suggestion>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub labeled_ranges: Vec<LabeledRange>,
}
/// Represents the error payload from `tsgolint`.
#[derive(Debug, Clone, Serialize, Deserialize)]
struct TsGoLintErrorPayload {
pub error: String,
}
#[derive(Debug, Clone)]
pub enum TsGoLintMessage {
Diagnostic(TsGoLintDiagnostic),
Error(TsGoLintError),
}
#[derive(Debug, Clone)]
pub enum TsGoLintDiagnostic {
Rule(TsGoLintRuleDiagnostic),
Internal(TsGoLintInternalDiagnostic),
}
#[derive(Debug, Clone)]
pub struct TsGoLintRuleDiagnostic {
pub span: Span,
pub rule: String,
pub message: RuleMessage,
pub fixes: Vec<Fix>,
pub suggestions: Vec<Suggestion>,
pub labeled_ranges: Vec<LabeledRange>,
pub file_path: PathBuf,
}
#[derive(Debug, Clone)]
pub struct TsGoLintInternalDiagnostic {
pub message: RuleMessage,
pub span: Option<Span>,
pub file_path: Option<PathBuf>,
}
#[derive(Debug, Clone)]
pub struct TsGoLintError {
pub error: String,
}
impl From<TsGoLintDiagnostic> for OxcDiagnostic {
fn from(val: TsGoLintDiagnostic) -> Self {
match val {
TsGoLintDiagnostic::Rule(d) => d.into(),
TsGoLintDiagnostic::Internal(d) => d.into(),
}
}
}
impl From<TsGoLintRuleDiagnostic> for OxcDiagnostic {
fn from(val: TsGoLintRuleDiagnostic) -> Self {
let mut d = OxcDiagnostic::warn(val.message.description)
.with_url(format!("{}/{}/{}.html", WEBSITE_BASE_RULES_URL, "typescript", val.rule))
.with_error_code("typescript-eslint", val.rule);
if let Some(help) = val.message.help {
d = d.with_help(help);
}
if val.labeled_ranges.is_empty() {
d = d.with_label(val.span);
} else {
let labels = val
.labeled_ranges
.into_iter()
.map(|lr| Span::new(lr.range.pos, lr.range.end).label(lr.label));
d = d.with_labels(labels);
// If the main span is empty, don't add it as a label since it doesn't have any meaning (means tsgolint sent nothing).
// Just use the labeled ranges that were passed instead.
if !val.span.is_unspanned() {
d = d.and_label(val.span.primary());
}
}
d
}
}
impl From<TsGoLintInternalDiagnostic> for OxcDiagnostic {
fn from(val: TsGoLintInternalDiagnostic) -> Self {
let mut d = OxcDiagnostic::error(val.message.description)
.with_error_code("typescript", val.message.id);
if let Some(help) = val.message.help {
d = d.with_help(help);
}
if val.file_path.is_some()
&& let Some(span) = val.span
{
d = d.with_label(span);
}
d
}
}
impl Message {
/// Converts a `TsGoLintDiagnostic` into a `Message` with possible fixes.
fn from_tsgo_lint_diagnostic(mut val: TsGoLintRuleDiagnostic, source_text: &str) -> Self {
let fix = if val.fixes.is_empty() {
None
} else {
let fix_vec = mem::take(&mut val.fixes)
.into_iter()
.map(|fix| crate::fixer::Fix {
content: Cow::Owned(fix.text),
span: Span::new(fix.range.pos, fix.range.end),
message: None,
kind: FixKind::Fix,
})
.collect();
Some(CompositeFix::merge_fixes(fix_vec, source_text))
};
let suggestions = mem::take(&mut val.suggestions).into_iter().map(|suggestion| {
let fix_vec = suggestion
.fixes
.into_iter()
.map(|fix| crate::fixer::Fix {
content: Cow::Owned(fix.text),
span: Span::new(fix.range.pos, fix.range.end),
message: None,
kind: FixKind::Suggestion,
})
.collect();
CompositeFix::merge_fixes(fix_vec, source_text)
.with_message(suggestion.message.description)
});
#[expect(clippy::from_iter_instead_of_collect)]
let possible_fixes = PossibleFixes::from_iter(iter::chain(fix, suggestions));
Self::new(val.into(), possible_fixes)
}
}
// TODO: Should this be removed and replaced with a `Span`?
#[derive(Clone, Debug, Serialize, Deserialize, Default)]
pub struct Range {
pub pos: u32,
pub end: u32,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RuleMessage {
pub id: String,
pub description: String,
pub help: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Fix {
pub text: String,
pub range: Range,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Suggestion {
pub message: RuleMessage,
pub fixes: Vec<Fix>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct LabeledRange {
pub label: String,
pub range: Range,
}
#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize)]
#[repr(u8)]
pub enum MessageType {
Error = 0,
Diagnostic = 1,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct InvalidMessageType(pub u8);
impl std::fmt::Display for InvalidMessageType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "invalid message type: {}", self.0)
}
}
impl std::error::Error for InvalidMessageType {}
impl TryFrom<u8> for MessageType {
type Error = InvalidMessageType;
fn try_from(value: u8) -> Result<Self, InvalidMessageType> {
match value {
0 => Ok(Self::Error),
1 => Ok(Self::Diagnostic),
_ => Err(InvalidMessageType(value)),
}
}
}
/// Iterator that streams messages from tsgolint stdout.
struct TsGoLintMessageStream {
stdout: std::process::ChildStdout,
buffer: Vec<u8>,
}
impl TsGoLintMessageStream {
fn new(stdout: std::process::ChildStdout) -> TsGoLintMessageStream {
TsGoLintMessageStream { stdout, buffer: Vec::with_capacity(8192) }
}
}
impl Iterator for TsGoLintMessageStream {
type Item = Result<TsGoLintMessage, String>;
fn next(&mut self) -> Option<Self::Item> {
let mut read_buf = [0u8; 8192];
loop {
// Try to parse a complete message from the existing buffer
let mut cursor = std::io::Cursor::new(self.buffer.as_slice());
if cursor.position() < self.buffer.len() as u64 {
match parse_single_message(&mut cursor) {
Ok(message) => {
// Successfully parsed a message, remove it from buffer
#[expect(clippy::cast_possible_truncation)]
self.buffer.drain(..cursor.position() as usize);
return Some(Ok(message));
}
Err(TsGoLintMessageParseError::IncompleteData) => {}
Err(e) => {
return Some(Err(e.to_string()));
}
}
}
// Read more data from stdout
match self.stdout.read(&mut read_buf) {
Ok(0) => {
return None;
}
Ok(n) => {
self.buffer.extend_from_slice(&read_buf[..n]);
}
Err(e) => {
return Some(Err(format!("Failed to read from tsgolint stdout: {e}")));
}
}
}
}
}
enum TsGoLintMessageParseError {
IncompleteData,
InvalidMessageType(InvalidMessageType),
InvalidErrorPayload(serde_json::Error),
InvalidDiagnosticPayload(serde_json::Error),
}
impl std::fmt::Display for TsGoLintMessageParseError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
TsGoLintMessageParseError::IncompleteData => write!(f, "Incomplete data"),
TsGoLintMessageParseError::InvalidMessageType(e) => write!(f, "{e}"),
TsGoLintMessageParseError::InvalidErrorPayload(e) => {
write!(f, "Failed to parse tsgolint error payload: {e}")
}
TsGoLintMessageParseError::InvalidDiagnosticPayload(e) => {
write!(f, "Failed to parse tsgolint diagnostic payload: {e}")
}
}
}
}
/// Cache for source text to avoid reading the same file multiple times.
#[derive(Default)]
struct SourceTextCache(FxHashMap<PathBuf, String>);
impl SourceTextCache {
fn get_or_insert(&mut self, path: &Path) -> &str {
self.0
.entry(path.to_path_buf())
.or_insert_with(|| read_to_string(path).unwrap_or_default())
.as_str()
}
}
/// Handles streaming and collecting diagnostics from tsgolint.
struct DiagnosticHandler {
cwd: PathBuf,
silent: bool,
should_fix: bool,
source_text_cache: SourceTextCache,
error_sender: DiagnosticSender,
/// Messages requiring fixes, grouped by file path: messages.
messages_requiring_fixes: FxHashMap<PathBuf, Vec<Message>>,
}
impl DiagnosticHandler {
fn new(cwd: PathBuf, silent: bool, should_fix: bool, error_sender: DiagnosticSender) -> Self {
Self {
cwd,
silent,
should_fix,
source_text_cache: SourceTextCache::default(),
error_sender,
messages_requiring_fixes: FxHashMap::default(),
}
}
fn get_source_text(&mut self, path: &Path) -> &str {
if self.silent && !self.should_fix {
// The source text is not needed in silent mode, the diagnostic isn't printed.
""
} else {
self.source_text_cache.get_or_insert(path)
}
}
fn handle_rule_diagnostic(
&mut self,
diagnostic: TsGoLintRuleDiagnostic,
severity: AllowWarnDeny,
) {
let path = diagnostic.file_path.clone();
let has_fixes =
self.should_fix && (!diagnostic.fixes.is_empty() || !diagnostic.suggestions.is_empty());
if has_fixes {
// Collect for later fix application
let mut message =
Message::from_tsgo_lint_diagnostic(diagnostic, self.get_source_text(&path));
message.error.severity =
if severity == AllowWarnDeny::Deny { Severity::Error } else { Severity::Warning };
let entry = self.messages_requiring_fixes.entry(path).or_default();
entry.push(message);
} else {
// Stream immediately
self.send_diagnostic(&path, diagnostic.into(), severity);
}
}
fn handle_internal_diagnostic(&mut self, e: TsGoLintInternalDiagnostic) {
let file_path = e.file_path.clone();
let oxc_diagnostic: OxcDiagnostic = e.into();