code: add git source control via JGit (status, stage, commit, branch, diff, clone, pull/push)
- Commit
62f582d9c76851311591151e414f16977b484a1f- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-06 22:48 UTC (4 months ago)
- Parents
7fd4ab8
Diff
code/build.gradle.kts
diff --git a/code/build.gradle.kts b/code/build.gradle.ktsindex 85a7044daa..18a29dc510 100644--- a/code/build.gradle.kts+++ b/code/build.gradle.kts@@ -17,4 +17,5 @@ android { dependencies { implementation(libs.androidx.datastore.preferences)+ implementation(libs.jgit) }
code/src/main/java/com/vayunmathur/code/MainActivity.kt
diff --git a/code/src/main/java/com/vayunmathur/code/MainActivity.kt b/code/src/main/java/com/vayunmathur/code/MainActivity.ktindex b150bf4ddf..09d82953e0 100644--- a/code/src/main/java/com/vayunmathur/code/MainActivity.kt+++ b/code/src/main/java/com/vayunmathur/code/MainActivity.kt@@ -18,6 +18,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import com.vayunmathur.code.ui.EditorPage import com.vayunmathur.code.ui.FolderBrowserPage+import com.vayunmathur.code.ui.GitPage import com.vayunmathur.code.ui.SearchPage import com.vayunmathur.code.ui.SettingsPage import com.vayunmathur.code.util.EditorPrefs@@ -118,6 +119,9 @@ sealed interface Route : NavKey { @Serializable data object FolderBrowser : Route++ @Serializable+ data object Git : Route } @Composable@@ -132,10 +136,12 @@ fun Navigation(viewModel: EditorViewModel) { onOpenSettings = { backStack.add(Route.Settings) }, onOpenSearch = { backStack.add(Route.Search) }, onOpenFolder = { backStack.add(Route.FolderBrowser) },+ onOpenGit = { backStack.add(Route.Git) }, ) } entry<Route.Settings> { SettingsPage(viewModel, backStack) } entry<Route.Search> { SearchPage(viewModel, backStack) } entry<Route.FolderBrowser> { FolderBrowserPage(viewModel, backStack) }+ entry<Route.Git> { GitPage(viewModel, backStack) } } }
code/src/main/java/com/vayunmathur/code/ui/EditorScreen.kt
diff --git a/code/src/main/java/com/vayunmathur/code/ui/EditorScreen.kt b/code/src/main/java/com/vayunmathur/code/ui/EditorScreen.ktindex 26b8a101a3..5379c8081d 100644--- a/code/src/main/java/com/vayunmathur/code/ui/EditorScreen.kt+++ b/code/src/main/java/com/vayunmathur/code/ui/EditorScreen.kt@@ -75,6 +75,7 @@ fun EditorPage( onOpenSettings: () -> Unit = {}, onOpenSearch: () -> Unit = {}, onOpenFolder: () -> Unit = {},+ onOpenGit: () -> Unit = {}, ) { val fileLauncher = rememberLauncherForActivityResult( ActivityResultContracts.OpenDocument()@@ -87,6 +88,7 @@ fun EditorPage( onOpenFile = { fileLauncher.launch(arrayOf("*/*")) }, onOpenSettings = onOpenSettings, onOpenSearch = onOpenSearch,+ onOpenGit = onOpenGit, ) } @@ -106,6 +108,7 @@ fun EditorScreen( onOpenFile: () -> Unit = {}, onOpenSettings: () -> Unit = {}, onOpenSearch: () -> Unit = {},+ onOpenGit: () -> Unit = {}, /** * Seeds for the screen's own UI-only state (is the drawer showing, is the find bar open * and on what query). The app always takes the defaults; previews set them so a given@@ -159,6 +162,7 @@ fun EditorScreen( actions = actions, onToggleFind = { showFind = !showFind }, onOpenSearch = onOpenSearch,+ onOpenGit = onOpenGit, ) HorizontalDivider() CodeEditor(@@ -266,6 +270,7 @@ private fun EditorToolbar( actions: CodeActions, onToggleFind: () -> Unit, onOpenSearch: () -> Unit = {},+ onOpenGit: () -> Unit = {}, ) { val tab = state.currentTab ?: return var showGoToLine by remember { mutableStateOf(false) }@@ -292,6 +297,7 @@ private fun EditorToolbar( Item(text = stringResource(R.string.move_line_down)) { actions.moveLineDown() } Item(text = stringResource(R.string.delete_line)) { actions.deleteLine() } Item(text = stringResource(R.string.search_in_project)) { onOpenSearch() }+ Item(text = stringResource(R.string.source_control)) { onOpenGit() } } Spacer(Modifier.width(8.dp)) Text(
code/src/main/java/com/vayunmathur/code/ui/GitPage.kt
diff --git a/code/src/main/java/com/vayunmathur/code/ui/GitPage.kt b/code/src/main/java/com/vayunmathur/code/ui/GitPage.ktnew file mode 100644index 0000000000..93af3b3990--- /dev/null+++ b/code/src/main/java/com/vayunmathur/code/ui/GitPage.kt@@ -0,0 +1,321 @@+package com.vayunmathur.code.ui++import android.os.Environment+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.heightIn+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.verticalScroll+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.TextStyle+import androidx.compose.ui.text.font.FontFamily+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import com.vayunmathur.code.R+import com.vayunmathur.code.Route+import com.vayunmathur.code.util.EditorViewModel+import com.vayunmathur.library.ui.AlertDialog+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.CircularProgressIndicator+import com.vayunmathur.library.ui.HorizontalDivider+import com.vayunmathur.library.ui.IconAdd+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconClose+import com.vayunmathur.library.ui.IconMerge+import com.vayunmathur.library.ui.IconRefresh+import com.vayunmathur.library.ui.IconRemove+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedTextField+import com.vayunmathur.library.ui.OverflowMenu+import com.vayunmathur.library.ui.SettingsSection+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.util.NavBackStack+import java.io.File++/**+ * Source Control panel over the open project: branch switcher, staged/unstaged change lists with+ * per-file stage toggles, a commit box, pull/push, a unified diff view, plus init/clone and the+ * HTTPS + PAT credentials. All git work runs in the ViewModel off the main thread.+ */+@Composable+fun GitPage(viewModel: EditorViewModel, backStack: NavBackStack<Route>) {+ LaunchedEffect(Unit) { viewModel.refreshGit() }++ AppScaffold(+ title = stringResource(R.string.source_control),+ backStack = backStack,+ actions = {+ IconButton(onClick = { viewModel.refreshGit() }) { IconRefresh() }+ },+ ) { padding ->+ Column(+ Modifier+ .padding(padding)+ .fillMaxSize()+ .verticalScroll(rememberScrollState()),+ ) {+ if (viewModel.gitBusy) {+ Row(+ Modifier.fillMaxWidth().padding(12.dp),+ horizontalArrangement = Arrangement.Center,+ ) { CircularProgressIndicator() }+ }+ viewModel.gitMessage?.let { message ->+ Row(+ Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Text(message, Modifier.weight(1f), color = MaterialTheme.colorScheme.error)+ IconButton(onClick = { viewModel.clearGitMessage() }) { IconClose() }+ }+ }++ if (viewModel.gitIsRepo) {+ RepoSection(viewModel)+ } else {+ NoRepoSection(viewModel)+ }++ CredentialsSection(viewModel)+ }+ }++ viewModel.gitDiff?.let { diff ->+ DiffDialog(diff = diff, onDismiss = { viewModel.clearGitDiff() })+ }+}++@Composable+private fun NoRepoSection(viewModel: EditorViewModel) {+ var cloneUrl by remember { mutableStateOf("") }+ SettingsSection(title = stringResource(R.string.source_control)) {+ Column(Modifier.fillMaxWidth().padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {+ Text(+ stringResource(R.string.not_a_git_repo),+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ Button(onClick = { viewModel.gitInit() }) { Text(stringResource(R.string.git_init)) }+ HorizontalDivider()+ OutlinedTextField(+ value = cloneUrl,+ onValueChange = { cloneUrl = it },+ modifier = Modifier.fillMaxWidth(),+ placeholder = { Text(stringResource(R.string.clone_url_hint)) },+ singleLine = true,+ )+ Button(+ onClick = {+ val into = cloneTargetFor(cloneUrl)+ if (into != null) viewModel.gitClone(cloneUrl.trim(), into)+ },+ enabled = cloneUrl.isNotBlank(),+ ) { Text(stringResource(R.string.git_clone)) }+ }+ }+}++/** Clones into a sibling of the external storage root named after the repo in the URL. */+private fun cloneTargetFor(url: String): File? {+ val name = url.trim().trimEnd('/').substringAfterLast('/').removeSuffix(".git")+ if (name.isBlank()) return null+ return File(Environment.getExternalStorageDirectory(), name)+}++@Composable+private fun RepoSection(viewModel: EditorViewModel) {+ val status = viewModel.gitStatus+ var message by remember { mutableStateOf("") }+ var showNewBranch by remember { mutableStateOf(false) }++ SettingsSection(title = stringResource(R.string.branch)) {+ Row(+ Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ IconMerge()+ Spacer(Modifier.size(8.dp))+ Text(status?.branch.orEmpty(), Modifier.weight(1f))+ OverflowMenu(icon = { Text(stringResource(R.string.switch_branch)) }) {+ viewModel.gitBranches.forEach { branch ->+ Item(text = branch) { viewModel.gitCheckout(branch) }+ }+ }+ TextButton(onClick = { showNewBranch = true }) { Text(stringResource(R.string.new_branch)) }+ }+ Row(+ Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 4.dp),+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ Button(onClick = { viewModel.gitPull() }) { Text(stringResource(R.string.git_pull)) }+ Button(onClick = { viewModel.gitPush() }) { Text(stringResource(R.string.git_push)) }+ }+ }++ SettingsSection(title = stringResource(R.string.commit)) {+ Column(Modifier.fillMaxWidth().padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {+ OutlinedTextField(+ value = message,+ onValueChange = { message = it },+ modifier = Modifier.fillMaxWidth(),+ placeholder = { Text(stringResource(R.string.commit_message)) },+ )+ Button(+ onClick = { viewModel.gitCommit(message.trim()); message = "" },+ enabled = message.isNotBlank() && status?.staged?.isNotEmpty() == true,+ ) { Text(stringResource(R.string.commit)) }+ }+ }++ if (status != null) {+ ChangeList(+ title = stringResource(R.string.staged_changes),+ paths = status.staged,+ staged = true,+ viewModel = viewModel,+ )+ ChangeList(+ title = stringResource(R.string.changes),+ paths = status.unstaged + status.untracked,+ staged = false,+ viewModel = viewModel,+ )+ if (status.isClean) {+ Text(+ stringResource(R.string.no_changes),+ Modifier.padding(16.dp),+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ }++ if (showNewBranch) {+ var name by remember { mutableStateOf("") }+ AlertDialog(+ onDismissRequest = { showNewBranch = false },+ title = { Text(stringResource(R.string.new_branch)) },+ text = {+ OutlinedTextField(+ value = name,+ onValueChange = { name = it },+ singleLine = true,+ label = { Text(stringResource(R.string.name)) },+ )+ },+ confirmButton = {+ TextButton(+ onClick = { viewModel.gitCreateBranch(name.trim()); showNewBranch = false },+ enabled = name.isNotBlank(),+ ) { Text(stringResource(R.string.create)) }+ },+ dismissButton = {+ TextButton(onClick = { showNewBranch = false }) { Text(stringResource(R.string.cancel)) }+ },+ )+ }+}++@Composable+private fun ChangeList(title: String, paths: List<String>, staged: Boolean, viewModel: EditorViewModel) {+ if (paths.isEmpty()) return+ Text(+ text = title,+ modifier = Modifier.padding(start = 16.dp, top = 12.dp, bottom = 4.dp),+ style = MaterialTheme.typography.titleSmall,+ color = MaterialTheme.colorScheme.primary,+ )+ paths.forEach { path ->+ Row(+ Modifier+ .fillMaxWidth()+ .clickable { viewModel.loadGitDiff(path, staged) }+ .padding(start = 16.dp, end = 4.dp, top = 6.dp, bottom = 6.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Text(path, Modifier.weight(1f), maxLines = 1, overflow = TextOverflow.Ellipsis)+ if (staged) {+ IconButton(onClick = { viewModel.gitUnstage(path) }) { IconRemove() }+ } else {+ IconButton(onClick = { viewModel.gitStage(path) }) { IconAdd() }+ }+ }+ }+}++@Composable+private fun CredentialsSection(viewModel: EditorViewModel) {+ SettingsSection(title = stringResource(R.string.git_credentials)) {+ Column(Modifier.fillMaxWidth().padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {+ OutlinedTextField(+ value = viewModel.gitUsername,+ onValueChange = viewModel::setGitUsername,+ modifier = Modifier.fillMaxWidth(),+ singleLine = true,+ label = { Text(stringResource(R.string.git_username)) },+ )+ OutlinedTextField(+ value = viewModel.gitToken,+ onValueChange = viewModel::setGitToken,+ modifier = Modifier.fillMaxWidth(),+ singleLine = true,+ label = { Text(stringResource(R.string.git_token)) },+ )+ OutlinedTextField(+ value = viewModel.gitAuthorName,+ onValueChange = viewModel::setGitAuthorName,+ modifier = Modifier.fillMaxWidth(),+ singleLine = true,+ label = { Text(stringResource(R.string.git_author_name)) },+ )+ OutlinedTextField(+ value = viewModel.gitAuthorEmail,+ onValueChange = viewModel::setGitAuthorEmail,+ modifier = Modifier.fillMaxWidth(),+ singleLine = true,+ label = { Text(stringResource(R.string.git_author_email)) },+ )+ }+ }+}++/** A unified-diff viewer that colours added/removed/hunk lines. */+@Composable+private fun DiffDialog(diff: String, onDismiss: () -> Unit) {+ AlertDialog(+ onDismissRequest = onDismiss,+ title = { Text(stringResource(R.string.diff)) },+ text = {+ Column(Modifier.heightIn(max = 400.dp).verticalScroll(rememberScrollState())) {+ val lines = if (diff.isBlank()) listOf(stringResource(R.string.no_changes)) else diff.lines()+ lines.forEach { line ->+ val color = when {+ line.startsWith("+") && !line.startsWith("+++") -> MaterialTheme.colorScheme.tertiary+ line.startsWith("-") && !line.startsWith("---") -> MaterialTheme.colorScheme.error+ line.startsWith("@@") -> MaterialTheme.colorScheme.primary+ else -> MaterialTheme.colorScheme.onSurfaceVariant+ }+ Text(text = line, color = color, style = TextStyle(fontFamily = FontFamily.Monospace))+ }+ }+ },+ confirmButton = {+ TextButton(onClick = onDismiss) { Text(stringResource(R.string.close)) }+ },+ )+}
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 3a89e9d615..4b933cfb4e 100644--- a/code/src/main/java/com/vayunmathur/code/util/EditorPrefs.kt+++ b/code/src/main/java/com/vayunmathur/code/util/EditorPrefs.kt@@ -40,6 +40,12 @@ class EditorPrefs(context: Context) { /** File path of the tab that was in the foreground, for session restore. */ val sessionCurrent: Flow<String?> = appContext.editorDataStore.data.map { it[SESSION_CURRENT_KEY] } + // Git remote credentials + author. DataStore is not encrypted; acceptable for F-Droid/local.+ val gitUsername: Flow<String> = appContext.editorDataStore.data.map { it[GIT_USERNAME_KEY] ?: "" }+ val gitToken: Flow<String> = appContext.editorDataStore.data.map { it[GIT_TOKEN_KEY] ?: "" }+ val gitAuthorName: Flow<String> = appContext.editorDataStore.data.map { it[GIT_AUTHOR_NAME_KEY] ?: "" }+ val gitAuthorEmail: Flow<String> = appContext.editorDataStore.data.map { it[GIT_AUTHOR_EMAIL_KEY] ?: "" }+ suspend fun setFolderPath(path: String) { appContext.editorDataStore.edit { it[FOLDER_PATH_KEY] = path } }@@ -85,6 +91,22 @@ class EditorPrefs(context: Context) { } } + suspend fun setGitUsername(value: String) {+ appContext.editorDataStore.edit { it[GIT_USERNAME_KEY] = value }+ }++ suspend fun setGitToken(value: String) {+ appContext.editorDataStore.edit { it[GIT_TOKEN_KEY] = value }+ }++ suspend fun setGitAuthorName(value: String) {+ appContext.editorDataStore.edit { it[GIT_AUTHOR_NAME_KEY] = value }+ }++ suspend fun setGitAuthorEmail(value: String) {+ appContext.editorDataStore.edit { it[GIT_AUTHOR_EMAIL_KEY] = value }+ }+ companion object { const val DEFAULT_FONT_SIZE = 14 const val DEFAULT_TAB_WIDTH = 4@@ -102,5 +124,9 @@ class EditorPrefs(context: Context) { private val AUTO_SAVE_KEY = booleanPreferencesKey("auto_save") private val SESSION_PATHS_KEY = stringPreferencesKey("session_paths") private val SESSION_CURRENT_KEY = stringPreferencesKey("session_current")+ private val GIT_USERNAME_KEY = stringPreferencesKey("git_username")+ private val GIT_TOKEN_KEY = stringPreferencesKey("git_token")+ private val GIT_AUTHOR_NAME_KEY = stringPreferencesKey("git_author_name")+ private val GIT_AUTHOR_EMAIL_KEY = stringPreferencesKey("git_author_email") } }
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 67eb8f7587..3621e09b92 100644--- a/code/src/main/java/com/vayunmathur/code/util/EditorViewModel.kt+++ b/code/src/main/java/com/vayunmathur/code/util/EditorViewModel.kt@@ -155,6 +155,29 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), var showCompletions by mutableStateOf(false) private set + // ---- Git ----+ var gitIsRepo by mutableStateOf(false)+ private set+ var gitStatus by mutableStateOf<GitStatus?>(null)+ private set+ val gitLog = mutableStateListOf<GitCommitInfo>()+ val gitBranches = mutableStateListOf<String>()+ var gitBusy by mutableStateOf(false)+ private set+ var gitMessage by mutableStateOf<String?>(null)+ private set+ var gitDiff by mutableStateOf<String?>(null)+ private set++ private val _gitUsername = mutableStateOf("")+ val gitUsername: String get() = _gitUsername.value+ private val _gitToken = mutableStateOf("")+ val gitToken: String get() = _gitToken.value+ private val _gitAuthorName = mutableStateOf("")+ val gitAuthorName: String get() = _gitAuthorName.value+ private val _gitAuthorEmail = mutableStateOf("")+ val gitAuthorEmail: String get() = _gitAuthorEmail.value+ /** Snapshot of everything the screens draw; rebuilt on every read, as Compose expects. */ val uiState: CodeUiState get() = CodeUiState(@@ -198,6 +221,10 @@ 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 { _gitUsername.value = prefs.gitUsername.first() }+ viewModelScope.launch { _gitToken.value = prefs.gitToken.first() }+ viewModelScope.launch { _gitAuthorName.value = prefs.gitAuthorName.first() }+ viewModelScope.launch { _gitAuthorEmail.value = prefs.gitAuthorEmail.first() } viewModelScope.launch { val stored = prefs.folderPath.first() ?: return@launch val dir = File(stored)@@ -259,6 +286,7 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), rootName = dir.name nodes.clear() nodes.addAll(children.map { TreeNode(it, depth = 0) })+ refreshGit() } /** Expands/collapses a directory row, or opens a file row in a tab. */@@ -552,6 +580,122 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), showCompletions = false } + // ---- Git ----++ /** Re-reads repo status, log and branches for the open folder (no-op if none is open). */+ fun refreshGit() {+ val dir = rootDir+ if (dir == null) {+ gitIsRepo = false+ gitStatus = null+ gitLog.clear()+ gitBranches.clear()+ return+ }+ viewModelScope.launch {+ gitIsRepo = withContext(Dispatchers.IO) { GitRepo.isRepo(dir) }+ if (gitIsRepo) {+ runCatching { loadGitState(dir) }.onFailure { gitMessage = it.message ?: it.toString() }+ } else {+ gitStatus = null+ gitLog.clear()+ gitBranches.clear()+ }+ }+ }++ private suspend fun loadGitState(dir: File) {+ val status = withContext(Dispatchers.IO) { GitRepo.status(dir) }+ val log = withContext(Dispatchers.IO) { GitRepo.log(dir, GIT_LOG_LIMIT) }+ val branches = withContext(Dispatchers.IO) { GitRepo.branches(dir) }+ gitStatus = status+ gitLog.clear(); gitLog.addAll(log)+ gitBranches.clear(); gitBranches.addAll(branches)+ }++ /** Runs a git mutation off-main, surfacing failures in [gitMessage], then refreshes status. */+ private fun gitOp(block: suspend (File) -> Unit) {+ val dir = rootDir ?: return+ viewModelScope.launch {+ gitBusy = true+ gitMessage = null+ runCatching { withContext(Dispatchers.IO) { block(dir) } }+ .onFailure { gitMessage = it.message ?: it.toString() }+ gitIsRepo = withContext(Dispatchers.IO) { GitRepo.isRepo(dir) }+ if (gitIsRepo) runCatching { loadGitState(dir) }+ gitBusy = false+ }+ }++ fun gitInit() = gitOp { GitRepo.init(it) }+ fun gitStage(path: String) = gitOp { GitRepo.stage(it, path) }+ fun gitUnstage(path: String) = gitOp { GitRepo.unstage(it, path) }+ fun gitPull() = gitOp { GitRepo.pull(it, gitUsername, gitToken) }+ fun gitPush() = gitOp { GitRepo.push(it, gitUsername, gitToken) }+ fun gitCheckout(name: String) = gitOp { GitRepo.checkout(it, name) }++ fun gitCreateBranch(name: String) = gitOp {+ GitRepo.createBranch(it, name)+ GitRepo.checkout(it, name)+ }++ fun gitCommit(message: String) = gitOp { dir ->+ val name = gitAuthorName.ifBlank { "Code" }+ val email = gitAuthorEmail.ifBlank { "code@localhost" }+ GitRepo.commit(dir, message, name, email)+ }++ /** Clones [url] into [into] and, on success, opens it as the project. */+ fun gitClone(url: String, into: File) {+ viewModelScope.launch {+ gitBusy = true+ gitMessage = null+ val result = runCatching {+ withContext(Dispatchers.IO) { GitRepo.clone(url, into, gitUsername, gitToken) }+ }+ gitBusy = false+ result.onSuccess { openFolder(into) }+ .onFailure { gitMessage = it.message ?: it.toString() }+ }+ }++ fun loadGitDiff(path: String, staged: Boolean) {+ val dir = rootDir ?: return+ viewModelScope.launch {+ gitDiff = runCatching {+ withContext(Dispatchers.IO) { GitRepo.diff(dir, path, staged) }+ }.getOrDefault("")+ }+ }++ fun clearGitDiff() {+ gitDiff = null+ }++ fun clearGitMessage() {+ gitMessage = null+ }++ fun setGitUsername(value: String) {+ _gitUsername.value = value+ viewModelScope.launch { prefs.setGitUsername(value) }+ }++ fun setGitToken(value: String) {+ _gitToken.value = value+ viewModelScope.launch { prefs.setGitToken(value) }+ }++ fun setGitAuthorName(value: String) {+ _gitAuthorName.value = value+ viewModelScope.launch { prefs.setGitAuthorName(value) }+ }++ fun setGitAuthorEmail(value: String) {+ _gitAuthorEmail.value = value+ viewModelScope.launch { prefs.setGitAuthorEmail(value) }+ }+ /** Debounced auto-save: writes the current tab a short idle period after the last edit. */ private fun scheduleAutoSave() { autoSaveJob?.cancel()@@ -614,6 +758,7 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), runCatching { FileFiles.writeText(file, textToSave) }.isSuccess } if (ok) tab.savedText = textToSave+ if (ok && gitIsRepo) refreshGit() } } @@ -779,6 +924,7 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), const val AUTO_SAVE_DELAY_MS = 1500L const val MIN_COMPLETION_PREFIX = 1 const val MAX_COMPLETIONS = 50+ const val GIT_LOG_LIMIT = 30 const val MAX_SEARCH_RESULTS = 500 const val MAX_MATCHES_PER_FILE = 50 const val MAX_SEARCH_FILE_SIZE = 500_000
code/src/main/java/com/vayunmathur/code/util/GitRepo.kt
diff --git a/code/src/main/java/com/vayunmathur/code/util/GitRepo.kt b/code/src/main/java/com/vayunmathur/code/util/GitRepo.ktnew file mode 100644index 0000000000..cbd7eb9b04--- /dev/null+++ b/code/src/main/java/com/vayunmathur/code/util/GitRepo.kt@@ -0,0 +1,147 @@+package com.vayunmathur.code.util++import org.eclipse.jgit.api.Git+import org.eclipse.jgit.lib.Constants+import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider+import org.eclipse.jgit.treewalk.filter.PathFilter+import java.io.ByteArrayOutputStream+import java.io.File++/** Current repository status: the branch plus the three change buckets, each a list of paths. */+data class GitStatus(+ val branch: String,+ val staged: List<String>,+ val unstaged: List<String>,+ val untracked: List<String>,+) {+ val isClean: Boolean get() = staged.isEmpty() && unstaged.isEmpty() && untracked.isEmpty()+}++/** One entry in the commit log. */+data class GitCommitInfo(+ val shortId: String,+ val message: String,+ val author: String,+ val timeSeconds: Long,+)++/**+ * IO-only wrapper over JGit. Every call opens the repository fresh and closes it, so callers hold+ * no handles; all methods block and must run off the main thread (the ViewModel does this).+ *+ * Remote auth is HTTPS + Personal Access Token only (no SSH). JGit's default transport is+ * `HttpURLConnection`-based, so no extra HTTP dependency is pulled in.+ */+object GitRepo {++ /** True if [dir] (or JGit's discovery from it) contains a git repository. */+ fun isRepo(dir: File): Boolean = File(dir, Constants.DOT_GIT).exists()++ fun init(dir: File) {+ Git.init().setDirectory(dir).call().close()+ }++ private inline fun <T> withRepo(dir: File, block: (Git) -> T): T =+ Git.open(dir).use(block)++ fun currentBranch(dir: File): String = withRepo(dir) { it.repository.branch ?: "" }++ fun status(dir: File): GitStatus = withRepo(dir) { git ->+ val s = git.status().call()+ GitStatus(+ branch = git.repository.branch ?: "",+ staged = (s.added + s.changed + s.removed).sorted().distinct(),+ unstaged = (s.modified + s.missing).sorted().distinct(),+ untracked = s.untracked.sorted(),+ )+ }++ fun stage(dir: File, path: String) = withRepo(dir) { git ->+ // add() also stages deletions on recent JGit; call rm for a path that no longer exists.+ if (File(dir, path).exists()) {+ git.add().addFilepattern(path).call()+ } else {+ git.rm().addFilepattern(path).setCached(true).call()+ }+ Unit+ }++ fun unstage(dir: File, path: String) = withRepo(dir) { git ->+ git.reset().addPath(path).call()+ Unit+ }++ fun commit(dir: File, message: String, name: String, email: String): String = withRepo(dir) { git ->+ val commit = git.commit()+ .setMessage(message)+ .setAuthor(name, email)+ .setCommitter(name, email)+ .call()+ commit.abbreviate(7).name()+ }++ fun log(dir: File, max: Int = 50): List<GitCommitInfo> = withRepo(dir) { git ->+ if (git.repository.resolve(Constants.HEAD) == null) return@withRepo emptyList()+ git.log().setMaxCount(max).call().map { commit ->+ GitCommitInfo(+ shortId = commit.abbreviate(7).name(),+ message = commit.shortMessage,+ author = commit.authorIdent.name,+ timeSeconds = commit.commitTime.toLong(),+ )+ }+ }++ /** Unified diff for [path]; [staged] chooses the index-vs-HEAD diff over the worktree one. */+ fun diff(dir: File, path: String, staged: Boolean): String = withRepo(dir) { git ->+ ByteArrayOutputStream().use { out ->+ git.diff()+ .setOutputStream(out)+ .setCached(staged)+ .setPathFilter(PathFilter.create(path))+ .call()+ out.toString(Charsets.UTF_8.name())+ }+ }++ fun branches(dir: File): List<String> = withRepo(dir) { git ->+ git.branchList().call().map { it.name.removePrefix(Constants.R_HEADS) }+ }++ fun createBranch(dir: File, name: String) = withRepo(dir) { git ->+ git.branchCreate().setName(name).call()+ Unit+ }++ fun checkout(dir: File, name: String) = withRepo(dir) { git ->+ git.checkout().setName(name).call()+ Unit+ }++ fun clone(url: String, dir: File, username: String, token: String) {+ Git.cloneRepository()+ .setURI(url)+ .setDirectory(dir)+ .apply { if (token.isNotBlank()) setCredentialsProvider(credentials(username, token)) }+ .call()+ .close()+ }++ fun pull(dir: File, username: String, token: String) = withRepo(dir) { git ->+ git.pull()+ .apply { if (token.isNotBlank()) setCredentialsProvider(credentials(username, token)) }+ .call()+ Unit+ }++ fun push(dir: File, username: String, token: String) = withRepo(dir) { git ->+ git.push()+ .apply { if (token.isNotBlank()) setCredentialsProvider(credentials(username, token)) }+ .call()+ Unit+ }++ /** For a GitHub-style PAT the username is often the token itself; fall back to that if blank. */+ private fun credentials(username: String, token: String) =+ UsernamePasswordCredentialsProvider(username.ifBlank { token }, token)+}
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 1f1b6fb0b4..c6e2f8caeb 100644--- a/code/src/main/res/values/strings.xml+++ b/code/src/main/res/values/strings.xml@@ -59,4 +59,25 @@ <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="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>+ <string name="git_clone">Clone</string>+ <string name="clone_url_hint">https://github.com/user/repo.git</string>+ <string name="branch">Branch</string>+ <string name="switch_branch">Switch</string>+ <string name="new_branch">New branch</string>+ <string name="git_pull">Pull</string>+ <string name="git_push">Push</string>+ <string name="commit">Commit</string>+ <string name="commit_message">Commit message</string>+ <string name="staged_changes">Staged changes</string>+ <string name="changes">Changes</string>+ <string name="no_changes">No changes</string>+ <string name="diff">Diff</string>+ <string name="git_credentials">Credentials (HTTPS + token)</string>+ <string name="git_username">Username</string>+ <string name="git_token">Personal access token</string>+ <string name="git_author_name">Author name</string>+ <string name="git_author_email">Author email</string> </resources>
gradle/libs.versions.toml
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex 78fc449dc5..3546eec756 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -87,6 +87,9 @@ flatgeobuf = "3.29.0" # JavaScript engines & HTML quickjs = "1.0.5" +# Git+jgit = "6.10.0.202406032230-r"+ # On-device AI onnxruntimeAndroid = "1.27.0" @@ -234,6 +237,9 @@ flatgeobuf = { module = "org.wololo:flatgeobuf", version.ref = "flatgeobuf" } # JavaScript engines & HTML quickjs-kt = { module = "io.github.dokar3:quickjs-kt", version.ref = "quickjs" } +# Git+jgit = { module = "org.eclipse.jgit:org.eclipse.jgit", version.ref = "jgit" }+ # On-device AI onnxruntime-android = { module = "com.microsoft.onnxruntime:onnxruntime-android", version.ref = "onnxruntimeAndroid" }