@@ -5,22 +5,50 @@ import cc.unitmesh.devti.language.compiler.model.LineInfo
5
5
import cc.unitmesh.devti.language.utils.lookupFile
6
6
import cc.unitmesh.devti.util.parser.Code
7
7
import com.intellij.openapi.application.runReadAction
8
+ import com.intellij.openapi.application.runWriteAction
8
9
import com.intellij.openapi.command.WriteCommandAction
10
+ import com.intellij.openapi.fileEditor.FileDocumentManager
9
11
import com.intellij.openapi.project.Project
12
+ import com.intellij.openapi.project.guessProjectDir
13
+ import com.intellij.openapi.vfs.findOrCreateDirectory
10
14
import com.intellij.psi.PsiDocumentManager
15
+ import com.intellij.psi.PsiFile
11
16
import com.intellij.psi.PsiManager
17
+ import java.io.File
12
18
13
19
class WriteInsCommand (val myProject : Project , val argument : String , val content : String ) : InsCommand {
14
20
override suspend fun execute (): String? {
15
21
val content = Code .parse(content).text
16
22
17
23
val range: LineInfo ? = LineInfo .fromString(argument)
18
- val filename = argument.split(" #" )[0 ]
24
+ val filepath = argument.split(" #" )[0 ]
25
+ val projectDir = myProject.guessProjectDir() ? : return " $DEVINS_ERROR : Project directory not found"
26
+
27
+ val virtualFile = myProject.lookupFile(filepath)
28
+ if (virtualFile == null ) {
29
+ return runWriteAction {
30
+ val parentPath = filepath.substringBeforeLast(File .separator)
31
+ val parentDir = projectDir.findOrCreateDirectory(parentPath)
32
+ val newFile = parentDir.createChildData(this , filepath.substringAfterLast(File .separator))
33
+ val document = FileDocumentManager .getInstance().getDocument(newFile)
34
+ ? : return @runWriteAction " $DEVINS_ERROR : Create File failed: $argument "
35
+
36
+ document.setText(content)
37
+
38
+ return @runWriteAction " Create file: $argument "
39
+ }
40
+ }
19
41
20
- val virtualFile = myProject.lookupFile(filename) ? : return " $DEVINS_ERROR : File not found: $argument "
21
42
val psiFile = PsiManager .getInstance(myProject).findFile(virtualFile)
22
43
? : return " $DEVINS_ERROR : File not found: $argument "
44
+ return executeInsert(psiFile, range, content)
45
+ }
23
46
47
+ private fun executeInsert (
48
+ psiFile : PsiFile ,
49
+ range : LineInfo ? ,
50
+ content : String
51
+ ): String {
24
52
val document = runReadAction {
25
53
PsiDocumentManager .getInstance(myProject).getDocument(psiFile)
26
54
} ? : return " $DEVINS_ERROR : File not found: $argument "
@@ -40,4 +68,4 @@ class WriteInsCommand(val myProject: Project, val argument: String, val content:
40
68
return " $DEVINS_ERROR : ${e.message} "
41
69
}
42
70
}
43
- }
71
+ }
0 commit comments