refactor: replace branch preference value with repository-based helper

This commit is contained in:
Harsh Shandilya 2022-11-27 13:06:08 +05:30
parent 74711fcc78
commit 56a25dcd32
No known key found for this signature in database
7 changed files with 26 additions and 40 deletions

View file

@ -99,13 +99,14 @@ class GitConfigActivity : BaseGitActivity() {
launchGitOperation(GitOp.BREAK_OUT_OF_DETACHED) launchGitOperation(GitOp.BREAK_OUT_OF_DETACHED)
.fold( .fold(
success = { success = {
val branch = PasswordRepository.getCurrentBranch()
MaterialAlertDialogBuilder(this@GitConfigActivity).run { MaterialAlertDialogBuilder(this@GitConfigActivity).run {
setTitle(resources.getString(R.string.git_abort_and_push_title)) setTitle(resources.getString(R.string.git_abort_and_push_title))
setMessage( setMessage(
resources.getString( resources.getString(
R.string.git_break_out_of_detached_success, R.string.git_break_out_of_detached_success,
gitSettings.branch, branch,
"conflicting-${gitSettings.branch}-...", "conflicting-$branch-...",
) )
) )
setOnDismissListener { finish() } setOnDismissListener { finish() }

View file

@ -141,8 +141,7 @@ class GitServerConfigActivity : BaseGitActivity() {
val updateResult = val updateResult =
gitSettings.updateConnectionSettingsIfValid( gitSettings.updateConnectionSettingsIfValid(
newAuthMode = newAuthMode, newAuthMode = newAuthMode,
newUrl = binding.serverUrl.text.toString().trim(), newUrl = binding.serverUrl.text.toString().trim()
newBranch = binding.serverBranch.text.toString().trim()
) )
) { ) {
GitSettings.UpdateConnectionSettingsResult.FailedToParseUrl -> { GitSettings.UpdateConnectionSettingsResult.FailedToParseUrl -> {

View file

@ -6,6 +6,7 @@ package app.passwordstore.util.git.operation
import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatActivity
import app.passwordstore.R import app.passwordstore.R
import app.passwordstore.data.repo.PasswordRepository
import app.passwordstore.util.extensions.unsafeLazy import app.passwordstore.util.extensions.unsafeLazy
import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.dialog.MaterialAlertDialogBuilder
import org.eclipse.jgit.api.RebaseCommand import org.eclipse.jgit.api.RebaseCommand
@ -15,17 +16,18 @@ import org.eclipse.jgit.lib.RepositoryState
class BreakOutOfDetached(callingActivity: AppCompatActivity) : GitOperation(callingActivity) { class BreakOutOfDetached(callingActivity: AppCompatActivity) : GitOperation(callingActivity) {
private val merging = repository.repositoryState == RepositoryState.MERGING private val merging = repository.repositoryState == RepositoryState.MERGING
private val localBranch = PasswordRepository.getCurrentBranch()
private val resetCommands = private val resetCommands =
arrayOf( arrayOf(
// git checkout -b conflict-branch // git checkout -b conflict-branch
git git
.checkout() .checkout()
.setCreateBranch(true) .setCreateBranch(true)
.setName("conflicting-$remoteBranch-${System.currentTimeMillis()}"), .setName("conflicting-$localBranch-${System.currentTimeMillis()}"),
// push the changes // push the changes
git.push().setRemote("origin"), git.push().setRemote("origin"),
// switch back to ${gitBranch} // switch back to ${gitBranch}
git.checkout().setName(remoteBranch), git.checkout().setName(localBranch),
) )
override val commands by unsafeLazy { override val commands by unsafeLazy {

View file

@ -13,23 +13,20 @@ import app.passwordstore.data.repo.PasswordRepository
import app.passwordstore.ui.sshkeygen.SshKeyGenActivity import app.passwordstore.ui.sshkeygen.SshKeyGenActivity
import app.passwordstore.ui.sshkeygen.SshKeyImportActivity import app.passwordstore.ui.sshkeygen.SshKeyImportActivity
import app.passwordstore.util.auth.BiometricAuthenticator import app.passwordstore.util.auth.BiometricAuthenticator
import app.passwordstore.util.auth.BiometricAuthenticator.Result.* import app.passwordstore.util.auth.BiometricAuthenticator.Result.Cancelled
import app.passwordstore.util.auth.BiometricAuthenticator.Result.Failure
import app.passwordstore.util.auth.BiometricAuthenticator.Result.Success
import app.passwordstore.util.git.GitCommandExecutor import app.passwordstore.util.git.GitCommandExecutor
import app.passwordstore.util.git.sshj.SshAuthMethod import app.passwordstore.util.git.sshj.SshAuthMethod
import app.passwordstore.util.git.sshj.SshKey import app.passwordstore.util.git.sshj.SshKey
import app.passwordstore.util.git.sshj.SshjSessionFactory import app.passwordstore.util.git.sshj.SshjSessionFactory
import app.passwordstore.util.settings.AuthMode import app.passwordstore.util.settings.AuthMode
import app.passwordstore.util.settings.GitSettings
import com.github.michaelbull.result.Err import com.github.michaelbull.result.Err
import com.github.michaelbull.result.Ok import com.github.michaelbull.result.Ok
import com.github.michaelbull.result.Result import com.github.michaelbull.result.Result
import com.github.michaelbull.result.onFailure import com.github.michaelbull.result.onFailure
import com.github.michaelbull.result.runCatching import com.github.michaelbull.result.runCatching
import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.dialog.MaterialAlertDialogBuilder
import dagger.hilt.EntryPoint
import dagger.hilt.InstallIn
import dagger.hilt.android.EntryPointAccessors
import dagger.hilt.components.SingletonComponent
import kotlin.coroutines.resume import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine import kotlin.coroutines.suspendCoroutine
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
@ -64,15 +61,8 @@ abstract class GitOperation(protected val callingActivity: FragmentActivity) {
open val requiresAuth: Boolean = true open val requiresAuth: Boolean = true
private val hostKeyFile = callingActivity.filesDir.resolve(".host_key") private val hostKeyFile = callingActivity.filesDir.resolve(".host_key")
private var sshSessionFactory: SshjSessionFactory? = null private var sshSessionFactory: SshjSessionFactory? = null
private val hiltEntryPoint =
EntryPointAccessors.fromApplication(
callingActivity.applicationContext,
GitOperationEntryPoint::class.java
)
protected val repository = PasswordRepository.repository!! protected val repository = PasswordRepository.repository!!
protected val git = Git(repository) protected val git = Git(repository)
protected val remoteBranch = hiltEntryPoint.gitSettings().branch
private val authActivity private val authActivity
get() = callingActivity as AppCompatActivity get() = callingActivity as AppCompatActivity
@ -241,10 +231,4 @@ abstract class GitOperation(protected val callingActivity: FragmentActivity) {
/** Timeout in seconds before [TransportCommand] will abort a stalled IO operation. */ /** Timeout in seconds before [TransportCommand] will abort a stalled IO operation. */
private const val CONNECT_TIMEOUT = 10 private const val CONNECT_TIMEOUT = 10
} }
@EntryPoint
@InstallIn(SingletonComponent::class)
interface GitOperationEntryPoint {
fun gitSettings(): GitSettings
}
} }

View file

@ -89,11 +89,6 @@ constructor(
set(value) { set(value) {
settings.edit { putString(PreferenceKeys.GIT_CONFIG_AUTHOR_EMAIL, value) } settings.edit { putString(PreferenceKeys.GIT_CONFIG_AUTHOR_EMAIL, value) }
} }
var branch
get() = settings.getString(PreferenceKeys.GIT_BRANCH_NAME) ?: DEFAULT_BRANCH
private set(value) {
settings.edit { putString(PreferenceKeys.GIT_BRANCH_NAME, value) }
}
var useMultiplexing var useMultiplexing
get() = settings.getBoolean(PreferenceKeys.GIT_REMOTE_USE_MULTIPLEXING, true) get() = settings.getBoolean(PreferenceKeys.GIT_REMOTE_USE_MULTIPLEXING, true)
set(value) { set(value) {
@ -135,8 +130,7 @@ constructor(
fun updateConnectionSettingsIfValid( fun updateConnectionSettingsIfValid(
newAuthMode: AuthMode, newAuthMode: AuthMode,
newUrl: String, newUrl: String
newBranch: String
): UpdateConnectionSettingsResult { ): UpdateConnectionSettingsResult {
val parsedUrl = val parsedUrl =
runCatching { URIish(newUrl) } runCatching { URIish(newUrl) }
@ -167,7 +161,6 @@ constructor(
url = newUrl url = newUrl
authMode = newAuthMode authMode = newAuthMode
branch = newBranch
return UpdateConnectionSettingsResult.Valid return UpdateConnectionSettingsResult.Valid
} }
@ -178,8 +171,4 @@ constructor(
/** Returns true if a host key was previously saved */ /** Returns true if a host key was previously saved */
fun hasSavedHostKey(): Boolean = File(hostKeyPath).exists() fun hasSavedHostKey(): Boolean = File(hostKeyPath).exists()
companion object {
private const val DEFAULT_BRANCH = "master"
}
} }

View file

@ -27,6 +27,15 @@ fun runMigrations(filesDirPath: String, sharedPrefs: SharedPreferences, gitSetti
migrateToClipboardHistory(sharedPrefs) migrateToClipboardHistory(sharedPrefs)
migrateToDiceware(sharedPrefs) migrateToDiceware(sharedPrefs)
removeExternalStorageProperties(sharedPrefs) removeExternalStorageProperties(sharedPrefs)
removeCurrentBranchValue(sharedPrefs)
}
fun removeCurrentBranchValue(sharedPrefs: SharedPreferences) {
if (sharedPrefs.contains(PreferenceKeys.GIT_BRANCH_NAME)) {
return
}
logcat(TAG, INFO) { "Deleting now unused branch name preference" }
sharedPrefs.edit { remove(PreferenceKeys.GIT_BRANCH_NAME) }
} }
private fun migrateToGitUrlBasedConfig(sharedPrefs: SharedPreferences, gitSettings: GitSettings) { private fun migrateToGitUrlBasedConfig(sharedPrefs: SharedPreferences, gitSettings: GitSettings) {
@ -36,7 +45,6 @@ private fun migrateToGitUrlBasedConfig(sharedPrefs: SharedPreferences, gitSettin
val serverUser = sharedPrefs.getString(PreferenceKeys.GIT_REMOTE_USERNAME) ?: "" val serverUser = sharedPrefs.getString(PreferenceKeys.GIT_REMOTE_USERNAME) ?: ""
val serverPath = sharedPrefs.getString(PreferenceKeys.GIT_REMOTE_LOCATION) ?: "" val serverPath = sharedPrefs.getString(PreferenceKeys.GIT_REMOTE_LOCATION) ?: ""
val protocol = Protocol.fromString(sharedPrefs.getString(PreferenceKeys.GIT_REMOTE_PROTOCOL)) val protocol = Protocol.fromString(sharedPrefs.getString(PreferenceKeys.GIT_REMOTE_PROTOCOL))
// Whether we need the leading ssh:// depends on the use of a custom port. // Whether we need the leading ssh:// depends on the use of a custom port.
val hostnamePart = serverHostname.removePrefix("ssh://") val hostnamePart = serverHostname.removePrefix("ssh://")
val url = val url =
@ -83,8 +91,7 @@ private fun migrateToGitUrlBasedConfig(sharedPrefs: SharedPreferences, gitSettin
url == null || url == null ||
gitSettings.updateConnectionSettingsIfValid( gitSettings.updateConnectionSettingsIfValid(
newAuthMode = gitSettings.authMode, newAuthMode = gitSettings.authMode,
newUrl = url, newUrl = url
newBranch = gitSettings.branch
) != GitSettings.UpdateConnectionSettingsResult.Valid ) != GitSettings.UpdateConnectionSettingsResult.Valid
) { ) {
logcat(TAG, ERROR) { "Failed to migrate to URL-based Git config, generated URL is invalid" } logcat(TAG, ERROR) { "Failed to migrate to URL-based Git config, generated URL is invalid" }

View file

@ -25,8 +25,10 @@ object PreferenceKeys {
const val GIT_CONFIG = "git_config" const val GIT_CONFIG = "git_config"
const val GIT_CONFIG_AUTHOR_EMAIL = "git_config_user_email" const val GIT_CONFIG_AUTHOR_EMAIL = "git_config_user_email"
const val GIT_CONFIG_AUTHOR_NAME = "git_config_user_name" const val GIT_CONFIG_AUTHOR_NAME = "git_config_user_name"
@Deprecated(message = "We're removing support for external storage") @Deprecated(message = "We're removing support for external storage")
const val GIT_EXTERNAL = "git_external" const val GIT_EXTERNAL = "git_external"
@Deprecated(message = "We're removing support for external storage") @Deprecated(message = "We're removing support for external storage")
const val GIT_EXTERNAL_REPO = "git_external_repo" const val GIT_EXTERNAL_REPO = "git_external_repo"
const val GIT_EXTERNAL_MIGRATED = "git_external_migrated" const val GIT_EXTERNAL_MIGRATED = "git_external_migrated"
@ -46,6 +48,8 @@ object PreferenceKeys {
@Deprecated("Use GIT_REMOTE_URL instead") const val GIT_REMOTE_USERNAME = "git_remote_username" @Deprecated("Use GIT_REMOTE_URL instead") const val GIT_REMOTE_USERNAME = "git_remote_username"
const val GIT_SERVER_INFO = "git_server_info" const val GIT_SERVER_INFO = "git_server_info"
@Deprecated("Git branch is no longer stored in preferences")
const val GIT_BRANCH_NAME = "git_branch" const val GIT_BRANCH_NAME = "git_branch"
const val HTTPS_PASSWORD = "https_password" const val HTTPS_PASSWORD = "https_password"
const val LENGTH = "length" const val LENGTH = "length"