1
+ package com.koxudaxi.ruff
2
+
3
+ import com.intellij.formatting.FormattingContext
4
+ import com.intellij.formatting.service.AsyncDocumentFormattingService
5
+ import com.intellij.formatting.service.AsyncFormattingRequest
6
+ import com.intellij.formatting.service.FormattingService
7
+ import com.intellij.openapi.progress.ProcessCanceledException
8
+ import com.intellij.psi.PsiFile
9
+ import java.util.*
10
+
11
+
12
+ class RuffAsyncFormatterFormat : AsyncDocumentFormattingService () {
13
+ private val FEATURES : MutableSet <FormattingService .Feature > = EnumSet .noneOf(
14
+ FormattingService .Feature ::class .java
15
+ )
16
+
17
+ override fun getFeatures (): MutableSet <FormattingService .Feature > {
18
+ return FEATURES
19
+ }
20
+
21
+ override fun canFormat (file : PsiFile ): Boolean {
22
+ return RuffConfigService .getInstance(file.project).runRuffOnReformatCode &&
23
+ RuffConfigService .getInstance(file.project).useRuffFormat &&
24
+ file.isApplicableTo
25
+ }
26
+
27
+ override fun runAfter (): Class <out FormattingService > {
28
+ return RuffAsyncFormatterFix ::class .java
29
+ }
30
+
31
+ override fun createFormattingTask (request : AsyncFormattingRequest ): FormattingTask ? {
32
+ val formattingContext: FormattingContext = request.context
33
+ val ioFile = request.ioFile ? : return null
34
+ return object : FormattingTask {
35
+ private fun updateText (currentText : String , text : String? ) {
36
+ when {
37
+ text == null -> request.onTextReady(null )
38
+ currentText == text -> request.onTextReady(null )
39
+ else -> request.onTextReady(text)
40
+ }
41
+ }
42
+
43
+ override fun run () {
44
+ runCatching {
45
+ val sourceFile = formattingContext.containingFile.sourceFile
46
+ val currentText = ioFile.readText()
47
+
48
+ val formatCommandArgs = generateCommandArgs(sourceFile, FORMAT_ARGS )
49
+ if (formatCommandArgs == null ) {
50
+ request.onTextReady(null )
51
+ return @runCatching
52
+ }
53
+ val formatCommandStdout = runRuff(formatCommandArgs, currentText.toByteArray())
54
+ updateText(currentText, formatCommandStdout)
55
+
56
+ }.onFailure { exception ->
57
+ when (exception) {
58
+ is ProcessCanceledException -> { /* ignore */
59
+ }
60
+
61
+ else -> {
62
+ request.onError(" Ruff Error" , exception.localizedMessage)
63
+ }
64
+ }
65
+ }
66
+ }
67
+
68
+ override fun cancel (): Boolean {
69
+ return true
70
+ }
71
+
72
+ override fun isRunUnderProgress (): Boolean {
73
+ return true
74
+ }
75
+ }
76
+ }
77
+
78
+ override fun getNotificationGroupId (): String {
79
+ return " Ruff"
80
+ }
81
+
82
+ override fun getName (): String {
83
+ return " Ruff Formatter Format"
84
+ }
85
+ }
0 commit comments