Modern Apps git

← Modern-Apps.git

code: gitignore-aware search, save transforms, and paste re-indent

Commit
2c40b44c785535d23353c72c1f9a131cde9961ea
Author
Vayun Mathur <[email protected]>
When
2026-08-07 02:31 UTC (4 months ago)
Parents
ad9c23f

Diff

code/src/main/java/com/vayunmathur/code/ui/SettingsPage.kt
diff --git a/code/src/main/java/com/vayunmathur/code/ui/SettingsPage.kt b/code/src/main/java/com/vayunmathur/code/ui/SettingsPage.ktindex 4162a3912d..1166935c8d 100644--- a/code/src/main/java/com/vayunmathur/code/ui/SettingsPage.kt+++ b/code/src/main/java/com/vayunmathur/code/ui/SettingsPage.kt@@ -119,6 +119,20 @@ fun SettingsPage(viewModel: EditorViewModel, backStack: NavBackStack<Route>) {                     onCheckedChange = viewModel::setAutoSave,                 )                 SettingsDivider()+                SettingsSwitchRow(+                    title = stringResource(R.string.trim_trailing_whitespace),+                    supportingText = stringResource(R.string.trim_trailing_whitespace_desc),+                    checked = viewModel.trimTrailingOnSave,+                    onCheckedChange = viewModel::setTrimTrailingOnSave,+                )+                SettingsDivider()+                SettingsSwitchRow(+                    title = stringResource(R.string.final_newline),+                    supportingText = stringResource(R.string.final_newline_desc),+                    checked = viewModel.finalNewlineOnSave,+                    onCheckedChange = viewModel::setFinalNewlineOnSave,+                )+                SettingsDivider()                 SettingsSwitchRow(                     title = stringResource(R.string.experimental_editor),                     supportingText = stringResource(R.string.experimental_editor_desc),
code/src/main/java/com/vayunmathur/code/util/EditorInput.kt
diff --git a/code/src/main/java/com/vayunmathur/code/util/EditorInput.kt b/code/src/main/java/com/vayunmathur/code/util/EditorInput.ktindex 58008861f6..14df9f3a50 100644--- a/code/src/main/java/com/vayunmathur/code/util/EditorInput.kt+++ b/code/src/main/java/com/vayunmathur/code/util/EditorInput.kt@@ -33,8 +33,24 @@ fun applyEditorInput( ): TextFieldValue {     if (!new.selection.collapsed) return new     val caret = new.selection.start+    val diff = new.text.length - old.text.length++    // Paste: a multi-character insertion containing a newline. Re-base its indentation onto the+    // caret line so pasted blocks line up with their new surroundings.+    if (diff > 1 && caret >= diff) {+        val cleanInsertion =+            old.text == new.text.substring(0, caret - diff) + new.text.substring(caret)+        if (cleanInsertion) {+            val pasted = new.text.substring(caret - diff, caret)+            if (autoIndent && pasted.contains('\n')) {+                return reindentPaste(old.text, caret - diff, pasted, indentUnit)+            }+        }+        return new+    }+     // Must be exactly one character longer, inserted so that removing it reproduces the old text.-    if (new.text.length != old.text.length + 1 || caret < 1) return new+    if (diff != 1 || caret < 1) return new     if (old.text != new.text.substring(0, caret - 1) + new.text.substring(caret)) return new      val c = new.text[caret - 1]@@ -280,3 +296,44 @@ fun findLineMatches( }  private const val PREVIEW_LIMIT = 200++// ---- Paste re-indentation & save transforms (pure) ----++private fun leadingWhitespaceLen(line: String): Int {+    var i = 0+    while (i < line.length && (line[i] == ' ' || line[i] == '\t')) i+++    return i+}++/**+ * Inserts [pasted] at [caret] in [text], re-basing the block's indentation onto the caret line.+ *+ * The minimal common indentation across the pasted block's non-blank lines is stripped, and the+ * caret line's leading whitespace ([caret]'s line indent) is re-applied to every line after the+ * first (the first pasted line continues at the caret, which already sits after that indent).+ * Relative indentation within the block is preserved.+ */+fun reindentPaste(text: String, caret: Int, pasted: String, indentUnit: String): TextFieldValue {+    val lineStart = text.lastIndexOf('\n', caret - 1) + 1+    val baseIndent = text.substring(lineStart, lineStart + leadingWhitespaceLen(text.substring(lineStart, caret)))++    val lines = pasted.split('\n')+    val nonBlank = lines.filter { it.isNotBlank() }+    val common = nonBlank.minOfOrNull { leadingWhitespaceLen(it) } ?: 0++    val reindented = lines.mapIndexed { idx, line ->+        val stripped = if (line.isBlank()) "" else line.substring(common.coerceAtMost(line.length))+        if (idx == 0) stripped else baseIndent + stripped+    }+    val block = reindented.joinToString("\n")+    val newText = text.substring(0, caret) + block + text.substring(caret)+    return TextFieldValue(newText, TextRange(caret + block.length))+}++/** Removes trailing spaces and tabs from every line (used by the trim-on-save preference). */+fun trimTrailingWhitespace(text: String): String =+    text.split('\n').joinToString("\n") { it.trimEnd(' ', '\t') }++/** Ensures the text ends with exactly one trailing newline (used by the final-newline preference). */+fun ensureFinalNewline(text: String): String =+    if (text.isEmpty() || text.endsWith('\n')) text else text + "\n"
code/src/main/java/com/vayunmathur/code/util/EditorPrefs.kt
diff --git a/code/src/main/java/com/vayunmathur/code/util/EditorPrefs.kt b/code/src/main/java/com/vayunmathur/code/util/EditorPrefs.ktindex 2a4e2cbf22..26e0994bda 100644--- a/code/src/main/java/com/vayunmathur/code/util/EditorPrefs.kt+++ b/code/src/main/java/com/vayunmathur/code/util/EditorPrefs.kt@@ -34,6 +34,10 @@ class EditorPrefs(context: Context) {     val autoCloseBrackets: Flow<Boolean> =         appContext.editorDataStore.data.map { it[AUTO_CLOSE_KEY] ?: true }     val autoSave: Flow<Boolean> = appContext.editorDataStore.data.map { it[AUTO_SAVE_KEY] ?: false }+    val trimTrailingOnSave: Flow<Boolean> =+        appContext.editorDataStore.data.map { it[TRIM_TRAILING_KEY] ?: false }+    val finalNewlineOnSave: Flow<Boolean> =+        appContext.editorDataStore.data.map { it[FINAL_NEWLINE_KEY] ?: false }     val experimentalEditor: Flow<Boolean> =         appContext.editorDataStore.data.map { it[EXPERIMENTAL_EDITOR_KEY] ?: false }     val showWhitespace: Flow<Boolean> =@@ -104,6 +108,14 @@ class EditorPrefs(context: Context) {         appContext.editorDataStore.edit { it[AUTO_SAVE_KEY] = enabled }     } +    suspend fun setTrimTrailingOnSave(enabled: Boolean) {+        appContext.editorDataStore.edit { it[TRIM_TRAILING_KEY] = enabled }+    }++    suspend fun setFinalNewlineOnSave(enabled: Boolean) {+        appContext.editorDataStore.edit { it[FINAL_NEWLINE_KEY] = enabled }+    }+     suspend fun setExperimentalEditor(enabled: Boolean) {         appContext.editorDataStore.edit { it[EXPERIMENTAL_EDITOR_KEY] = enabled }     }@@ -207,6 +219,8 @@ class EditorPrefs(context: Context) {         private val AUTO_INDENT_KEY = booleanPreferencesKey("auto_indent")         private val AUTO_CLOSE_KEY = booleanPreferencesKey("auto_close_brackets")         private val AUTO_SAVE_KEY = booleanPreferencesKey("auto_save")+        private val TRIM_TRAILING_KEY = booleanPreferencesKey("trim_trailing_on_save")+        private val FINAL_NEWLINE_KEY = booleanPreferencesKey("final_newline_on_save")         private val EXPERIMENTAL_EDITOR_KEY = booleanPreferencesKey("experimental_editor")         private val SHOW_WHITESPACE_KEY = booleanPreferencesKey("show_whitespace")         private val SHOW_INDENT_GUIDES_KEY = booleanPreferencesKey("show_indent_guides")
code/src/main/java/com/vayunmathur/code/util/EditorViewModel.kt
diff --git a/code/src/main/java/com/vayunmathur/code/util/EditorViewModel.kt b/code/src/main/java/com/vayunmathur/code/util/EditorViewModel.ktindex 5b8115f751..500e9b4a1f 100644--- a/code/src/main/java/com/vayunmathur/code/util/EditorViewModel.kt+++ b/code/src/main/java/com/vayunmathur/code/util/EditorViewModel.kt@@ -160,6 +160,10 @@ class EditorViewModel(application: Application) : AndroidViewModel(application),     val autoCloseBrackets: Boolean get() = _autoCloseBrackets.value     private val _autoSave = mutableStateOf(false)     val autoSave: Boolean get() = _autoSave.value+    private val _trimTrailingOnSave = mutableStateOf(false)+    val trimTrailingOnSave: Boolean get() = _trimTrailingOnSave.value+    private val _finalNewlineOnSave = mutableStateOf(false)+    val finalNewlineOnSave: Boolean get() = _finalNewlineOnSave.value     private val _editorTheme = mutableStateOf(EditorThemes.DEFAULT)     val editorTheme: String get() = _editorTheme.value     private val _experimentalEditor = mutableStateOf(false)@@ -276,6 +280,8 @@ class EditorViewModel(application: Application) : AndroidViewModel(application),         viewModelScope.launch { _autoIndent.value = prefs.autoIndent.first() }         viewModelScope.launch { _autoCloseBrackets.value = prefs.autoCloseBrackets.first() }         viewModelScope.launch { _autoSave.value = prefs.autoSave.first() }+        viewModelScope.launch { _trimTrailingOnSave.value = prefs.trimTrailingOnSave.first() }+        viewModelScope.launch { _finalNewlineOnSave.value = prefs.finalNewlineOnSave.first() }         viewModelScope.launch { _editorTheme.value = prefs.editorTheme.first() }         viewModelScope.launch { _experimentalEditor.value = prefs.experimentalEditor.first() }         viewModelScope.launch { _showWhitespace.value = prefs.showWhitespace.first() }@@ -979,7 +985,18 @@ class EditorViewModel(application: Application) : AndroidViewModel(application),     /** Encodes [tab] with its stored charset/BOM/line-ending and writes it, refreshing the snapshot. */     private fun saveTab(tab: OpenTab) {         val file = tab.file ?: return // external read-only tabs have no save target-        val textToSave = tab.value.text+        var textToSave = tab.value.text+        if (trimTrailingOnSave) textToSave = trimTrailingWhitespace(textToSave)+        if (finalNewlineOnSave) textToSave = ensureFinalNewline(textToSave)+        // Reflect the transformed text back into the buffer so the tab isn't left "dirty".+        if (textToSave != tab.value.text) {+            val sel = tab.value.selection+            val clamped = TextRange(+                sel.start.coerceAtMost(textToSave.length),+                sel.end.coerceAtMost(textToSave.length),+            )+            tab.value = TextFieldValue(textToSave, clamped)+        }         val bytes = TextEncoding.encode(textToSave, tab.charset, tab.lineEnding, tab.hadBom)         viewModelScope.launch {             val ok = withContext(Dispatchers.IO) {@@ -1090,6 +1107,16 @@ class EditorViewModel(application: Application) : AndroidViewModel(application),         if (enabled) scheduleAutoSave()     } +    fun setTrimTrailingOnSave(enabled: Boolean) {+        _trimTrailingOnSave.value = enabled+        viewModelScope.launch { prefs.setTrimTrailingOnSave(enabled) }+    }++    fun setFinalNewlineOnSave(enabled: Boolean) {+        _finalNewlineOnSave.value = enabled+        viewModelScope.launch { prefs.setFinalNewlineOnSave(enabled) }+    }+     fun setEditorTheme(theme: String) {         _editorTheme.value = theme         viewModelScope.launch { prefs.setEditorTheme(theme) }@@ -1178,6 +1205,7 @@ class EditorViewModel(application: Application) : AndroidViewModel(application),         searchJob = viewModelScope.launch {             val collected = withContext(Dispatchers.IO) {                 val out = ArrayList<SearchResult>()+                val ignore = loadGitIgnore(root)                 val stack = ArrayDeque<File>()                 stack.addLast(root)                 while (stack.isNotEmpty() && out.size < MAX_SEARCH_RESULTS) {@@ -1186,10 +1214,12 @@ class EditorViewModel(application: Application) : AndroidViewModel(application),                     val children = runCatching { FileFiles.listChildren(dir) }.getOrDefault(emptyList())                     for (child in children) {                         if (out.size >= MAX_SEARCH_RESULTS) break+                        val rel = relativeTo(root, child.file)                         if (child.isDirectory) {-                            if (child.name !in SKIP_DIRS) stack.addLast(child.file)+                            if (child.name !in SKIP_DIRS && !ignore.isIgnored(rel, true)) stack.addLast(child.file)                             continue                         }+                        if (ignore.isIgnored(rel, false)) continue                         if (Language.fromFileName(child.name) == Language.PLAINTEXT) continue                         if (child.file.length() > MAX_SEARCH_FILE_SIZE) continue                         val text = runCatching { FileFiles.readText(child.file) }.getOrNull() ?: continue@@ -1236,7 +1266,7 @@ class EditorViewModel(application: Application) : AndroidViewModel(application),         projectFilesJob = viewModelScope.launch {             val collected = withContext(Dispatchers.IO) {                 val out = ArrayList<ProjectFileEntry>()-                val rootPath = root.absolutePath+                val ignore = loadGitIgnore(root)                 val stack = ArrayDeque<File>()                 stack.addLast(root)                 while (stack.isNotEmpty() && out.size < MAX_PROJECT_FILES) {@@ -1245,10 +1275,12 @@ class EditorViewModel(application: Application) : AndroidViewModel(application),                     val children = runCatching { FileFiles.listChildren(dir) }.getOrDefault(emptyList())                     for (child in children) {                         if (out.size >= MAX_PROJECT_FILES) break+                        val rel = relativeTo(root, child.file)                         if (child.isDirectory) {-                            if (child.name !in SKIP_DIRS) stack.addLast(child.file)+                            if (child.name !in SKIP_DIRS && !ignore.isIgnored(rel, true)) stack.addLast(child.file)                             continue                         }+                        if (ignore.isIgnored(rel, false)) continue                         out.add(toProjectEntry(child.file))                     }                 }@@ -1259,6 +1291,19 @@ class EditorViewModel(application: Application) : AndroidViewModel(application),         }     } +    /** Reads and parses the project root `.gitignore`, or returns an empty matcher. */+    private fun loadGitIgnore(root: File): GitIgnore = runCatching {+        val f = File(root, ".gitignore")+        if (f.isFile) parseGitIgnore(f.readText()) else GitIgnore.EMPTY+    }.getOrDefault(GitIgnore.EMPTY)++    /** Path of [file] relative to [root] (falling back to the bare name when not under root). */+    private fun relativeTo(root: File, file: File): String {+        val rp = root.absolutePath+        val ap = file.absolutePath+        return if (ap.startsWith(rp + File.separator)) ap.substring(rp.length + 1) else file.name+    }+     /** Builds the display entry for [file], with a path relative to the open root when possible. */     private fun toProjectEntry(file: File): ProjectFileEntry {         val abs = file.absolutePath
code/src/main/java/com/vayunmathur/code/util/GitIgnore.kt
diff --git a/code/src/main/java/com/vayunmathur/code/util/GitIgnore.kt b/code/src/main/java/com/vayunmathur/code/util/GitIgnore.ktnew file mode 100644index 0000000000..3e9e3ee554--- /dev/null+++ b/code/src/main/java/com/vayunmathur/code/util/GitIgnore.kt@@ -0,0 +1,115 @@+package com.vayunmathur.code.util++/**+ * A small, pure `.gitignore` matcher used to hide ignored files from project search and+ * quick-open (alongside the hard-coded [EditorViewModel.SKIP_DIRS]).+ *+ * It supports the common subset of the gitignore spec: comments (`#`) and blank lines, `*`+ * and `?` wildcards, `**` across directories, `/` anchoring (a leading or interior slash+ * anchors to the project root), directory-only patterns (trailing `/`) and negation (`!`).+ * Rules are applied in file order with last-match-wins, so a later `!pattern` can re-include a+ * path an earlier rule ignored. It deliberately does not implement every corner of the real+ * spec (e.g. escaping oddities), which is fine for a client-side "hide the noise" filter.+ */+class GitIgnore internal constructor(private val rules: List<Rule>) {++    internal class Rule(+        val regex: Regex,+        val negate: Boolean,+        val dirOnly: Boolean,+        val anchored: Boolean,+    ) {+        fun matches(prefix: String, prefixIsDir: Boolean): Boolean {+            if (dirOnly && !prefixIsDir) return false+            return if (anchored) regex.matches(prefix) else regex.matches(prefix.substringAfterLast('/'))+        }+    }++    /**+     * True if [relativePath] (relative to the project root, `/`-separated) is ignored. [isDir]+     * marks whether the entry itself is a directory. Every ancestor directory of the path is+     * also tested, so a file under an ignored directory is reported ignored too.+     */+    fun isIgnored(relativePath: String, isDir: Boolean): Boolean {+        if (rules.isEmpty()) return false+        val norm = relativePath.replace('\\', '/').trim('/')+        if (norm.isEmpty()) return false+        val segs = norm.split('/')+        var ignored = false+        for (i in 1..segs.size) {+            val prefix = segs.subList(0, i).joinToString("/")+            val prefixIsDir = if (i < segs.size) true else isDir+            for (rule in rules) {+                if (rule.matches(prefix, prefixIsDir)) ignored = !rule.negate+            }+        }+        return ignored+    }++    companion object {+        val EMPTY = GitIgnore(emptyList())+    }+}++/** Parses the text of a `.gitignore` file into a [GitIgnore] matcher. */+fun parseGitIgnore(text: String): GitIgnore {+    val rules = ArrayList<GitIgnore.Rule>()+    for (raw in text.lineSequence()) {+        var line = raw.trimEnd()+        if (line.isEmpty() || line.startsWith("#")) continue++        var negate = false+        if (line.startsWith("!")) {+            negate = true+            line = line.substring(1)+        }+        // An escaped leading '#' or '!' is a literal.+        if (line.startsWith("\\#") || line.startsWith("\\!")) line = line.substring(1)++        var dirOnly = false+        if (line.endsWith("/")) {+            dirOnly = true+            line = line.dropLast(1)+        }+        if (line.isEmpty()) continue++        val anchored = line.contains('/')+        val pat = if (line.startsWith("/")) line.substring(1) else line+        if (pat.isEmpty()) continue+        rules.add(GitIgnore.Rule(globToRegex(pat), negate, dirOnly, anchored))+    }+    return GitIgnore(rules)+}++/** Translates a gitignore glob into a [Regex] matching a whole path segment (or full path). */+private fun globToRegex(glob: String): Regex {+    val sb = StringBuilder()+    var i = 0+    while (i < glob.length) {+        val c = glob[i]+        when (c) {+            '*' -> {+                if (i + 1 < glob.length && glob[i + 1] == '*') {+                    // "**" spans directories. A "/**/" segment also matches zero directories.+                    val slashBefore = i > 0 && glob[i - 1] == '/'+                    val slashAfter = i + 2 < glob.length && glob[i + 2] == '/'+                    if (slashBefore && slashAfter) {+                        // Emitted "/" already; consume the trailing "/" and allow zero-or-more dirs.+                        sb.append("(.*/)?")+                        i += 2 // skip second '*' and the following '/'+                    } else {+                        sb.append(".*")+                        i++ // skip second '*'+                    }+                } else {+                    sb.append("[^/]*")+                }+            }+            '?' -> sb.append("[^/]")+            '.', '(', ')', '+', '|', '^', '$', '{', '}', '[', ']', '\\' -> sb.append('\\').append(c)+            else -> sb.append(c)+        }+        i+++    }+    return Regex(sb.toString())+}
code/src/main/res/values/strings.xml
diff --git a/code/src/main/res/values/strings.xml b/code/src/main/res/values/strings.xmlindex ae9b02d3eb..dfde0c1a71 100644--- a/code/src/main/res/values/strings.xml+++ b/code/src/main/res/values/strings.xml@@ -60,6 +60,10 @@     <string name="delete_line">Delete line</string>     <string name="auto_save">Auto-save</string>     <string name="auto_save_desc">Save automatically a moment after you stop typing</string>+    <string name="trim_trailing_whitespace">Trim trailing whitespace</string>+    <string name="trim_trailing_whitespace_desc">Remove trailing spaces and tabs on save</string>+    <string name="final_newline">Final newline</string>+    <string name="final_newline_desc">Ensure the file ends with a newline on save</string>     <string name="source_control">Source control</string>     <string name="not_a_git_repo">This folder is not a git repository.</string>     <string name="git_init">Initialize repository</string>
code/src/test/java/com/vayunmathur/code/util/EditorInputTest.kt
diff --git a/code/src/test/java/com/vayunmathur/code/util/EditorInputTest.kt b/code/src/test/java/com/vayunmathur/code/util/EditorInputTest.ktindex 6d4f8a7d39..98356187c1 100644--- a/code/src/test/java/com/vayunmathur/code/util/EditorInputTest.kt+++ b/code/src/test/java/com/vayunmathur/code/util/EditorInputTest.kt@@ -254,4 +254,57 @@ class EditorInputTest {         val result = toggleLineComment(value, "//")         assertEquals("// foo\n\n// bar", result.text)     }++    // ---- Paste re-indentation ----++    @Test+    fun pasteReindentsBlockOntoCaretIndent() {+        // Caret sits after 4 spaces of indentation; the pasted block is de-dented then re-based.+        val result = reindentPaste("    ", 4, "if (x) {\n    y()\n}", "  ")+        assertEquals("    if (x) {\n        y()\n    }", result.text)+    }++    @Test+    fun pasteStripsCommonLeadingIndent() {+        val result = reindentPaste("", 0, "    a\n      b", "  ")+        assertEquals("a\n  b", result.text)+    }++    @Test+    fun pasteThroughApplyEditorInputReindents() {+        val old = TextFieldValue("    ", TextRange(4))+        val new = TextFieldValue("    a\n    b", TextRange(11))+        val result = applyEditorInput(old, new, "  ", autoIndent = true, autoCloseBrackets = true)+        // Base indent "    " is re-applied to the second line (its own indent is common-stripped to 0).+        assertEquals("    a\n        b", result.text)+    }++    @Test+    fun pasteBlankLinesBecomeEmpty() {+        val result = reindentPaste("", 0, "a\n\nb", "  ")+        assertEquals("a\n\nb", result.text)+    }++    // ---- Save transforms ----++    @Test+    fun trimTrailingWhitespaceRemovesLineEndSpaces() {+        assertEquals("a\nb", trimTrailingWhitespace("a  \nb\t"))+    }++    @Test+    fun trimTrailingWhitespaceKeepsInteriorAndNewlines() {+        assertEquals("a b\n\n", trimTrailingWhitespace("a b \n \n"))+    }++    @Test+    fun ensureFinalNewlineAddsWhenMissing() {+        assertEquals("a\n", ensureFinalNewline("a"))+    }++    @Test+    fun ensureFinalNewlineNoOpWhenPresentOrEmpty() {+        assertEquals("a\n", ensureFinalNewline("a\n"))+        assertEquals("", ensureFinalNewline(""))+    } }
code/src/test/java/com/vayunmathur/code/util/GitIgnoreTest.kt
diff --git a/code/src/test/java/com/vayunmathur/code/util/GitIgnoreTest.kt b/code/src/test/java/com/vayunmathur/code/util/GitIgnoreTest.ktnew file mode 100644index 0000000000..30ea4fb4f8--- /dev/null+++ b/code/src/test/java/com/vayunmathur/code/util/GitIgnoreTest.kt@@ -0,0 +1,82 @@+package com.vayunmathur.code.util++import kotlin.test.Test+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/** Unit tests for the pure [GitIgnore] matcher. */+class GitIgnoreTest {++    @Test+    fun literalNameIgnoredAtAnyDepth() {+        val gi = parseGitIgnore("node_modules")+        assertTrue(gi.isIgnored("node_modules", isDir = true))+        assertTrue(gi.isIgnored("src/node_modules", isDir = true))+        assertTrue(gi.isIgnored("node_modules/pkg/index.js", isDir = false))+        assertFalse(gi.isIgnored("src/main.kt", isDir = false))+    }++    @Test+    fun starMatchesExtension() {+        val gi = parseGitIgnore("*.log")+        assertTrue(gi.isIgnored("app.log", isDir = false))+        assertTrue(gi.isIgnored("logs/app.log", isDir = false))+        assertFalse(gi.isIgnored("app.txt", isDir = false))+    }++    @Test+    fun questionMarkMatchesSingleChar() {+        val gi = parseGitIgnore("file?.txt")+        assertTrue(gi.isIgnored("file1.txt", isDir = false))+        assertFalse(gi.isIgnored("file10.txt", isDir = false))+    }++    @Test+    fun trailingSlashMatchesDirectoriesOnly() {+        val gi = parseGitIgnore("build/")+        assertTrue(gi.isIgnored("build", isDir = true))+        assertFalse(gi.isIgnored("build", isDir = false))+        assertTrue(gi.isIgnored("build/out.o", isDir = false))+    }++    @Test+    fun leadingSlashAnchorsToRoot() {+        val gi = parseGitIgnore("/build")+        assertTrue(gi.isIgnored("build", isDir = true))+        assertFalse(gi.isIgnored("src/build", isDir = true))+    }++    @Test+    fun interiorSlashIsAnchored() {+        val gi = parseGitIgnore("src/generated")+        assertTrue(gi.isIgnored("src/generated", isDir = true))+        assertFalse(gi.isIgnored("app/src/generated", isDir = true))+    }++    @Test+    fun negationReincludes() {+        val gi = parseGitIgnore("*.log\n!keep.log")+        assertTrue(gi.isIgnored("app.log", isDir = false))+        assertFalse(gi.isIgnored("keep.log", isDir = false))+    }++    @Test+    fun commentsAndBlankLinesIgnored() {+        val gi = parseGitIgnore("# a comment\n\n*.tmp")+        assertTrue(gi.isIgnored("x.tmp", isDir = false))+        assertFalse(gi.isIgnored("x.kt", isDir = false))+    }++    @Test+    fun doubleStarMatchesAcrossDirectories() {+        val gi = parseGitIgnore("a/**/z")+        assertTrue(gi.isIgnored("a/z", isDir = false))+        assertTrue(gi.isIgnored("a/b/c/z", isDir = false))+        assertFalse(gi.isIgnored("x/z", isDir = false))+    }++    @Test+    fun emptyMatcherIgnoresNothing() {+        assertFalse(GitIgnore.EMPTY.isIgnored("anything", isDir = false))+    }+}