all: reformat with ktfmt 0.36

This commit is contained in:
Harsh Shandilya 2022-04-25 10:47:02 +05:30
parent 11720e9542
commit aaf6ceb8ec
No known key found for this signature in database
GPG key ID: 366D7BBAD1031E80
34 changed files with 637 additions and 614 deletions

View file

@ -42,7 +42,8 @@ object PasswordRepository {
private fun initializeRepository(repositoryDir: File) { private fun initializeRepository(repositoryDir: File) {
val builder = FileRepositoryBuilder() val builder = FileRepositoryBuilder()
repository = repository =
runCatching { builder.setGitDir(repositoryDir).build() }.getOrElse { e -> runCatching { builder.setGitDir(repositoryDir).build() }
.getOrElse { e ->
e.printStackTrace() e.printStackTrace()
null null
} }

View file

@ -117,7 +117,8 @@ class AutofillPublisherChangedActivity : AppCompatActivity() {
packageManager.getApplicationLabel(appInfo) packageManager.getApplicationLabel(appInfo)
) )
val currentHash = computeCertificatesHash(this@AutofillPublisherChangedActivity, appPackage) val currentHash =
computeCertificatesHash(this@AutofillPublisherChangedActivity, appPackage)
warningAppAdvancedInfo.text = warningAppAdvancedInfo.text =
getString( getString(
R.string.oreo_autofill_warning_publisher_advanced_info_template, R.string.oreo_autofill_warning_publisher_advanced_info_template,

View file

@ -411,7 +411,10 @@ class PasswordCreationActivity : BasePgpActivity(), OpenPgpServiceConnection.OnB
File(repoRoot, directory.text.toString()).findTillRoot(".gpg-id", repoRoot) File(repoRoot, directory.text.toString()).findTillRoot(".gpg-id", repoRoot)
?: File(repoRoot, ".gpg-id").apply { createNewFile() } ?: File(repoRoot, ".gpg-id").apply { createNewFile() }
val gpgIdentifiers = val gpgIdentifiers =
gpgIdentifierFile.readLines().filter { it.isNotBlank() }.map { line -> gpgIdentifierFile
.readLines()
.filter { it.isNotBlank() }
.map { line ->
GpgIdentifier.fromString(line) GpgIdentifier.fromString(line)
?: run { ?: run {
// The line being empty means this is most likely an empty `.gpg-id` // The line being empty means this is most likely an empty `.gpg-id`
@ -503,8 +506,10 @@ class PasswordCreationActivity : BasePgpActivity(), OpenPgpServiceConnection.OnB
// associate the new password name with the last name's timestamp in // associate the new password name with the last name's timestamp in
// history // history
val preference = getSharedPreferences("recent_password_history", Context.MODE_PRIVATE) val preference =
val oldFilePathHash = "$repoPath/${oldCategory?.trim('/')}/$oldFileName.gpg".base64() getSharedPreferences("recent_password_history", Context.MODE_PRIVATE)
val oldFilePathHash =
"$repoPath/${oldCategory?.trim('/')}/$oldFileName.gpg".base64()
val timestamp = preference.getString(oldFilePathHash) val timestamp = preference.getString(oldFilePathHash)
if (timestamp != null) { if (timestamp != null) {
preference.edit { preference.edit {
@ -522,7 +527,8 @@ class PasswordCreationActivity : BasePgpActivity(), OpenPgpServiceConnection.OnB
) )
if (shouldGeneratePassword) { if (shouldGeneratePassword) {
val directoryStructure = AutofillPreferences.directoryStructure(applicationContext) val directoryStructure =
AutofillPreferences.directoryStructure(applicationContext)
val entry = passwordEntryFactory.create(content.encodeToByteArray()) val entry = passwordEntryFactory.create(content.encodeToByteArray())
returnIntent.putExtra(RETURN_EXTRA_PASSWORD, entry.password) returnIntent.putExtra(RETURN_EXTRA_PASSWORD, entry.password)
val username = entry.username ?: directoryStructure.getUsernameFor(file) val username = entry.username ?: directoryStructure.getUsernameFor(file)
@ -552,7 +558,10 @@ class PasswordCreationActivity : BasePgpActivity(), OpenPgpServiceConnection.OnB
if (editing) R.string.git_commit_edit_text else R.string.git_commit_add_text if (editing) R.string.git_commit_edit_text else R.string.git_commit_add_text
lifecycleScope.launch { lifecycleScope.launch {
commitChange( commitChange(
resources.getString(commitMessageRes, getLongName(fullPath, repoPath, editName)) resources.getString(
commitMessageRes,
getLongName(fullPath, repoPath, editName)
)
) )
.onSuccess { .onSuccess {
setResult(RESULT_OK, returnIntent) setResult(RESULT_OK, returnIntent)

View file

@ -368,7 +368,8 @@ class PasswordCreationActivityV2 : BasePgpActivity() {
// Additionally, if we were editing and the incoming and outgoing // Additionally, if we were editing and the incoming and outgoing
// filenames differ, it means we renamed. Ensure that the target // filenames differ, it means we renamed. Ensure that the target
// doesn't already exist to prevent an accidental overwrite. // doesn't already exist to prevent an accidental overwrite.
if ((!editing || (editing && suggestedName != file.nameWithoutExtension)) && file.exists() if ((!editing || (editing && suggestedName != file.nameWithoutExtension)) &&
file.exists()
) { ) {
snackbar(message = getString(R.string.password_creation_duplicate_error)) snackbar(message = getString(R.string.password_creation_duplicate_error))
return@runCatching return@runCatching

View file

@ -48,8 +48,7 @@ class PasswordGeneratorDialogFragment : DialogFragment() {
val monoTypeface = Typeface.createFromAsset(callingActivity.assets, "fonts/sourcecodepro.ttf") val monoTypeface = Typeface.createFromAsset(callingActivity.assets, "fonts/sourcecodepro.ttf")
val prefs = val prefs =
requireActivity() requireActivity()
.applicationContext .applicationContext.getSharedPreferences("PasswordGenerator", Context.MODE_PRIVATE)
.getSharedPreferences("PasswordGenerator", Context.MODE_PRIVATE)
builder.setView(binding.root) builder.setView(binding.root)
@ -102,8 +101,8 @@ class PasswordGeneratorDialogFragment : DialogFragment() {
val passwordLength = getLength() val passwordLength = getLength()
setPrefs(requireContext(), passwordOptions, passwordLength) setPrefs(requireContext(), passwordOptions, passwordLength)
passwordField.text = passwordField.text =
runCatching { PasswordGenerator.generate(passwordOptions, passwordLength) }.getOrElse { runCatching { PasswordGenerator.generate(passwordOptions, passwordLength) }
exception -> .getOrElse { exception ->
val errorText = val errorText =
when (exception) { when (exception) {
is MaxIterationsExceededException -> is MaxIterationsExceededException ->

View file

@ -64,9 +64,8 @@ class SelectFolderFragment : Fragment(R.layout.password_recycler_view) {
override fun onFragmentInteraction(item: PasswordItem) { override fun onFragmentInteraction(item: PasswordItem) {
if (item.type == PasswordItem.TYPE_CATEGORY) { if (item.type == PasswordItem.TYPE_CATEGORY) {
model.navigateTo(item.file, listMode = ListMode.DirectoriesOnly) model.navigateTo(item.file, listMode = ListMode.DirectoriesOnly)
(requireActivity() as AppCompatActivity).supportActionBar?.setDisplayHomeAsUpEnabled( (requireActivity() as AppCompatActivity)
true .supportActionBar?.setDisplayHomeAsUpEnabled(true)
)
} }
} }
} }

View file

@ -88,9 +88,8 @@ class GitConfigActivity : BaseGitActivity() {
binding.gitAbortRebase.alpha = if (needsAbort) 1.0f else 0.5f binding.gitAbortRebase.alpha = if (needsAbort) 1.0f else 0.5f
} }
binding.gitLog.setOnClickListener { binding.gitLog.setOnClickListener {
runCatching { startActivity(Intent(this, GitLogActivity::class.java)) }.onFailure { ex -> runCatching { startActivity(Intent(this, GitLogActivity::class.java)) }
logcat(ERROR) { "Failed to start GitLogActivity\n${ex}" } .onFailure { ex -> logcat(ERROR) { "Failed to start GitLogActivity\n${ex}" } }
}
} }
binding.gitAbortRebase.setOnClickListener { binding.gitAbortRebase.setOnClickListener {
lifecycleScope.launch { lifecycleScope.launch {

View file

@ -292,9 +292,8 @@ class PasswordStore : BaseGitActivity() {
.setPositiveButton(resources.getString(R.string.dialog_ok), null) .setPositiveButton(resources.getString(R.string.dialog_ok), null)
when (id) { when (id) {
R.id.user_pref -> { R.id.user_pref -> {
runCatching { startActivity(Intent(this, SettingsActivity::class.java)) }.onFailure { e -> runCatching { startActivity(Intent(this, SettingsActivity::class.java)) }
e.printStackTrace() .onFailure { e -> e.printStackTrace() }
}
} }
R.id.git_push -> { R.id.git_push -> {
if (!PasswordRepository.isInitialized) { if (!PasswordRepository.isInitialized) {
@ -618,9 +617,7 @@ class PasswordStore : BaseGitActivity() {
fun matchPasswordWithApp(item: PasswordItem) { fun matchPasswordWithApp(item: PasswordItem) {
val path = val path =
item item.file.absolutePath
.file
.absolutePath
.replace(PasswordRepository.getRepositoryDirectory().toString() + "/", "") .replace(PasswordRepository.getRepositoryDirectory().toString() + "/", "")
.replace(".gpg", "") .replace(".gpg", "")
val data = Intent() val data = Intent()

View file

@ -42,9 +42,10 @@ class ProxySelectorActivity : AppCompatActivity() {
with(binding) { with(binding) {
proxyHost.setText(proxyPrefs.getString(PreferenceKeys.PROXY_HOST)) proxyHost.setText(proxyPrefs.getString(PreferenceKeys.PROXY_HOST))
proxyUser.setText(proxyPrefs.getString(PreferenceKeys.PROXY_USERNAME)) proxyUser.setText(proxyPrefs.getString(PreferenceKeys.PROXY_USERNAME))
proxyPrefs.getInt(PreferenceKeys.PROXY_PORT, -1).takeIf { it != -1 }?.let { proxyPrefs
proxyPort.setText("$it") .getInt(PreferenceKeys.PROXY_PORT, -1)
} .takeIf { it != -1 }
?.let { proxyPort.setText("$it") }
proxyPassword.setText(proxyPrefs.getString(PreferenceKeys.PROXY_PASSWORD)) proxyPassword.setText(proxyPrefs.getString(PreferenceKeys.PROXY_PASSWORD))
save.setOnClickListener { saveSettings() } save.setOnClickListener { saveSettings() }
proxyHost.doOnTextChanged { text, _, _, _ -> proxyHost.doOnTextChanged { text, _, _, _ ->
@ -70,18 +71,22 @@ class ProxySelectorActivity : AppCompatActivity() {
private fun saveSettings() { private fun saveSettings() {
proxyPrefs.edit { proxyPrefs.edit {
binding.proxyHost.text?.toString()?.takeIf { it.isNotEmpty() }.let { binding.proxyHost.text
gitSettings.proxyHost = it ?.toString()
} ?.takeIf { it.isNotEmpty() }
binding.proxyUser.text?.toString()?.takeIf { it.isNotEmpty() }.let { .let { gitSettings.proxyHost = it }
gitSettings.proxyUsername = it binding.proxyUser.text
} ?.toString()
binding.proxyPort.text?.toString()?.takeIf { it.isNotEmpty() }?.let { ?.takeIf { it.isNotEmpty() }
gitSettings.proxyPort = it.toInt() .let { gitSettings.proxyUsername = it }
} binding.proxyPort.text
binding.proxyPassword.text?.toString()?.takeIf { it.isNotEmpty() }.let { ?.toString()
gitSettings.proxyPassword = it ?.takeIf { it.isNotEmpty() }
} ?.let { gitSettings.proxyPort = it.toInt() }
binding.proxyPassword.text
?.toString()
?.takeIf { it.isNotEmpty() }
.let { gitSettings.proxyPassword = it }
} }
proxyUtils.setDefaultProxy() proxyUtils.setDefaultProxy()
Handler(Looper.getMainLooper()).postDelayed(500) { finish() } Handler(Looper.getMainLooper()).postDelayed(500) { finish() }

View file

@ -107,7 +107,9 @@ class AutofillMatcher {
val matchedFiles = val matchedFiles =
matchPreferences.getStringSet(matchesKey(formOrigin), emptySet())!!.map { File(it) } matchPreferences.getStringSet(matchesKey(formOrigin), emptySet())!!.map { File(it) }
return Ok( return Ok(
matchedFiles.filter { it.exists() }.also { validFiles -> matchedFiles
.filter { it.exists() }
.also { validFiles ->
matchPreferences.edit { matchPreferences.edit {
putStringSet(matchesKey(formOrigin), validFiles.map { it.absolutePath }.toSet()) putStringSet(matchesKey(formOrigin), validFiles.map { it.absolutePath }.toSet())
} }

View file

@ -34,7 +34,8 @@ fun File.contains(other: File): Boolean {
if (!isDirectory) return false if (!isDirectory) return false
if (!other.exists()) return false if (!other.exists()) return false
val relativePath = val relativePath =
runCatching { other.relativeTo(this) }.getOrElse { runCatching { other.relativeTo(this) }
.getOrElse {
return false return false
} }
// Direct containment is equivalent to the relative path being equal to the filename. // Direct containment is equivalent to the relative path being equal to the filename.

View file

@ -25,7 +25,8 @@ private fun commits(): Iterable<RevCommit> {
logcat(TAG, ERROR) { "Could not access git repository" } logcat(TAG, ERROR) { "Could not access git repository" }
return listOf() return listOf()
} }
return runCatching { Git(repo).log().call() }.getOrElse { e -> return runCatching { Git(repo).log().call() }
.getOrElse { e ->
logcat(TAG, ERROR) { e.asLog("Failed to obtain git commits") } logcat(TAG, ERROR) { e.asLog("Failed to obtain git commits") }
listOf() listOf()
} }

View file

@ -316,13 +316,18 @@ object SshKey {
private object KeystoreNativeKeyProvider : KeyProvider { private object KeystoreNativeKeyProvider : KeyProvider {
override fun getPublic(): PublicKey = override fun getPublic(): PublicKey =
runCatching { androidKeystore.sshPublicKey!! }.getOrElse { error -> runCatching { androidKeystore.sshPublicKey!! }
.getOrElse { error ->
logcat { error.asLog() } logcat { error.asLog() }
throw IOException("Failed to get public key '$KEYSTORE_ALIAS' from Android Keystore", error) throw IOException(
"Failed to get public key '$KEYSTORE_ALIAS' from Android Keystore",
error
)
} }
override fun getPrivate(): PrivateKey = override fun getPrivate(): PrivateKey =
runCatching { androidKeystore.sshPrivateKey!! }.getOrElse { error -> runCatching { androidKeystore.sshPrivateKey!! }
.getOrElse { error ->
logcat { error.asLog() } logcat { error.asLog() }
throw IOException( throw IOException(
"Failed to access private key '$KEYSTORE_ALIAS' from Android Keystore", "Failed to access private key '$KEYSTORE_ALIAS' from Android Keystore",
@ -336,7 +341,8 @@ object SshKey {
private object KeystoreWrappedEd25519KeyProvider : KeyProvider { private object KeystoreWrappedEd25519KeyProvider : KeyProvider {
override fun getPublic(): PublicKey = override fun getPublic(): PublicKey =
runCatching { parseSshPublicKey(sshPublicKey!!)!! }.getOrElse { error -> runCatching { parseSshPublicKey(sshPublicKey!!)!! }
.getOrElse { error ->
logcat { error.asLog() } logcat { error.asLog() }
throw IOException("Failed to get the public key for wrapped ed25519 key", error) throw IOException("Failed to get the public key for wrapped ed25519 key", error)
} }

View file

@ -93,9 +93,8 @@ private fun makeTofuHostKeyVerifier(hostKeyFile: File): HostKeyVerifier {
return object : HostKeyVerifier { return object : HostKeyVerifier {
override fun verify(hostname: String?, port: Int, key: PublicKey?): Boolean { override fun verify(hostname: String?, port: Int, key: PublicKey?): Boolean {
val digest = val digest =
runCatching { SecurityUtils.getMessageDigest("SHA-256") }.getOrElse { e -> runCatching { SecurityUtils.getMessageDigest("SHA-256") }
throw SSHRuntimeException(e) .getOrElse { e -> throw SSHRuntimeException(e) }
}
digest.update(PlainBuffer().putPublicKey(key).compactData) digest.update(PlainBuffer().putPublicKey(key).compactData)
val digestData = digest.digest() val digestData = digest.digest()
val hostKeyEntry = "SHA256:${Base64.encodeToString(digestData, Base64.NO_WRAP)}" val hostKeyEntry = "SHA256:${Base64.encodeToString(digestData, Base64.NO_WRAP)}"

View file

@ -140,7 +140,8 @@ constructor(
newBranch: String newBranch: String
): UpdateConnectionSettingsResult { ): UpdateConnectionSettingsResult {
val parsedUrl = val parsedUrl =
runCatching { URIish(newUrl) }.getOrElse { runCatching { URIish(newUrl) }
.getOrElse {
return UpdateConnectionSettingsResult.FailedToParseUrl return UpdateConnectionSettingsResult.FailedToParseUrl
} }
val newProtocol = val newProtocol =

View file

@ -229,9 +229,8 @@ class SearchableRepositoryViewModel(application: Application) : AndroidViewModel
.filter { it.first > 0 } .filter { it.first > 0 }
.toList() .toList()
.sortedWith( .sortedWith(
compareByDescending<Pair<Int, PasswordItem>> { it.first }.thenBy(itemComparator) { compareByDescending<Pair<Int, PasswordItem>> { it.first }
it.second .thenBy(itemComparator) { it.second }
}
) )
.map { it.second } .map { it.second }
} }

View file

@ -105,7 +105,10 @@ internal class SingleFieldMatcher(
} }
override fun match(fields: List<FormField>, alreadyMatched: List<FormField>): List<FormField>? { override fun match(fields: List<FormField>, alreadyMatched: List<FormField>): List<FormField>? {
return fields.minus(alreadyMatched).filter { take(it, alreadyMatched) }.let { contestants -> return fields
.minus(alreadyMatched)
.filter { take(it, alreadyMatched) }
.let { contestants ->
when (contestants.size) { when (contestants.size) {
1 -> return@let listOf(contestants.single()) 1 -> return@let listOf(contestants.single())
0 -> return@let null 0 -> return@let null

View file

@ -251,8 +251,7 @@ public fun getInstalledBrowsersWithAutofillSupportLevel(
.map { it to getBrowserAutofillSupportLevel(context, it.activityInfo.packageName) } .map { it to getBrowserAutofillSupportLevel(context, it.activityInfo.packageName) }
.filter { it.first.isDefault || it.second != BrowserAutofillSupportLevel.None } .filter { it.first.isDefault || it.second != BrowserAutofillSupportLevel.None }
.map { .map {
context context.packageManager
.packageManager
.getApplicationLabel(it.first.activityInfo.applicationInfo) .getApplicationLabel(it.first.activityInfo.applicationInfo)
.toString() to it.second .toString() to it.second
} }

View file

@ -182,9 +182,10 @@ internal class FormField(
// Basic type detection for HTML fields // Basic type detection for HTML fields
private val htmlTag = node.htmlInfo?.tag private val htmlTag = node.htmlInfo?.tag
private val htmlAttributes: Map<String, String> = private val htmlAttributes: Map<String, String> =
node.htmlInfo?.attributes?.filter { it.first != null && it.second != null }?.associate { node.htmlInfo
Pair(it.first.lowercase(Locale.US), it.second.lowercase(Locale.US)) ?.attributes
} ?.filter { it.first != null && it.second != null }
?.associate { Pair(it.first.lowercase(Locale.US), it.second.lowercase(Locale.US)) }
?: emptyMap() ?: emptyMap()
private val htmlAttributesDebug = htmlAttributes.entries.joinToString { "${it.key}=${it.value}" } private val htmlAttributesDebug = htmlAttributes.entries.joinToString { "${it.key}=${it.value}" }
private val htmlInputType = htmlAttributes["type"] private val htmlInputType = htmlAttributes["type"]

View file

@ -32,9 +32,9 @@ afterEvaluate {
} }
} }
// disable kapt tasks for unit tests // disable kapt tasks for unit tests
tasks.matching { it.name.startsWith("kapt") && it.name.endsWith("UnitTestKotlin") }.configureEach { tasks
enabled = false .matching { it.name.startsWith("kapt") && it.name.endsWith("UnitTestKotlin") }
} .configureEach { enabled = false }
fun Project.hasDaggerCompilerDependency(): Boolean { fun Project.hasDaggerCompilerDependency(): Boolean {
return configurations.any { return configurations.any {

View file

@ -79,17 +79,17 @@ constructor(
when (id) { when (id) {
is GpgIdentifier.KeyId -> { is GpgIdentifier.KeyId -> {
val keyIdMatch = val keyIdMatch =
keys.map { key -> key to tryGetId(key) }.firstOrNull { (_, keyId) -> keys
keyId?.id == id.id .map { key -> key to tryGetId(key) }
} .firstOrNull { (_, keyId) -> keyId?.id == id.id }
keyIdMatch?.first keyIdMatch?.first
} }
is GpgIdentifier.UserId -> { is GpgIdentifier.UserId -> {
val selector = SelectUserId.byEmail(id.email) val selector = SelectUserId.byEmail(id.email)
val userIdMatch = val userIdMatch =
keys.map { key -> key to tryParseKeyring(key) }.firstOrNull { (_, keyRing) -> keys
selector.firstMatch(keyRing) != null .map { key -> key to tryParseKeyring(key) }
} .firstOrNull { (_, keyRing) -> selector.firstMatch(keyRing) != null }
userIdMatch?.first userIdMatch?.first
} }
} }