madeveloper: browse repos via git host JSON (#madev)
- Commit
5c0472a14aba171ae374a13e2353b893423a57b1- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-16 17:32 UTC (19 days ago)
- Parents
5efdead
Replace smart-HTTP info/refs parsing and the GitHub push-mirror contents API with the git host first-party JSON API on https://git.maproj.org (NetworkClient, FIRST_PARTY as before): - GET /api/repos drives the home repo list (defaultBranch, head sha/subject/time); GET /api/repos/<repo> drives the repo screen with branches and recentCommits. - Branch switching via the shared SelectDropdown resets the tree to the root and reloads commits; tree browsing and file view use /tree and /file with repo+branch+path caching, binary/truncated files labelled instead of dumped as text. - New commits screen pages /commits with branch/limit/after, and a commit detail screen shows subject/body/author/time/sha. The JSON API has no diff endpoint, so detail links out to the git host instead of inventing a diff view. - Pure domain layer: new GitBranch/GitCommit/RepoDetail/GitFile models, GitParsers parsers for every new endpoint (ISO or epoch times), and RepoBrowser/RepoBrowserState state holder for branch, tree-path, commit paging and selection transitions. - /tests, issues, PRs, catalog and push features are unchanged. The server API is being built in parallel and may 404 until deployed; errors surface as-is with no mirror fallback. Verified: ./gradlew :madeveloper:testDevUnitTest :madeveloper:detekt :madeveloper:lint (direct on host) — green, 20 unit tests including new parser fixtures and RepoBrowser navigation/paging tests.
Diff
madeveloper/AGENTS.md
diff --git a/madeveloper/AGENTS.md b/madeveloper/AGENTS.mdindex 12c8b21f16..4f92fc7a63 100644--- a/madeveloper/AGENTS.md+++ b/madeveloper/AGENTS.md@@ -14,13 +14,13 @@ _Install: ./install madeveloper (dev by default)._ ## Overview **Purpose:** Developer companion for the maproj infrastructure: git host pages, CI status, a read-only build catalog, and server-pushed dev installs. **Key features:**-- Git pages over the host JSON (`/tests.json`, `/issues.json`, `/prs.json`) and smart-HTTP refs; the host has no repo-browsing pages, so files read via its GitHub push-mirror+- Git pages over the host JSON (`/tests.json`, `/issues.json`, `/prs.json`) and native repo browsing via the first-party JSON API (`/api/repos[/<repo>]`, `/commits`, `/tree`, `/file` on git.maproj.org) with branch switching and commit detail (no diff endpoint: metadata + link-out) - Read-only F-Droid catalog (`static.maproj.org/fdroid/repo/index-v2.json`, newest build per package) - Pushed installs: paired WebSocket to `wss://api.maproj.org/dev/ws`, download + SHA-256 verify, then a user-tapped PackageInstaller session (never silent) **Architecture / data-flow:** `ui/` screens → `platform/MaDevViewModel` → `data/GitHostRepository` (NetworkClient, FIRST_PARTY) + `data/DevPushClient` seam over `WebSocketClient`; pure parsing and the install state machine live in `domain/` (`GitParsers`, `DevProtocol`) with no Android imports. **Entry points + reading order:** `Route` → `MainActivity.kt` → `Navigation.kt` → `platform/MaDevViewModel.kt` → `data/GitHostRepository.kt` / `domain/DevProtocol.kt`. **Gotchas:**-- The git host exposes no commits/tree/file endpoints — do not invent them; mirror reads plus a link-out are the honest v1+- The JSON API has no diff endpoint — commit detail shows metadata (subject/body/author/time) plus a link-out to the git host; do not invent a diff view. The API may 404 until deployed server-side - Android forbids silent installs here by design: a push only downloads and verifies, the Install button and system prompt do the rest - The `/dev/ws` server endpoint is built in parallel; the client is coded to the agreed JSON contract behind `DevSocketTransport` @@ -35,6 +35,7 @@ _Install: ./install madeveloper (dev by default)._ ### domain/ — pure models, parsers and push protocol - com/vayunmathur/madeveloper/domain/GitModels.kt - com/vayunmathur/madeveloper/domain/GitParsers.kt+- com/vayunmathur/madeveloper/domain/RepoBrowser.kt - com/vayunmathur/madeveloper/domain/DevProtocol.kt ### platform/ — view model, pairing, notifications, installer - com/vayunmathur/madeveloper/platform/MaDevViewModel.kt@@ -45,6 +46,8 @@ _Install: ./install madeveloper (dev by default)._ ### ui/ — screens - com/vayunmathur/madeveloper/ui/HomeScreen.kt - com/vayunmathur/madeveloper/ui/RepoScreen.kt+- com/vayunmathur/madeveloper/ui/CommitsScreen.kt+- com/vayunmathur/madeveloper/ui/CommitScreen.kt - com/vayunmathur/madeveloper/ui/FileScreen.kt - com/vayunmathur/madeveloper/ui/TestsScreen.kt - com/vayunmathur/madeveloper/ui/CatalogScreen.kt
madeveloper/src/main/java/com/vayunmathur/madeveloper/Navigation.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/Navigation.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/Navigation.ktindex 049fe3d5db..cb6d7dada1 100644--- a/madeveloper/src/main/java/com/vayunmathur/madeveloper/Navigation.kt+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/Navigation.kt@@ -6,6 +6,8 @@ import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.rememberNavBackStack import com.vayunmathur.madeveloper.platform.MaDevViewModel import com.vayunmathur.madeveloper.ui.CatalogScreen+import com.vayunmathur.madeveloper.ui.CommitScreen+import com.vayunmathur.madeveloper.ui.CommitsScreen import com.vayunmathur.madeveloper.ui.FileScreen import com.vayunmathur.madeveloper.ui.HomeScreen import com.vayunmathur.madeveloper.ui.PushScreen@@ -31,11 +33,33 @@ fun Navigation(viewModel: MaDevViewModel) { entry<Route.Repo> { route -> RepoScreen( repoName = route.name, viewModel = viewModel,- onOpenFile = { backStack.add(Route.File(route.name, it)) }, onBack = { backStack.pop() },+ onOpenFile = { branch, path -> backStack.add(Route.File(route.name, path, branch)) },+ onOpenCommits = { branch -> backStack.add(Route.Commits(route.name, branch)) },+ onOpenCommit = { branch, sha ->+ viewModel.selectCommit(route.name, sha)+ backStack.add(Route.Commit(route.name, branch, sha))+ },+ onBack = { backStack.pop() }, ) }+ entry<Route.Commits> { route ->+ CommitsScreen(+ repoName = route.repo, branch = route.branch, viewModel = viewModel,+ onOpenCommit = { sha ->+ viewModel.selectCommit(route.repo, sha)+ backStack.add(Route.Commit(route.repo, route.branch, sha))+ },+ onBack = { backStack.pop() },+ )+ }+ entry<Route.Commit> { route ->+ CommitScreen(repoName = route.repo, sha = route.sha, viewModel = viewModel, onBack = { backStack.pop() })+ } entry<Route.File> { route ->- FileScreen(repoName = route.repo, path = route.path, viewModel = viewModel, onBack = { backStack.pop() })+ FileScreen(+ repoName = route.repo, path = route.path, branch = route.branch,+ viewModel = viewModel, onBack = { backStack.pop() },+ ) } entry<Route.Tests> { TestsScreen(state = viewModel.state, onBack = { backStack.pop() }) } entry<Route.Catalog> {
madeveloper/src/main/java/com/vayunmathur/madeveloper/Route.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/Route.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/Route.ktindex 6de8f8b77d..53f83fac9d 100644--- a/madeveloper/src/main/java/com/vayunmathur/madeveloper/Route.kt+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/Route.kt@@ -11,12 +11,20 @@ sealed interface Route : NavKey { data object Home : Route @Serializable- /** One repository: refs, issues, pull requests and file tree. */+ /** One repository: branches, recent commits and file tree. */ data class Repo(val name: String) : Route @Serializable- /** One file in a repository, shown with line numbers. */- data class File(val repo: String, val path: String) : Route+ /** Commits of one repository on one branch. */+ data class Commits(val repo: String, val branch: String) : Route++ @Serializable+ /** One commit's metadata; the JSON API has no diff endpoint. */+ data class Commit(val repo: String, val branch: String, val sha: String) : Route++ @Serializable+ /** One file in a repository on a branch, shown with line numbers. */+ data class File(val repo: String, val path: String, val branch: String) : Route @Serializable /** Full CI history from the git host tests page. */
madeveloper/src/main/java/com/vayunmathur/madeveloper/data/GitHostRepository.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/data/GitHostRepository.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/data/GitHostRepository.ktindex f07a0af1be..9a2ad52ef3 100644--- a/madeveloper/src/main/java/com/vayunmathur/madeveloper/data/GitHostRepository.kt+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/data/GitHostRepository.kt@@ -2,42 +2,43 @@ package com.vayunmathur.madeveloper.data import com.vayunmathur.library.network.NetworkClient import com.vayunmathur.madeveloper.domain.CatalogApp+import com.vayunmathur.madeveloper.domain.GitCommit+import com.vayunmathur.madeveloper.domain.GitFile import com.vayunmathur.madeveloper.domain.GitIssue import com.vayunmathur.madeveloper.domain.GitParsers import com.vayunmathur.madeveloper.domain.GitPr import com.vayunmathur.madeveloper.domain.GitRepo+import com.vayunmathur.madeveloper.domain.RepoDetail import com.vayunmathur.madeveloper.domain.TestsStatus import com.vayunmathur.madeveloper.domain.TreeEntry-import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.withContext-import kotlinx.serialization.json.Json-import kotlinx.serialization.json.JsonArray-import kotlinx.serialization.json.JsonObject-import kotlinx.serialization.json.contentOrNull-import kotlinx.serialization.json.jsonObject-import kotlinx.serialization.json.jsonPrimitive-import kotlinx.serialization.json.longOrNull-import java.util.Base64+import java.net.URLEncoder /**- * Reads the maproj git host through [NetworkClient] (FIRST_PARTY trust is set- * once by the activity). The host serves clone + dashboards only, so code- * browsing reads the host's own GitHub push-mirror contents API; every screen- * still links out to the canonical git host page as a fallback.+ * Reads the maproj git host through [NetworkClient] (FIRST_PARTY trust is+ * set once by the activity). Repositories, branches, commits, trees and+ * files all come from the host's first-party JSON API under `/api/repos`;+ * CI, issues, pull requests and the F-Droid catalog keep their existing+ * endpoints. The JSON API may not be deployed yet — callers surface the+ * HTTP error (e.g. 404) rather than falling back to any mirror. */ class GitHostRepository {- private val json = Json { ignoreUnknownKeys = true; isLenient = true } private var treeCache: Map<String, List<TreeEntry>> = emptyMap()- private var fileCache: Map<String, String> = emptyMap()+ private var fileCache: Map<String, GitFile> = emptyMap() - /** Repositories with their advertised refs filled in. */- suspend fun repos(): List<GitRepo> = GitParsers.knownRepos.map { repo ->- val refs = runCatching {- val refsUrl = repo.cloneUrl.removeSuffix(".git") + ".git/info/refs?service=git-upload-pack"- val (status, bytes) = NetworkClient.performRequestBytes(refsUrl)- if (status in 200..299) GitParsers.parseRefs(bytes) else emptyList()- }.getOrDefault(emptyList())- repo.copy(refs = refs)+ /** Repositories from `GET /api/repos`. */+ suspend fun repos(): List<GitRepo> = GitParsers.parseRepos(fetchText("$GIT_HOST/api/repos"))++ /** Branches and recent commits from `GET /api/repos/<repo>`. */+ suspend fun repo(name: String): RepoDetail =+ GitParsers.parseRepoDetail(fetchText("$GIT_HOST/api/repos/${enc(name)}"))++ /** One page of commits; [after] is the previous page's last sha. */+ suspend fun commits(name: String, branch: String, limit: Int, after: String?): List<GitCommit> {+ val query = buildString {+ append("?branch=").append(enc(branch)).append("&limit=").append(limit)+ if (!after.isNullOrBlank()) append("&after=").append(enc(after))+ }+ return GitParsers.parseCommits(fetchText("$GIT_HOST/api/repos/${enc(name)}/commits$query")) } /** CI status from `/tests.json`. */@@ -53,41 +54,24 @@ class GitHostRepository { suspend fun catalog(): List<CatalogApp> = GitParsers.parseFdroidIndex(fetchText("$FDROID_BASE/index-v2.json"), FDROID_BASE) - /** Tree of [path] in [repo] via the mirror contents API; cached per repo+path. */- suspend fun tree(repo: GitRepo, path: String): List<TreeEntry> {- val key = repo.name + ":" + path+ /** Tree of [path] in [repo] on [branch]; cached per repo+branch+path. */+ suspend fun tree(repo: String, branch: String, path: String): List<TreeEntry> {+ val key = "$repo:$branch:$path" treeCache[key]?.let { return it }- val github = repo.github ?: return emptyList()- val url = "https://api.github.com/repos/$github/contents/$path"- val entries = parseTree(fetchText(url))+ val url = "$GIT_HOST/api/repos/${enc(repo)}/tree?branch=${enc(branch)}&path=${enc(path)}"+ val entries = GitParsers.parseTree(fetchText(url), path) treeCache = treeCache + (key to entries) return entries } - /** File text of [path] in [repo] via the mirror contents API; cached. */- suspend fun file(repo: GitRepo, path: String): String {- val key = repo.name + ":" + path+ /** File at [path] in [repo] on [branch]; cached per repo+branch+path. */+ suspend fun file(repo: String, branch: String, path: String): GitFile {+ val key = "$repo:$branch:$path" fileCache[key]?.let { return it }- val github = repo.github ?: return ""- val root = json.parseToJsonElement(fetchText("https://api.github.com/repos/$github/contents/$path")).jsonObject- val encoded = root["content"]?.jsonPrimitive?.contentOrNull ?: return ""- val text = withContext(Dispatchers.IO) { String(Base64.getMimeDecoder().decode(encoded), Charsets.UTF_8) }- fileCache = fileCache + (key to text)- return text- }-- private fun parseTree(text: String): List<TreeEntry> {- val root = json.parseToJsonElement(text)- val array = root as? JsonArray ?: return emptyList()- return array.mapNotNull { element ->- val obj = element as? JsonObject ?: return@mapNotNull null- TreeEntry(- name = obj["name"]?.jsonPrimitive?.contentOrNull ?: return@mapNotNull null,- path = obj["path"]?.jsonPrimitive?.contentOrNull ?: "",- isDir = obj["type"]?.jsonPrimitive?.contentOrNull == "dir",- size = obj["size"]?.jsonPrimitive?.longOrNull,- )- }.sortedWith(compareByDescending<TreeEntry> { it.isDir }.thenBy { it.name.lowercase() })+ val url = "$GIT_HOST/api/repos/${enc(repo)}/file?branch=${enc(branch)}&path=${enc(path)}"+ val file = GitParsers.parseFile(fetchText(url))+ fileCache = fileCache + (key to file)+ return file } private suspend fun fetchText(url: String): String {@@ -102,5 +86,11 @@ class GitHostRepository { const val GIT_HOST = "https://git.maproj.org" const val FDROID_BASE = "https://static.maproj.org/fdroid/repo" const val DEV_WS_URL = "wss://api.maproj.org/dev/ws"++ /** Default commits page size for the commits screen. */+ const val COMMITS_PAGE_SIZE = 30 } }++/** URL-encodes one path segment or query value. */+private fun enc(value: String): String = URLEncoder.encode(value, "UTF-8").replace("+", "%20")
madeveloper/src/main/java/com/vayunmathur/madeveloper/domain/GitModels.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/domain/GitModels.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/domain/GitModels.ktindex 53c8e5c244..127e6072ff 100644--- a/madeveloper/src/main/java/com/vayunmathur/madeveloper/domain/GitModels.kt+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/domain/GitModels.kt@@ -1,14 +1,57 @@ package com.vayunmathur.madeveloper.domain -/** A repository hosted on the maproj git host. */-data class GitRepo(val name: String, val cloneUrl: String, val github: String?, val refs: List<GitRef> = emptyList())+/** A repository hosted on the maproj git host, from `GET /api/repos`. */+data class GitRepo(+ val name: String,+ val defaultBranch: String = "",+ val headSha: String = "",+ val headSubject: String = "",+ val headTime: String = "",+) {+ /** Short form of [headSha] for display. */+ val shortHeadSha: String get() = headSha.take(8)++ /** Clone URL on the git host. */+ val cloneUrl: String get() = "https://git.maproj.org/$name.git" -/** One advertised git reference (branch or tag) from `info/refs`. */-data class GitRef(val name: String, val sha: String) {+ /** Human web page for this repository on the git host. */+ val webUrl: String get() = "https://git.maproj.org/$name"+}++/** One branch of a repository, from `GET /api/repos/<repo>`. */+data class GitBranch(val name: String, val sha: String, val time: String = "") { /** Short form of [sha] for display. */ val shortSha: String get() = sha.take(8) } +/** One commit, from the repo detail or `GET /api/repos/<repo>/commits`. */+data class GitCommit(+ val sha: String,+ val shortSha: String = sha.take(8),+ val author: String = "",+ val time: String = "",+ val subject: String = "",+ val body: String = "",+)++/** Full repository detail from `GET /api/repos/<repo>`. */+data class RepoDetail(+ val name: String,+ val defaultBranch: String = "",+ val branches: List<GitBranch> = emptyList(),+ val recentCommits: List<GitCommit> = emptyList(),+)++/** One file read from `GET /api/repos/<repo>/file`. */+data class GitFile(+ val path: String,+ val size: Long = 0,+ val isBinary: Boolean = false,+ val content: String? = null,+ val truncated: Boolean = false,+ val sha: String = "",+)+ /** One issue as served by `/issues.json`. */ data class GitIssue( val repo: String, val number: Int, val title: String, val author: String,@@ -30,7 +73,7 @@ data class TestsStatus( val history: List<TestRun>, val coveragePct: Double?, ) -/** One entry in a repository tree listing. */+/** One entry in a repository tree listing from `GET /api/repos/<repo>/tree`. */ data class TreeEntry(val name: String, val path: String, val isDir: Boolean, val size: Long?) /** One installable build in the read-only F-Droid catalog. */
madeveloper/src/main/java/com/vayunmathur/madeveloper/domain/GitParsers.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/domain/GitParsers.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/domain/GitParsers.ktindex 821afed535..9ae8843091 100644--- a/madeveloper/src/main/java/com/vayunmathur/madeveloper/domain/GitParsers.kt+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/domain/GitParsers.kt@@ -3,6 +3,7 @@ package com.vayunmathur.madeveloper.domain import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.booleanOrNull import kotlinx.serialization.json.contentOrNull import kotlinx.serialization.json.doubleOrNull import kotlinx.serialization.json.intOrNull@@ -12,43 +13,101 @@ import kotlinx.serialization.json.jsonPrimitive import kotlinx.serialization.json.longOrNull /**- * Pure parsers for the machine-readable forms the git host and F-Droid repo- * actually expose. The git host has no repository-browsing pages: repositories- * are the fixed clone set, refs come from the smart-HTTP advertisement, and- * issues, pull requests and CI all serve JSON next to their HTML pages.+ * Pure parsers for the git host's first-party JSON API (`/api/repos…`),+ * its dashboard JSON (`/tests.json`, `/issues.json`, `/prs.json`) and the+ * F-Droid repo index. Times may arrive as ISO-8601 strings or epoch+ * seconds; both are normalised to a display string by [t]. */ object GitParsers { private val json = Json { ignoreUnknownKeys = true; isLenient = true } - /** Repositories known to the host, from its landing-page clone URLs. */- val knownRepos: List<GitRepo> = listOf(- GitRepo("Modern-Apps", "https://git.maproj.org/Modern-Apps.git", "vayun-mathur/Modern-Apps"),- GitRepo("MAOS", "https://git.maproj.org/MAOS.git", "vayun-mathur/MAOS"),- GitRepo(- "location_share_server",- "https://git.maproj.org/location_share_server.git", "vayun-mathur/location_share_server",- ),- )-- /** Parses the pkt-line ref advertisement of `GET /<repo>/info/refs?service=git-upload-pack`. */- fun parseRefs(body: ByteArray): List<GitRef> {- val text = body.toString(Charsets.UTF_8)- val refs = mutableListOf<GitRef>()- for (line in text.split('\n')) {- val clean = line.trim()- if (clean.length < 45) continue- val payload = clean.drop(4)- val parts = payload.split(' ', '\t', '\u0000')- if (parts.size < 2) continue- val sha = parts[0].trim()- val ref = parts[1].trim().removeSuffix("^{}")- if (sha.length in 40..64 && ref.startsWith("refs/")) {- refs += GitRef(ref.removePrefix("refs/heads/").removePrefix("refs/tags/"), sha)- }+ /** Parses `GET /api/repos` into the hosted repository list. */+ fun parseRepos(text: String): List<GitRepo> {+ val root = json.parseToJsonElement(text) as? JsonArray ?: return emptyList()+ return root.mapNotNull { element ->+ val obj = element as? JsonObject ?: return@mapNotNull null+ val name = obj.s("name")+ if (name.isBlank()) null else GitRepo(+ name = name,+ defaultBranch = obj.s("defaultBranch"),+ headSha = obj.s("headSha"),+ headSubject = obj.s("headSubject"),+ headTime = obj.t("headTime"),+ ) }- return refs.distinctBy { it.name } } + /** Parses `GET /api/repos/<repo>` into branches plus recent commits. */+ fun parseRepoDetail(text: String): RepoDetail {+ val root = json.parseToJsonElement(text).jsonObject+ return RepoDetail(+ name = root.s("name"),+ defaultBranch = root.s("defaultBranch"),+ branches = (root["branches"] as? JsonArray).orEmpty().mapNotNull { element ->+ val obj = element as? JsonObject ?: return@mapNotNull null+ val name = obj.s("name")+ if (name.isBlank()) null else GitBranch(name, obj.s("sha"), obj.t("time"))+ },+ recentCommits = parseCommitArray(root["recentCommits"] as? JsonArray),+ )+ }++ /** Parses `GET /api/repos/<repo>/commits` into one page of commits. */+ fun parseCommits(text: String): List<GitCommit> {+ val root = json.parseToJsonElement(text) as? JsonArray ?: return emptyList()+ return parseCommitArray(root)+ }++ /** Parses one commit object; shared by detail and commits responses. */+ fun parseCommit(obj: JsonObject): GitCommit {+ val sha = obj.s("sha")+ return GitCommit(+ sha = sha,+ shortSha = obj.s("shortSha").ifBlank { sha.take(8) },+ author = obj.s("author"),+ time = obj.t("time"),+ subject = obj.s("subject"),+ body = obj.s("body"),+ )+ }++ /**+ * Parses `GET /api/repos/<repo>/tree` for [parentPath] (blank = root).+ * Entries carry only a name, so the full path is joined here; trees+ * sort before blobs, each group by name.+ */+ fun parseTree(text: String, parentPath: String): List<TreeEntry> {+ val root = json.parseToJsonElement(text) as? JsonArray ?: return emptyList()+ val parent = parentPath.trim('/')+ return root.mapNotNull { element ->+ val obj = element as? JsonObject ?: return@mapNotNull null+ val name = obj.s("name")+ if (name.isBlank()) null else TreeEntry(+ name = name,+ path = if (parent.isEmpty()) name else "$parent/$name",+ isDir = obj.s("type") == "tree",+ size = obj["size"]?.jsonPrimitive?.longOrNull,+ )+ }.sortedWith(compareByDescending<TreeEntry> { it.isDir }.thenBy { it.name.lowercase() })+ }++ /** Parses `GET /api/repos/<repo>/file`. */+ fun parseFile(text: String): GitFile {+ val root = json.parseToJsonElement(text).jsonObject+ return GitFile(+ path = root.s("path"),+ size = root["size"]?.jsonPrimitive?.longOrNull ?: 0,+ isBinary = root.b("isBinary"),+ content = root["content"]?.jsonPrimitive?.contentOrNull,+ truncated = root.b("truncated"),+ sha = root.s("sha"),+ )+ }++ private fun parseCommitArray(array: JsonArray?): List<GitCommit> =+ array.orEmpty().mapNotNull { (it as? JsonObject)?.let(::parseCommit) }++ /** Parses `/tests.json` into the latest state plus recent history. */ fun parseTests(text: String): TestsStatus { val root = json.parseToJsonElement(text).jsonObject@@ -169,4 +228,13 @@ object GitParsers { private fun JsonArray?.orEmpty(): List<kotlinx.serialization.json.JsonElement> = this ?: emptyList() private fun JsonObject.s(key: String): String = this[key]?.jsonPrimitive?.contentOrNull ?: "" private fun JsonObject.i(key: String): Int = this[key]?.jsonPrimitive?.intOrNull ?: 0+ private fun JsonObject.b(key: String): Boolean = this[key]?.jsonPrimitive?.booleanOrNull ?: false++ /** Time fields arrive as ISO strings or epoch seconds; normalise both. */+ private fun JsonObject.t(key: String): String {+ val prim = this[key]?.jsonPrimitive ?: return ""+ prim.contentOrNull?.takeIf { it.isNotBlank() && prim.isString }?.let { return it }+ val epoch = prim.longOrNull ?: return prim.contentOrNull ?: ""+ return epoch.toString()+ } }
madeveloper/src/main/java/com/vayunmathur/madeveloper/domain/RepoBrowser.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/domain/RepoBrowser.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/domain/RepoBrowser.ktnew file mode 100644index 0000000000..28db4b675a--- /dev/null+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/domain/RepoBrowser.kt@@ -0,0 +1,77 @@+package com.vayunmathur.madeveloper.domain++/**+ * Pure navigation state for browsing one repository via the git host JSON+ * API: the selected branch, the current tree path, the loaded commit page+ * and the selected commit. No Android imports, so every transition is+ * unit-testable.+ */+data class RepoBrowserState(+ val repoName: String = "",+ val branch: String = "",+ val branches: List<GitBranch> = emptyList(),+ val path: String = "",+ val commits: List<GitCommit> = emptyList(),+ val commitsExhausted: Boolean = false,+ val selectedCommitSha: String = "",+) {+ /** The commit currently shown on the commit detail screen, if loaded. */+ val selectedCommit: GitCommit? get() = commits.firstOrNull { it.sha == selectedCommitSha }++ /** Breadcrumb segments of [path] as (label, cumulative path) pairs. */+ val breadcrumbs: List<Pair<String, String>>+ get() {+ if (path.isBlank()) return emptyList()+ val parts = path.split('/').filter { it.isNotEmpty() }+ return parts.mapIndexed { index, part -> part to parts.take(index + 1).joinToString("/") }+ }++ /** Cursor for the next commits page (`after=`), or null when exhausted. */+ val nextCommitCursor: String? get() = if (commitsExhausted) null else commits.lastOrNull()?.sha+}++/** State transitions for [RepoBrowserState]. */+object RepoBrowser {+ /** Starts browsing [detail], on its default branch, at the tree root. */+ fun open(detail: RepoDetail): RepoBrowserState = RepoBrowserState(+ repoName = detail.name,+ branch = detail.defaultBranch.ifBlank { detail.branches.firstOrNull()?.name ?: "" },+ branches = detail.branches,+ commits = detail.recentCommits,+ commitsExhausted = false,+ )++ /** Switches branch: tree returns to the root and the commit list resets. */+ fun selectBranch(state: RepoBrowserState, branch: String): RepoBrowserState =+ if (branch == state.branch) state else state.copy(+ branch = branch, path = "", commits = emptyList(),+ commitsExhausted = false, selectedCommitSha = "",+ )++ /** Descends into a tree entry; blobs do not change the tree path. */+ fun openEntry(state: RepoBrowserState, entry: TreeEntry): RepoBrowserState =+ if (entry.isDir) state.copy(path = entry.path) else state++ /** Moves to [path] (a breadcrumb target); blank means the tree root. */+ fun navigateTo(state: RepoBrowserState, path: String): RepoBrowserState =+ state.copy(path = path.trim('/'))++ /** Moves one directory up; stays at the root when already there. */+ fun navigateUp(state: RepoBrowserState): RepoBrowserState =+ state.copy(path = state.path.substringBeforeLast('/', "").trim('/'))++ /** Replaces the commit list with a fresh first page. */+ fun commitsLoaded(state: RepoBrowserState, page: List<GitCommit>, pageSize: Int): RepoBrowserState =+ state.copy(commits = page, commitsExhausted = page.size < pageSize)++ /** Appends the next commits page, de-duplicated by sha. */+ fun commitsAppended(state: RepoBrowserState, page: List<GitCommit>, pageSize: Int): RepoBrowserState =+ state.copy(+ commits = (state.commits + page).distinctBy { it.sha },+ commitsExhausted = page.size < pageSize,+ )++ /** Selects the commit shown on the detail screen. */+ fun selectCommit(state: RepoBrowserState, sha: String): RepoBrowserState =+ state.copy(selectedCommitSha = sha)+}
madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/MaDevViewModel.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/MaDevViewModel.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/MaDevViewModel.ktindex 25e7dfd8c9..e4c03b39ee 100644--- a/madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/MaDevViewModel.kt+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/MaDevViewModel.kt@@ -16,12 +16,16 @@ import com.vayunmathur.madeveloper.data.WebSocketDevTransport import com.vayunmathur.madeveloper.domain.CatalogApp import com.vayunmathur.madeveloper.domain.DevMessage import com.vayunmathur.madeveloper.domain.DevProtocol+import com.vayunmathur.madeveloper.domain.GitFile import com.vayunmathur.madeveloper.domain.GitIssue import com.vayunmathur.madeveloper.domain.GitPr import com.vayunmathur.madeveloper.domain.GitRepo import com.vayunmathur.madeveloper.domain.InstallPhase import com.vayunmathur.madeveloper.domain.InstalledAppInfo import com.vayunmathur.madeveloper.domain.PendingInstall+import com.vayunmathur.madeveloper.domain.RepoBrowser+import com.vayunmathur.madeveloper.domain.RepoBrowserState+import com.vayunmathur.madeveloper.domain.RepoDetail import com.vayunmathur.madeveloper.domain.TestsStatus import com.vayunmathur.madeveloper.domain.TreeEntry import kotlinx.coroutines.Dispatchers@@ -40,6 +44,9 @@ data class MaDevUiState( val issues: List<GitIssue> = emptyList(), val prs: List<GitPr> = emptyList(), val catalog: List<CatalogApp> = emptyList(),+ val repoDetails: Map<String, RepoDetail> = emptyMap(),+ val browsers: Map<String, RepoBrowserState> = emptyMap(),+ val repoError: String? = null, val connected: Boolean = false, val pairingCode: String = "", val paired: Boolean = false,@@ -89,15 +96,81 @@ class MaDevViewModel(app: Application) : AndroidViewModel(app) { } } - /** Tree entries for [gitRepo] at [path]. */- suspend fun tree(gitRepo: GitRepo, path: String): List<TreeEntry> = repo.tree(gitRepo, path)+ /** Loads repo detail (branches + recent commits) and opens its browser. */+ fun loadRepo(name: String) {+ if (state.browsers.containsKey(name)) return+ viewModelScope.launch {+ try {+ val detail = repo.repo(name)+ state = state.copy(+ repoDetails = state.repoDetails + (name to detail),+ browsers = state.browsers + (name to RepoBrowser.open(detail)),+ repoError = null,+ )+ } catch (e: java.io.IOException) {+ state = state.copy(repoError = e.message ?: "Could not load $name")+ }+ }+ }++ /** The browser state for [name], if its detail has loaded. */+ fun browser(name: String): RepoBrowserState? = state.browsers[name]++ /** Switches [name] to [branch]; resets tree path and commits, then reloads. */+ fun selectBranch(name: String, branch: String) {+ val current = state.browsers[name] ?: return+ updateBrowser(RepoBrowser.selectBranch(current, branch))+ loadCommits(name, loadMore = false)+ }++ /** Navigates the tree browser for [name] to [path]. */+ fun navigateTree(name: String, path: String) {+ val current = state.browsers[name] ?: return+ updateBrowser(RepoBrowser.navigateTo(current, path))+ } - /** File contents for [path] in the repo named [repoName]. */- suspend fun file(repoName: String, path: String): String {- val gitRepo = state.repos.firstOrNull { it.name == repoName } ?: return ""- return repo.file(gitRepo, path)+ /** Loads the first commits page, or appends the next when [loadMore]. */+ fun loadCommits(name: String, loadMore: Boolean) {+ val browser = state.browsers[name] ?: return+ if (loadMore && browser.commitsExhausted) return+ viewModelScope.launch {+ try {+ val page = repo.commits(+ name, browser.branch, GitHostRepository.COMMITS_PAGE_SIZE,+ if (loadMore) browser.nextCommitCursor else null,+ )+ val current = state.browsers[name] ?: return@launch+ updateBrowser(+ if (loadMore) {+ RepoBrowser.commitsAppended(current, page, GitHostRepository.COMMITS_PAGE_SIZE)+ } else {+ RepoBrowser.commitsLoaded(current, page, GitHostRepository.COMMITS_PAGE_SIZE)+ },+ )+ } catch (e: java.io.IOException) {+ state = state.copy(repoError = e.message ?: "Could not load commits")+ }+ } } + /** Selects the commit shown on the commit detail screen. */+ fun selectCommit(name: String, sha: String) {+ val current = state.browsers[name] ?: return+ updateBrowser(RepoBrowser.selectCommit(current, sha))+ }++ private fun updateBrowser(browser: RepoBrowserState) {+ state = state.copy(browsers = state.browsers + (browser.repoName to browser))+ }++ /** Tree entries for [repoName] on [branch] at [path]. */+ suspend fun tree(repoName: String, branch: String, path: String): List<TreeEntry> =+ repo.tree(repoName, branch, path)++ /** File at [path] in [repoName] on [branch]. */+ suspend fun file(repoName: String, branch: String, path: String): GitFile =+ repo.file(repoName, branch, path)+ /** Finds a repo by display name. */ fun repoByName(name: String): GitRepo? = state.repos.firstOrNull { it.name == name }
madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/CommitScreen.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/CommitScreen.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/CommitScreen.ktnew file mode 100644index 0000000000..4ddc011e46--- /dev/null+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/CommitScreen.kt@@ -0,0 +1,57 @@+package com.vayunmathur.madeveloper.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.verticalScroll+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.ExternalIntents+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.madeveloper.platform.MaDevViewModel++/**+ * One commit's metadata. The JSON API has no diff endpoint, so this shows+ * subject, body, author and time, and links out to the git host instead of+ * inventing a diff view.+ */+@Composable+fun CommitScreen(repoName: String, sha: String, viewModel: MaDevViewModel, onBack: () -> Unit) {+ val context = LocalContext.current+ LaunchedEffect(repoName) { viewModel.loadRepo(repoName) }+ val commit = viewModel.browser(repoName)?.let { browser ->+ browser.commits.firstOrNull { it.sha == sha } ?: browser.selectedCommit+ }+ AppScaffold(+ title = commit?.shortSha?.ifBlank { sha.take(8) } ?: sha.take(8),+ onNavigateBack = onBack, scrollBehavior = appBarScrollBehavior(),+ ) { padding ->+ Column(+ Modifier.padding(padding).padding(16.dp).verticalScroll(rememberScrollState()),+ verticalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ if (commit == null) {+ Text("Commit not in the loaded pages. Open the commits list and load more, or view it on the git host.")+ } else {+ Text(commit.subject.ifBlank { commit.shortSha }, style = MaterialTheme.typography.titleMedium)+ Text("Author: " + commit.author)+ Text("Time: " + commit.time)+ Text("SHA: " + commit.sha)+ if (commit.body.isNotBlank()) Text(commit.body)+ }+ Button(+ onClick = { ExternalIntents.openUrl(context, "https://git.maproj.org/$repoName") },+ modifier = Modifier.fillMaxWidth(),+ ) { Text("View on git host") }+ }+ }+}
madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/CommitsScreen.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/CommitsScreen.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/CommitsScreen.ktnew file mode 100644index 0000000000..119c4e1c35--- /dev/null+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/CommitsScreen.kt@@ -0,0 +1,68 @@+package com.vayunmathur.madeveloper.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.madeveloper.platform.MaDevViewModel++/** Paged commit list for one repository branch. */+@Composable+fun CommitsScreen(+ repoName: String,+ branch: String,+ viewModel: MaDevViewModel,+ onOpenCommit: (String) -> Unit,+ onBack: () -> Unit,+) {+ val browser = viewModel.browser(repoName)+ LaunchedEffect(repoName, branch, browser?.branch) {+ viewModel.loadRepo(repoName)+ if (browser != null && browser.commits.isEmpty()) viewModel.loadCommits(repoName, loadMore = false)+ }+ AppScaffold(title = "Commits · $branch", onNavigateBack = onBack, scrollBehavior = appBarScrollBehavior()) { padding ->+ LazyColumn(Modifier.padding(padding).padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {+ viewModel.state.repoError?.let { error ->+ item { Text(error, color = MaterialTheme.colorScheme.error) }+ }+ if (browser == null) {+ item { Text("Loading commits…") }+ } else {+ items(browser.commits) { commit ->+ Column {+ ListItem(+ headlineContent = { Text(commit.subject.ifBlank { commit.shortSha }) },+ supportingContent = {+ Text(commit.shortSha + " · " + commit.author + " · " + commit.time)+ },+ )+ Button(onClick = { onOpenCommit(commit.sha) }, modifier = Modifier.fillMaxWidth()) {+ Text("View commit")+ }+ }+ }+ if (browser.commits.isEmpty()) item { Text("No commits loaded yet.") }+ if (!browser.commitsExhausted) {+ item {+ Button(+ onClick = { viewModel.loadCommits(repoName, loadMore = true) },+ modifier = Modifier.fillMaxWidth(),+ ) { Text("Load more") }+ }+ }+ }+ }+ }+}
madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/FileScreen.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/FileScreen.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/FileScreen.ktindex 49a0ee7322..1a32e6762d 100644--- a/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/FileScreen.kt+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/FileScreen.kt@@ -1,5 +1,6 @@ package com.vayunmathur.madeveloper.ui +import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState@@ -13,18 +14,42 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.madeveloper.domain.GitFile import com.vayunmathur.madeveloper.platform.MaDevViewModel -/** One source file with line numbers. */+/** One source file with line numbers; binary and truncated files say so. */ @Composable-fun FileScreen(repoName: String, path: String, viewModel: MaDevViewModel, onBack: () -> Unit) {- var text by remember { mutableStateOf("") }- LaunchedEffect(repoName, path) { text = viewModel.file(repoName, path) }+fun FileScreen(repoName: String, path: String, branch: String, viewModel: MaDevViewModel, onBack: () -> Unit) {+ var file by remember { mutableStateOf<GitFile?>(null) }+ var error by remember { mutableStateOf<String?>(null) }+ LaunchedEffect(repoName, path, branch) {+ error = null+ file = runCatching { viewModel.file(repoName, branch, path) }+ .getOrElse { error = it.message; null }+ } AppScaffold(title = path.substringAfterLast('/'), onNavigateBack = onBack, scrollBehavior = appBarScrollBehavior()) { padding ->- Column(Modifier.padding(padding).padding(16.dp).verticalScroll(rememberScrollState())) {- Text(text.lines().mapIndexed { index, line -> (index + 1).toString().padStart(4) + " " + line }.joinToString("\n"))+ Column(+ Modifier.padding(padding).padding(16.dp).verticalScroll(rememberScrollState()),+ verticalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ error?.let { Text(it, color = MaterialTheme.colorScheme.error) }+ val loaded = file+ when {+ loaded == null && error == null -> Text("Loading file…")+ loaded == null -> Unit+ loaded.isBinary -> Text("Binary file · ${loaded.size} B · ${loaded.sha.take(8)}")+ else -> {+ if (loaded.truncated) Text("File truncated by the server · ${loaded.size} B")+ Text(+ (loaded.content ?: "").lines()+ .mapIndexed { index, line -> (index + 1).toString().padStart(4) + " " + line }+ .joinToString("\n"),+ )+ }+ } } } }
madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/HomeScreen.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/HomeScreen.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/HomeScreen.ktindex a7f8f12195..f286f477f7 100644--- a/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/HomeScreen.kt+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/HomeScreen.kt@@ -53,7 +53,12 @@ fun HomeScreen(state: MaDevUiState, onRefresh: () -> Unit, onOpenRepo: (String) items(state.repos) { repo -> ListItem( headlineContent = { Text(repo.name) },- supportingContent = { Text(repo.refs.firstOrNull()?.let { it.name + " " + it.shortSha } ?: repo.cloneUrl) },+ supportingContent = {+ Text(+ listOf(repo.defaultBranch, repo.shortHeadSha, repo.headSubject)+ .filter { it.isNotBlank() }.joinToString(" · ").ifBlank { repo.cloneUrl },+ )+ }, leadingContent = { IconCode() }, modifier = Modifier.fillMaxWidth(), )
madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/RepoScreen.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/RepoScreen.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/RepoScreen.ktindex f80760f5f8..e864ce4ab4 100644--- a/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/RepoScreen.kt+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/RepoScreen.kt@@ -2,6 +2,7 @@ package com.vayunmathur.madeveloper.ui import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn@@ -13,37 +14,126 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import com.vayunmathur.library.ui.AppScaffold import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.ExternalIntents import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.SelectDropdown import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.TextField import com.vayunmathur.library.ui.appBarScrollBehavior import com.vayunmathur.madeveloper.domain.TreeEntry import com.vayunmathur.madeveloper.platform.MaDevViewModel -/** One repository: refs, issues, pull requests and its file tree. */+/** One repository: branch switching, recent commits and its file tree. */ @Composable-fun RepoScreen(repoName: String, viewModel: MaDevViewModel, onOpenFile: (String) -> Unit, onBack: () -> Unit) {+fun RepoScreen(+ repoName: String,+ viewModel: MaDevViewModel,+ onOpenFile: (String, String) -> Unit,+ onOpenCommits: (String) -> Unit,+ onOpenCommit: (String, String) -> Unit,+ onBack: () -> Unit,+) {+ val state = viewModel.state+ val browser = viewModel.browser(repoName) val repo = viewModel.repoByName(repoName)- var path by remember { mutableStateOf("") }+ val context = LocalContext.current var entries by remember { mutableStateOf<List<TreeEntry>>(emptyList()) } var filter by remember { mutableStateOf("") }- LaunchedEffect(repoName, path) { if (repo != null) entries = viewModel.tree(repo, path) }+ var treeError by remember { mutableStateOf<String?>(null) }+ LaunchedEffect(repoName) { viewModel.loadRepo(repoName) }+ LaunchedEffect(repoName, browser?.branch, browser?.path) {+ val branch = browser?.branch ?: return@LaunchedEffect+ treeError = null+ entries = runCatching { viewModel.tree(repoName, branch, browser.path) }+ .getOrElse { treeError = it.message; emptyList() }+ } AppScaffold(title = repoName, onNavigateBack = onBack, scrollBehavior = appBarScrollBehavior()) { padding -> LazyColumn(Modifier.padding(padding).padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {- item { Text("Clone: " + (repo?.cloneUrl ?: "")) }- items(repo?.refs.orEmpty().take(12)) { ref -> ListItem(headlineContent = { Text(ref.name) }, supportingContent = { Text(ref.shortSha) }) }- item { TextField(value = filter, onValueChange = { filter = it }, label = { Text("Filter files") }, modifier = Modifier.fillMaxWidth()) }- if (path.isNotEmpty()) item { Button(onClick = { path = path.substringBeforeLast('/', "") }) { Text("Up") } }- items(entries.filter { it.name.contains(filter, ignoreCase = true) }) { entry ->- ListItem(headlineContent = { Text(entry.name) }, supportingContent = { Text(if (entry.isDir) "Folder" else "File") })- Button(onClick = { if (entry.isDir) path = entry.path else onOpenFile(entry.path) }, modifier = Modifier.fillMaxWidth()) {- Text(if (entry.isDir) "Open folder" else "Read file")+ item { Text("Clone: " + (repo?.cloneUrl ?: "https://git.maproj.org/$repoName.git")) }+ state.repoError?.let { error -> item { Text(error, color = MaterialTheme.colorScheme.error) } }+ if (browser == null) {+ item { Text("Loading repository…") }+ } else {+ item {+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ Text("Branch:", style = MaterialTheme.typography.titleMedium)+ SelectDropdown(+ label = browser.branch.ifBlank { "—" },+ options = browser.branches.map { it.name },+ selected = browser.branch,+ itemLabel = { it },+ onSelect = { viewModel.selectBranch(repoName, it) },+ )+ }+ }+ item { Text("Recent commits", style = MaterialTheme.typography.titleMedium) }+ items(browser.commits.take(5)) { commit ->+ Column {+ ListItem(+ headlineContent = { Text(commit.subject.ifBlank { commit.shortSha }) },+ supportingContent = { Text(commit.shortSha + " · " + commit.author + " · " + commit.time) },+ )+ Button(+ onClick = { onOpenCommit(browser.branch, commit.sha) },+ modifier = Modifier.fillMaxWidth(),+ ) { Text("View commit") }+ }+ }+ item {+ Button(onClick = { onOpenCommits(browser.branch) }, modifier = Modifier.fillMaxWidth()) {+ Text("All commits")+ }+ }+ item { Text("Files", style = MaterialTheme.typography.titleMedium) }+ item {+ TextField(+ value = filter, onValueChange = { filter = it },+ label = { Text("Filter files") }, modifier = Modifier.fillMaxWidth(),+ )+ }+ if (browser.path.isNotEmpty()) {+ item {+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ Button(onClick = { viewModel.navigateTree(repoName, "") }) { Text("Root") }+ for ((label, target) in browser.breadcrumbs) {+ Button(onClick = { viewModel.navigateTree(repoName, target) }) { Text(label) }+ }+ Button(onClick = {+ viewModel.navigateTree(repoName, browser.path.substringBeforeLast('/', ""))+ }) { Text("Up") }+ }+ }+ }+ treeError?.let { error -> item { Text(error, color = MaterialTheme.colorScheme.error) } }+ items(entries.filter { it.name.contains(filter, ignoreCase = true) }) { entry ->+ Column {+ ListItem(+ headlineContent = { Text(entry.name) },+ supportingContent = {+ Text(if (entry.isDir) "Folder" else (entry.size?.let { "$it B" } ?: "File"))+ },+ )+ Button(+ onClick = {+ if (entry.isDir) viewModel.navigateTree(repoName, entry.path)+ else onOpenFile(browser.branch, entry.path)+ },+ modifier = Modifier.fillMaxWidth(),+ ) { Text(if (entry.isDir) "Open folder" else "Read file") }+ }+ }+ item {+ Button(+ onClick = { ExternalIntents.openUrl(context, "https://git.maproj.org/$repoName") },+ modifier = Modifier.fillMaxWidth(),+ ) { Text("View on git host") } } }- item { Text("Issues and pull requests are on the Home data set; source files come from the host mirror.") } } } }
madeveloper/src/screenshotTest/kotlin/com/vayunmathur/madeveloper/ui/MetadataPreviews.kt
diff --git a/madeveloper/src/screenshotTest/kotlin/com/vayunmathur/madeveloper/ui/MetadataPreviews.kt b/madeveloper/src/screenshotTest/kotlin/com/vayunmathur/madeveloper/ui/MetadataPreviews.ktindex baff488c43..44448a4058 100644--- a/madeveloper/src/screenshotTest/kotlin/com/vayunmathur/madeveloper/ui/MetadataPreviews.kt+++ b/madeveloper/src/screenshotTest/kotlin/com/vayunmathur/madeveloper/ui/MetadataPreviews.kt@@ -18,7 +18,7 @@ class MetadataPreviews { fun PreviewHome() { DynamicTheme(darkTheme = true) { HomeScreen(- state = MaDevUiState(repos = listOf(GitRepo("Modern-Apps", "https://git.maproj.org/Modern-Apps.git", "vayun-mathur/Modern-Apps")), pairingCode = "ABC234"),+ state = MaDevUiState(repos = listOf(GitRepo("Modern-Apps", "main", "abc12345", "Demo commit", "2026-11-16T00:00:00Z")), pairingCode = "ABC234"), onRefresh = {}, onOpenRepo = {}, onOpenTests = {}, onOpenCatalog = {}, onOpenPush = {}, ) }
madeveloper/src/test/java/com/vayunmathur/madeveloper/GitParsersTest.kt
diff --git a/madeveloper/src/test/java/com/vayunmathur/madeveloper/GitParsersTest.kt b/madeveloper/src/test/java/com/vayunmathur/madeveloper/GitParsersTest.ktindex bb88ef78c4..fe395bf19a 100644--- a/madeveloper/src/test/java/com/vayunmathur/madeveloper/GitParsersTest.kt+++ b/madeveloper/src/test/java/com/vayunmathur/madeveloper/GitParsersTest.kt@@ -20,10 +20,61 @@ class GitParsersTest { assertEquals(listOf("bug"), issues[0].labels) } - @Test fun refsParseAdvertisement() {- val body = "0000" + "003d" + "a".repeat(40) + " refs/heads/main\u0000multi_ack\n" + "003d" + "b".repeat(40) + " refs/tags/v1\n"- val refs = GitParsers.parseRefs(body.toByteArray())- assertTrue(refs.any { it.name == "main" })+ @Test fun reposJsonParsesList() {+ val repos = GitParsers.parseRepos(+ """[{"name":"Modern-Apps","defaultBranch":"main","headSha":"aabbccdd11223344","headSubject":"madeveloper: x (#madev)","headTime":"2026-11-16T10:00:00Z"},{"name":"","defaultBranch":"main"}]""",+ )+ assertEquals(1, repos.size)+ assertEquals("main", repos[0].defaultBranch)+ assertEquals("aabbccdd", repos[0].shortHeadSha)+ assertEquals("https://git.maproj.org/Modern-Apps.git", repos[0].cloneUrl)+ }++ @Test fun repoDetailParsesBranchesAndRecentCommits() {+ val detail = GitParsers.parseRepoDetail(+ """{"name":"MAOS","defaultBranch":"main","branches":[{"name":"main","sha":"11111111aaaa","time":"2026-11-15T00:00:00Z"},{"name":"dev","sha":"22222222bbbb","time":1760000000}],"recentCommits":[{"sha":"11111111aaaa0000","author":"vayun","time":"2026-11-15T01:00:00Z","subject":"init","body":"notes"}]}""",+ )+ assertEquals("MAOS", detail.name)+ assertEquals(2, detail.branches.size)+ assertEquals("1760000000", detail.branches[1].time)+ assertEquals(1, detail.recentCommits.size)+ assertEquals("11111111", detail.recentCommits[0].shortSha)+ assertEquals("notes", detail.recentCommits[0].body)+ }++ @Test fun commitsJsonParsesPageWithDefaults() {+ val commits = GitParsers.parseCommits(+ """[{"sha":"abcdef0123456789","shortSha":"abcdef01","author":"a","time":"2026-01-01T00:00:00Z","subject":"s"},{"sha":"1234567890abcdef","author":"b","time":"2026-01-02T00:00:00Z","subject":"t","body":"body"}]""",+ )+ assertEquals(2, commits.size)+ assertEquals("abcdef01", commits[0].shortSha)+ assertEquals("12345678", commits[1].shortSha)+ assertEquals("", commits[0].body)+ }++ @Test fun treeJsonJoinsPathsAndSortsDirsFirst() {+ val entries = GitParsers.parseTree(+ """[{"name":"README.md","type":"blob","size":42},{"name":"src","type":"tree"}]""",+ "docs",+ )+ assertEquals(listOf("src", "README.md"), entries.map { it.name })+ assertEquals("docs/src", entries[0].path)+ assertTrue(entries[0].isDir)+ assertEquals(42L, entries[1].size)+ }++ @Test fun fileJsonParsesTextBinaryAndTruncated() {+ val text = GitParsers.parseFile(+ """{"path":"a.kt","size":3,"isBinary":false,"content":"hi\n","sha":"abc123"}""",+ )+ assertEquals("hi\n", text.content)+ assertEquals(false, text.isBinary)+ val binary = GitParsers.parseFile(+ """{"path":"a.png","size":99,"isBinary":true,"truncated":true,"sha":"def456"}""",+ )+ assertTrue(binary.isBinary)+ assertTrue(binary.truncated)+ assertEquals(null, binary.content) } @Test fun fdroidIndexPicksNewestVersion() {
madeveloper/src/test/java/com/vayunmathur/madeveloper/RepoBrowserTest.kt
diff --git a/madeveloper/src/test/java/com/vayunmathur/madeveloper/RepoBrowserTest.kt b/madeveloper/src/test/java/com/vayunmathur/madeveloper/RepoBrowserTest.ktnew file mode 100644index 0000000000..3398d5f672--- /dev/null+++ b/madeveloper/src/test/java/com/vayunmathur/madeveloper/RepoBrowserTest.kt@@ -0,0 +1,72 @@+package com.vayunmathur.madeveloper++import com.vayunmathur.madeveloper.domain.GitBranch+import com.vayunmathur.madeveloper.domain.GitCommit+import com.vayunmathur.madeveloper.domain.RepoBrowser+import com.vayunmathur.madeveloper.domain.RepoDetail+import com.vayunmathur.madeveloper.domain.TreeEntry+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** Tests for the pure repo-browser navigation state holder. */+class RepoBrowserTest {+ private val detail = RepoDetail(+ name = "Modern-Apps", defaultBranch = "main",+ branches = listOf(GitBranch("main", "a".repeat(40)), GitBranch("dev", "b".repeat(40))),+ recentCommits = listOf(GitCommit("a".repeat(40), subject = "head")),+ )++ @Test fun openUsesDefaultBranchAndRecentCommits() {+ val state = RepoBrowser.open(detail)+ assertEquals("main", state.branch)+ assertEquals(1, state.commits.size)+ assertEquals("", state.path)+ }++ @Test fun selectBranchResetsPathCommitsAndSelection() {+ var state = RepoBrowser.open(detail)+ state = RepoBrowser.navigateTo(state, "src/main")+ state = RepoBrowser.selectCommit(state, "a".repeat(40))+ val switched = RepoBrowser.selectBranch(state, "dev")+ assertEquals("dev", switched.branch)+ assertEquals("", switched.path)+ assertTrue(switched.commits.isEmpty())+ assertNull(switched.selectedCommit)+ // Re-selecting the same branch is a no-op.+ assertEquals(switched, RepoBrowser.selectBranch(switched, "dev"))+ }++ @Test fun treeNavigationBreadcrumbsAndUp() {+ var state = RepoBrowser.open(detail)+ state = RepoBrowser.openEntry(state, TreeEntry("src", "src", isDir = true, size = null))+ state = RepoBrowser.openEntry(state, TreeEntry("main", "src/main", isDir = true, size = null))+ assertEquals("src/main", state.path)+ assertEquals(listOf("src" to "src", "main" to "src/main"), state.breadcrumbs)+ // Blobs do not move the tree path.+ assertEquals(state, RepoBrowser.openEntry(state, TreeEntry("A.kt", "src/main/A.kt", false, 1)))+ assertEquals("src", RepoBrowser.navigateUp(state).path)+ assertEquals("", RepoBrowser.navigateUp(RepoBrowser.navigateUp(state)).path)+ assertEquals("", RepoBrowser.navigateTo(state, "").path)+ }++ @Test fun commitPagingAppendsDedupesAndExhausts() {+ var state = RepoBrowser.open(detail.copy(recentCommits = emptyList()))+ val page1 = listOf(GitCommit("1".repeat(40)), GitCommit("2".repeat(40)))+ state = RepoBrowser.commitsLoaded(state, page1, pageSize = 2)+ assertEquals(false, state.commitsExhausted)+ assertEquals("2".repeat(40), state.nextCommitCursor)+ state = RepoBrowser.commitsAppended(state, listOf(GitCommit("2".repeat(40)), GitCommit("3".repeat(40))), pageSize = 2)+ assertEquals(3, state.commits.size)+ state = RepoBrowser.commitsAppended(state, listOf(GitCommit("4".repeat(40))), pageSize = 2)+ assertTrue(state.commitsExhausted)+ assertNull(state.nextCommitCursor)+ }++ @Test fun selectCommitResolvesSelectedCommit() {+ var state = RepoBrowser.open(detail)+ state = RepoBrowser.selectCommit(state, "a".repeat(40))+ assertEquals("head", state.selectedCommit?.subject)+ }+}
madeveloper/src/test/java/com/vayunmathur/madeveloper/StateHolderTest.kt
diff --git a/madeveloper/src/test/java/com/vayunmathur/madeveloper/StateHolderTest.kt b/madeveloper/src/test/java/com/vayunmathur/madeveloper/StateHolderTest.ktindex 55ce098007..4a21383383 100644--- a/madeveloper/src/test/java/com/vayunmathur/madeveloper/StateHolderTest.kt+++ b/madeveloper/src/test/java/com/vayunmathur/madeveloper/StateHolderTest.kt@@ -15,7 +15,9 @@ class StateHolderTest { } @Test fun repoShortSha() {- val repo = GitRepo("Modern-Apps", "https://git.maproj.org/Modern-Apps.git", null)+ val repo = GitRepo("Modern-Apps", "main", "abc12345deadbeef") assertEquals("Modern-Apps", repo.name)+ assertEquals("abc12345", repo.shortHeadSha)+ assertEquals("https://git.maproj.org/Modern-Apps.git", repo.cloneUrl) } }