Skip to content

Commit

Permalink
feat: kgit migration
Browse files Browse the repository at this point in the history
  • Loading branch information
ViscousPot committed Aug 31, 2024
1 parent 92d2107 commit 07ba599
Show file tree
Hide file tree
Showing 7 changed files with 53 additions and 44 deletions.
8 changes: 4 additions & 4 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,11 @@ android {
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
kotlinOptions {
jvmTarget = "1.8"
jvmTarget = JavaVersion.VERSION_17.toString()
}
buildFeatures {
compose = true
Expand All @@ -52,7 +52,7 @@ android {
dependencies {
implementation(libs.security.crypto)
implementation(libs.squareup.okhttp3)
implementation(libs.eclipse.jgit)
implementation(libs.kgit)
implementation(libs.androidx.core.ktx)
implementation(libs.androidx.lifecycle.runtime.ktx)
implementation(libs.androidx.activity.compose)
Expand Down
6 changes: 4 additions & 2 deletions app/src/main/java/com/viscouspot/gitsync/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,7 @@ class MainActivity : AppCompatActivity() {
refreshAuthButton()

CloneRepoFragment(settingsManager, gitManager) {
gitDirPath.setText(settingsManager.getGitDirPath())
refreshGitRepo()
}.show(supportFragmentManager, "Select a repository")
}
Expand Down Expand Up @@ -282,7 +283,7 @@ class MainActivity : AppCompatActivity() {

}

gitDirPath.setOnFocusChangeListener { v, hasFocus ->
gitDirPath.setOnFocusChangeListener { _, hasFocus ->
if (!hasFocus) {
settingsManager.setGitDirPath(gitDirPath.text.toString())
refreshGitRepo()
Expand Down Expand Up @@ -452,8 +453,8 @@ class MainActivity : AppCompatActivity() {
private fun refreshGitRepo() {
var repoName = ""

val gitConfigFile = File("${gitDirPath.text}/.git/config")
val gitPathEmpty = gitDirPath.text.toString().trim() == ""
val gitConfigFile = File("${gitDirPath.text}/.git/config")
if (!gitPathEmpty && gitConfigFile.exists()) {
val fileContents = gitConfigFile.readText()

Expand All @@ -473,6 +474,7 @@ class MainActivity : AppCompatActivity() {
cloneRepoButton.visibility = View.VISIBLE
cloneRepoButton.setOnClickListener {
CloneRepoFragment(settingsManager, gitManager) {
gitDirPath.setText(settingsManager.getGitDirPath())
refreshGitRepo()
}.show(supportFragmentManager, getString(R.string.clone_repo))
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ class CloneRepoFragment(

gitManager.getRepos(settingsManager.getGitAuthCredentials().second) {
repoList.addAll(it)
requireActivity()?.runOnUiThread {
requireActivity().runOnUiThread {
adapter.notifyDataSetChanged()
}
}
Expand Down Expand Up @@ -125,7 +125,7 @@ class CloneRepoFragment(
callback = ::localDirCallback
dirSelectionLauncher.launch(null)
}
.setNegativeButton(android.R.string.no, null)
.setNegativeButton(android.R.string.cancel, null)
.show()
}

Expand Down
66 changes: 35 additions & 31 deletions app/src/main/java/com/viscouspot/gitsync/util/GitManager.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import android.net.Uri
import android.os.Looper
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.github.syari.kgit.KGit
import com.viscouspot.gitsync.Secrets
import com.viscouspot.gitsync.ui.adapter.Commit
import com.viscouspot.gitsync.util.Logger.log
Expand All @@ -19,13 +20,10 @@ import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import org.eclipse.jgit.api.Git
import org.eclipse.jgit.diff.DiffFormatter
import org.eclipse.jgit.internal.storage.file.FileRepository
import org.eclipse.jgit.lib.Repository
import org.eclipse.jgit.revwalk.RevSort
import org.eclipse.jgit.revwalk.RevWalk
import org.eclipse.jgit.revwalk.filter.RevFilter
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider
import org.eclipse.jgit.util.io.DisabledOutputStream
import org.json.JSONArray
Expand Down Expand Up @@ -70,7 +68,7 @@ class GitManager(private val context: Context, private val activity: AppCompatAc

override fun onResponse(call: Call, response: Response) {
log("GithubAuthCredentials", "Auth Token Obtained")
val authToken = JSONObject(response.body?.string()).getString("access_token")
val authToken = JSONObject(response.body?.string() ?: "").getString("access_token")

getGithubProfile(authToken, {
setCallback.invoke(it, authToken)
Expand Down Expand Up @@ -139,11 +137,11 @@ class GitManager(private val context: Context, private val activity: AppCompatAc
CoroutineScope(Dispatchers.IO).launch {
try {
log("CloneRepo", "Cloning Repo")
Git.cloneRepository()
.setURI(repoUrl)
.setDirectory(File(storageDir))
.setCredentialsProvider(UsernamePasswordCredentialsProvider(username, token))
.call()
KGit.cloneRepository {
setURI(repoUrl)
setDirectory(File(storageDir))
setCredentialsProvider(UsernamePasswordCredentialsProvider(username, token))
}

log("CloneRepo", "Repository cloned successfully")
withContext(Dispatchers.Main) {
Expand All @@ -168,19 +166,21 @@ class GitManager(private val context: Context, private val activity: AppCompatAc
var returnResult: Boolean? = false
log("PullFromRepo", "Getting local directory")
val repo = FileRepository("$storageDir/.git")
val git = Git(repo)
val git = KGit(repo)
val cp = UsernamePasswordCredentialsProvider(username, token)

log("PullFromRepo", "Fetching changes")
val fetchResult = git.fetch().setCredentialsProvider(cp).call()
val fetchResult = git.fetch {
setCredentialsProvider(cp)
}

if (!fetchResult.trackingRefUpdates.isEmpty()) {
log("PullFromRepo", "Pulling changes")
onSync.invoke()
val result = git.pull()
.setCredentialsProvider(cp)
.setRemote("origin")
.call()
val result = git.pull {
setCredentialsProvider(cp)
remote = "origin"
}
if (result.isSuccessful()) {
returnResult = true
} else {
Expand All @@ -204,31 +204,36 @@ class GitManager(private val context: Context, private val activity: AppCompatAc
log("PushToRepo", "Getting local directory")

val repo = FileRepository("$storageDir/.git")
val git = Git(repo)
val git = KGit(repo)

logStatus(git)
val status = git.status().call()
val status = git.status()
if (status.uncommittedChanges.isNotEmpty() || status.untracked.isNotEmpty()) {
onSync.invoke()
log("PushToRepo", "Adding Files to Stage")
git.add().addFilepattern(".").call();
git.add().addFilepattern(".").setUpdate(true).call();
git.add {
addFilepattern(".")
}
git.add {
addFilepattern(".")
isUpdate = true
}

log("PushToRepo", "Getting current time")
val currentDateTime = LocalDateTime.now()
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")

log("PushToRepo", "Committing changes")
git.commit()
.setCommitter(username, "")
.setMessage("Last Sync: ${currentDateTime.format(formatter)} (Mobile)")
.call()
git.commit {
setCommitter(username, "")
message = "Last Sync: ${currentDateTime.format(formatter)} (Mobile)"
}

log("PushToRepo", "Pushing changes")
git.push()
.setCredentialsProvider(UsernamePasswordCredentialsProvider(username, token))
.setRemote(repoUrl)
.call()
git.push {
setCredentialsProvider(UsernamePasswordCredentialsProvider(username, token))
remote = repoUrl
}

if (Looper.myLooper() == null) {
Looper.prepare()
Expand All @@ -248,8 +253,8 @@ class GitManager(private val context: Context, private val activity: AppCompatAc
return null
}

private fun logStatus(git: Git) {
val status = git.status().call()
private fun logStatus(git: KGit) {
val status = git.status()
log("GitStatus.HasUncommittedChanges", status.hasUncommittedChanges().toString())
log("GitStatus.Missing", status.missing.toString())
log("GitStatus.Modified", status.modified.toString())
Expand All @@ -272,7 +277,6 @@ class GitManager(private val context: Context, private val activity: AppCompatAc
val head = repo.resolve("refs/heads/master")
revWalk.markStart(revWalk.parseCommit(head))
revWalk.sort(RevSort.COMMIT_TIME_DESC)
revWalk.setRevFilter(RevFilter.NO_MERGES)

val commits = mutableListOf<Commit>()
var count = 0
Expand Down Expand Up @@ -319,7 +323,7 @@ class GitManager(private val context: Context, private val activity: AppCompatAc
return listOf()
}

private fun closeRepo(repo: Repository) {
private fun closeRepo(repo: FileRepository) {
repo.close()
val lockFile = File(repo.directory, "index.lock")
if (lockFile.exists()) lockFile.delete()
Expand Down
3 changes: 3 additions & 0 deletions app/src/main/java/com/viscouspot/gitsync/util/Logger.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,16 @@ package com.viscouspot.gitsync.util
import android.util.Log
import java.io.PrintWriter
import java.io.StringWriter
import kotlin.system.exitProcess

object Logger {
fun log(type: String, e: Exception) {
val sw = StringWriter()
val pw = PrintWriter(sw)
e.printStackTrace(pw)
log(type, "Error: $sw")

exitProcess(0)
}

fun log(type: String, message: String) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ class SettingsManager internal constructor(context: Context) {
}

fun getApplicationObserverEnabled(): Boolean {
return settingsSharedPref.getBoolean("applicationObserverEnabled", false)!!
return settingsSharedPref.getBoolean("applicationObserverEnabled", false)
}

fun setApplicationObserverEnabled(enabled: Boolean) {
Expand All @@ -83,7 +83,7 @@ class SettingsManager internal constructor(context: Context) {
}

fun getSyncOnAppOpened(): Boolean {
return settingsSharedPref.getBoolean("syncOnAppOpened", false)!!
return settingsSharedPref.getBoolean("syncOnAppOpened", false)
}

fun setSyncOnAppOpened(enabled: Boolean) {
Expand All @@ -94,7 +94,7 @@ class SettingsManager internal constructor(context: Context) {
}

fun getSyncOnAppClosed(): Boolean {
return settingsSharedPref.getBoolean("syncOnAppClosed", false)!!
return settingsSharedPref.getBoolean("syncOnAppClosed", false)
}

fun setSyncOnAppClosed(enabled: Boolean) {
Expand Down
4 changes: 2 additions & 2 deletions gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
agp = "8.3.0"
kotlin = "1.9.0"
coreKtx = "1.13.1"
jgit = "3.7.1.201504261725-r"
kgit = "1.0.6"
junit = "4.13.2"
junitVersion = "1.1.5"
espressoCore = "3.5.1"
Expand All @@ -16,7 +16,7 @@ securityCryptoKtx = "1.1.0-alpha06"
[libraries]
security-crypto = { group = "androidx.security", name = "security-crypto", version.ref = "securityCryptoKtx" }
squareup-okhttp3 = { group = "com.squareup.okhttp3", name = "okhttp", version.ref = "okhttp" }
eclipse-jgit = { group = "org.eclipse.jgit", name = "org.eclipse.jgit", version.ref = "jgit" }
kgit = { group = "com.github.sya-ri", name = "kgit", version.ref = "kgit" }
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
junit = { group = "junit", name = "junit", version.ref = "junit" }
androidx-junit = { group = "androidx.test.ext", name = "junit", version.ref = "junitVersion" }
Expand Down

0 comments on commit 07ba599

Please sign in to comment.