in rider/src/main/kotlin/com/jetbrains/aspire/rider/orchestration/AspireAppHostModificationService.kt [52:119]
suspend fun modifyAppHost(appHostEntity: ProjectModelEntity, projectEntities: List<ProjectModelEntity>): Boolean {
if (projectEntities.isEmpty()) return false
val appHostProjectPath = appHostEntity.url?.toPath()
if (appHostProjectPath == null) {
LOG.warn("AppHost project URL is null, cannot modify AppHost")
return false
}
val appHostFile = findAppHostFile(appHostProjectPath)
if (appHostFile == null) {
LOG.warn("Unable to find AppHost.cs (or Program.cs) file in the host project")
return false
}
val linesToInsert = modifyAppHostWithHandlers(appHostEntity, projectEntities)
return readAndEdtWriteAction {
val document = appHostFile.findDocument()
if (document == null) {
LOG.warn("Unable to find AppHost.cs (or Program.cs) file document")
return@readAndEdtWriteAction value(false)
}
val text = document.text
val lastAddProjectIndex = text.lastIndexOf(ADD_PROJECT_METHOD)
var semicolonIndex = if (lastAddProjectIndex == -1) {
val builderIndex = text.indexOf(CREATE_BUILDER_METHOD)
if (builderIndex == -1) {
LOG.info("Unable to find a method for creating a distributed builder")
return@readAndEdtWriteAction value(false)
}
text.indexOf(';', builderIndex)
} else {
text.indexOf(';', lastAddProjectIndex)
}
if (semicolonIndex == -1) {
LOG.info("Unable to find an index to insert an `AddProject` method")
return@readAndEdtWriteAction value(false)
}
val psiFile = appHostFile.findPsiFile(project)
writeCommandAction(project, AspireRiderBundle.message("write.command.insert.into.app.host")) {
val indent =
if (psiFile != null) calculateIndent(psiFile, document, semicolonIndex)
else ""
var methodsWereInserted = false
for (lineToInsert in linesToInsert) {
if (text.contains(lineToInsert)) continue
val textToInsert = buildString {
append('\n')
append('\n')
append(indent)
append(lineToInsert)
}
document.insertString(semicolonIndex + 1, textToInsert)
semicolonIndex += textToInsert.length
methodsWereInserted = true
}
return@writeCommandAction methodsWereInserted
}
}
}