-
Notifications
You must be signed in to change notification settings - Fork 22
ADFA-3817 | Fix for dropdown entries separating layout and strings data #1258
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
150 changes: 150 additions & 0 deletions
150
app/src/main/java/com/itsaky/androidide/api/commands/AddStringArrayResourceCommand.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,150 @@ | ||
| package com.itsaky.androidide.api.commands | ||
|
|
||
| import com.blankj.utilcode.util.FileIOUtils | ||
| import com.itsaky.androidide.agent.model.ToolResult | ||
| import kotlinx.coroutines.Dispatchers | ||
| import kotlinx.coroutines.sync.Mutex | ||
| import kotlinx.coroutines.sync.withLock | ||
| import kotlinx.coroutines.withContext | ||
| import org.slf4j.LoggerFactory | ||
| import org.w3c.dom.Document | ||
| import org.w3c.dom.Element | ||
| import org.w3c.dom.Node | ||
| import org.xml.sax.EntityResolver | ||
| import org.xml.sax.InputSource | ||
| import java.io.File | ||
| import java.io.StringReader | ||
| import java.util.concurrent.ConcurrentHashMap | ||
| import javax.xml.parsers.DocumentBuilder | ||
| import javax.xml.parsers.DocumentBuilderFactory | ||
| import javax.xml.parsers.ParserConfigurationException | ||
| import javax.xml.transform.OutputKeys | ||
| import javax.xml.transform.TransformerFactory | ||
| import javax.xml.transform.dom.DOMSource | ||
| import javax.xml.transform.stream.StreamResult | ||
| import java.io.StringWriter | ||
|
|
||
| class AddStringArrayResourceCommand( | ||
| private val stringsFilePath: String, | ||
| private val name: String, | ||
| private val items: List<String> | ||
| ) : SuspendCommand<Unit> { | ||
|
|
||
| companion object { | ||
| private val log = LoggerFactory.getLogger(AddStringArrayResourceCommand::class.java) | ||
| private val fileMutexes = ConcurrentHashMap<String, Mutex>() | ||
| } | ||
|
|
||
| override suspend fun execute(): ToolResult { | ||
| if (name.isBlank()) { | ||
| return ToolResult.failure("String-array name cannot be blank.") | ||
| } | ||
|
|
||
| val stringsFile = withContext(Dispatchers.IO) { File(stringsFilePath).canonicalFile } | ||
| if (!stringsFile.exists() || !stringsFile.isFile) { | ||
| return ToolResult.failure("strings.xml file not found at '$stringsFilePath'.") | ||
| } | ||
|
|
||
| val fileMutex = fileMutexes.computeIfAbsent(stringsFile.path) { Mutex() } | ||
|
|
||
| return fileMutex.withLock { | ||
| try { | ||
| withContext(Dispatchers.IO) { | ||
| val currentContent = FileIOUtils.readFile2String(stringsFile) | ||
| val updatedContent = upsertStringArray(currentContent, name, items) | ||
|
|
||
| if (FileIOUtils.writeFileFromString(stringsFile, updatedContent)) { | ||
| ToolResult.success( | ||
| message = "Successfully added or updated string-array '$name'.", | ||
| data = "R.array.$name" | ||
| ) | ||
| } else { | ||
| ToolResult.failure("Failed to write to strings.xml.") | ||
| } | ||
| } | ||
| } catch (e: Exception) { | ||
| ToolResult.failure( | ||
| message = "An error occurred while adding or updating the string-array resource.", | ||
| error_details = e.message | ||
| ) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private fun upsertStringArray(currentContent: String, name: String, items: List<String>): String { | ||
| val document = newDocumentBuilder() | ||
| .parse(InputSource(StringReader(currentContent))) | ||
|
|
||
| val resources = document.getElementsByTagName("resources").item(0) as? Element | ||
| ?: throw IllegalStateException("The strings.xml file does not contain the <resources> tag") | ||
|
|
||
| val newNode = document.createElement("string-array").apply { | ||
| setAttribute("name", name) | ||
| items.forEach { itemValue -> | ||
| appendChild(document.createElement("item").apply { | ||
| appendChild(document.createTextNode(itemValue)) | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| val existingNode = List(document.getElementsByTagName("string-array").length) { index -> | ||
| document.getElementsByTagName("string-array").item(index) as Element | ||
| }.firstOrNull { it.getAttribute("name") == name } | ||
|
|
||
| if (existingNode != null) { | ||
| existingNode.parentNode.replaceChild(newNode, existingNode) | ||
| } else { | ||
| appendWithIndentation(document, resources, newNode) | ||
| } | ||
|
|
||
| return serializeDocument(document) | ||
| } | ||
|
|
||
| private fun appendWithIndentation(document: Document, parent: Element, child: Element) { | ||
| val closingIndentation = parent.lastChild | ||
| val childIndentation = document.createTextNode("\n ") | ||
|
|
||
| if (closingIndentation != null && closingIndentation.isResourcesClosingIndentation()) { | ||
| parent.insertBefore(childIndentation, closingIndentation) | ||
| parent.insertBefore(child, closingIndentation) | ||
| } else { | ||
| parent.appendChild(childIndentation) | ||
| parent.appendChild(child) | ||
| parent.appendChild(document.createTextNode("\n")) | ||
| } | ||
| } | ||
|
|
||
| private fun serializeDocument(document: Document): String { | ||
| val transformer = TransformerFactory.newInstance().newTransformer().apply { | ||
| setOutputProperty(OutputKeys.INDENT, "yes") | ||
| setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4") | ||
| setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no") | ||
| } | ||
| return StringWriter().also { writer -> | ||
| transformer.transform(DOMSource(document), StreamResult(writer)) | ||
| }.toString() | ||
| } | ||
|
|
||
| private fun newDocumentBuilder(): DocumentBuilder { | ||
| return DocumentBuilderFactory.newInstance().apply { | ||
| setFeatureIfSupported("http://apache.org/xml/features/disallow-doctype-decl", true) | ||
| setFeatureIfSupported("http://xml.org/sax/features/external-general-entities", false) | ||
| setFeatureIfSupported("http://xml.org/sax/features/external-parameter-entities", false) | ||
| isExpandEntityReferences = false | ||
| }.newDocumentBuilder().apply { | ||
| setEntityResolver { _, _ -> InputSource(StringReader("")) } | ||
| } | ||
| } | ||
|
|
||
| private fun DocumentBuilderFactory.setFeatureIfSupported(name: String, value: Boolean) { | ||
| try { | ||
| setFeature(name, value) | ||
| } catch (_: ParserConfigurationException) { | ||
| log.warn("XML parser does not support feature '{}'; continuing without it.", name) | ||
| } | ||
| } | ||
|
|
||
| private fun Node.isResourcesClosingIndentation(): Boolean { | ||
| return nodeType == Node.TEXT_NODE && textContent.contains('\n') | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
7 changes: 7 additions & 0 deletions
7
app/src/main/java/com/itsaky/androidide/api/commands/SuspendCommand.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| package com.itsaky.androidide.api.commands | ||
|
|
||
| import com.itsaky.androidide.agent.model.ToolResult | ||
|
|
||
| interface SuspendCommand<T> { | ||
| suspend fun execute(): ToolResult | ||
| } |
37 changes: 37 additions & 0 deletions
37
app/src/main/java/com/itsaky/androidide/utils/ProjectStringsXmlResolver.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| package com.itsaky.androidide.utils | ||
|
|
||
| import kotlinx.coroutines.Dispatchers | ||
| import kotlinx.coroutines.withContext | ||
| import java.io.File | ||
|
|
||
| /** | ||
| * Resolves the project's default strings.xml file while ensuring access stays | ||
| * within the provided project root. | ||
| */ | ||
| object ProjectStringsXmlResolver { | ||
|
|
||
| private const val STRINGS_XML_RELATIVE_PATH = "app/src/main/res/values/strings.xml" | ||
|
|
||
| suspend fun find(projectRootPath: String): File? = withContext(Dispatchers.IO) { | ||
| findNow(projectRootPath) | ||
| } | ||
|
|
||
| fun findNow(projectRootPath: String): File? { | ||
| val projectRoot = projectRootPath.toCanonicalDirectory() ?: return null | ||
| val stringsFile = File(projectRoot, STRINGS_XML_RELATIVE_PATH).canonicalFile | ||
| return stringsFile.takeIf { | ||
| it.exists() && it.isFile && it.isWithin(projectRoot) | ||
| } | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| private fun String.toCanonicalDirectory(): File? { | ||
| val dir = File(this).canonicalFile | ||
| return dir.takeIf { it.exists() && it.isDirectory } | ||
| } | ||
|
|
||
| private fun File.isWithin(root: File): Boolean { | ||
| val rootPath = root.toPath() | ||
| val filePath = toPath() | ||
| return filePath.startsWith(rootPath) | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.