Migrated the deprecated detekt rules to new rules.

* Refactored the code according to the new rules of detekt.
This commit is contained in:
MohitMaliFtechiz 2025-03-05 16:42:31 +05:30 committed by Kelson
parent f96ab4d44d
commit c5cc0cdd4c
13 changed files with 65 additions and 66 deletions

View File

@ -393,7 +393,7 @@ class LocalLibraryFragment : BaseFragment(), CopyMoveFileHandler.FileCopyMoveCal
if (sharedPreferenceUtil.prefIsTest) {
putExtra(
"android.provider.extra.INITIAL_URI",
Uri.parse("content://com.android.externalstorage.documents/document/primary:Download")
"content://com.android.externalstorage.documents/document/primary:Download".toUri()
)
}
}

View File

@ -18,7 +18,6 @@
package org.kiwix.kiwixmobile.nav.destination.reader
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Looper
@ -30,6 +29,8 @@ import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.core.net.toUri
import androidx.core.view.isVisible
import androidx.drawerlayout.widget.DrawerLayout
import com.google.android.material.bottomnavigation.BottomNavigationView
import kotlinx.coroutines.launch
@ -137,7 +138,7 @@ class KiwixReaderFragment : CoreReaderFragment() {
val filePath =
FileUtils.getLocalFilePathByUri(
requireActivity().applicationContext,
Uri.parse(zimFileUri)
zimFileUri.toUri()
)
if (filePath == null || !File(filePath).isFileExist()) {
// Close the previously opened book in the reader. Since this file is not found,
@ -160,7 +161,7 @@ class KiwixReaderFragment : CoreReaderFragment() {
override fun openHomeScreen() {
Handler(Looper.getMainLooper()).postDelayed({
if (webViewList.size == 0) {
if (webViewList.isEmpty()) {
hideTabSwitcher(false)
}
}, HIDE_TAB_SWITCHER_DELAY)
@ -187,7 +188,7 @@ class KiwixReaderFragment : CoreReaderFragment() {
setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED)
closeAllTabsButton?.setImageDrawableCompat(drawable.ic_close_black_24dp)
if (tabSwitcherRoot?.visibility == View.VISIBLE) {
if (tabSwitcherRoot?.isVisible == true) {
tabSwitcherRoot?.visibility = GONE
startAnimation(tabSwitcherRoot, anim.slide_up)
progressBar?.visibility = View.GONE

View File

@ -184,7 +184,7 @@ class AllProjectConfigurer {
configureExtension<DetektExtension> {
buildUponDefaultConfig = true
allRules = false
config = target.files("${target.rootDir}/config/detekt/detekt.yml")
config.setFrom(target.files("${target.rootDir}/config/detekt/detekt.yml"))
baseline = project.file("detekt_baseline.xml")
}
}

View File

@ -61,16 +61,16 @@ complexity:
active: false
threshold: 10
includeStaticDeclarations: false
ComplexMethod:
CyclomaticComplexMethod:
active: true
threshold: 15
ignoreSingleWhenExpression: false
ignoreSimpleWhenEntries: false
ignoreNestingFunctions: false
nestingFunctions: run,let,apply,with,also,use,forEach,isNotNull,ifNull
nestingFunctions: [ 'run', 'let', 'apply', 'with', 'also', 'use', 'forEach', 'isNotNull', 'ifNull' ]
LabeledExpression:
active: false
ignoredLabels: ""
ignoredLabels: [ "" ]
LargeClass:
active: true
threshold: 600
@ -151,7 +151,7 @@ exceptions:
active: true
ExceptionRaisedInUnexpectedLocation:
active: false
methodNames: 'toString,hashCode,equals,finalize'
methodNames: [ 'toString', 'hashCode', 'equals', 'finalize' ]
InstanceOfCheckForException:
active: false
excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt"
@ -166,7 +166,7 @@ exceptions:
ignoreLabeled: false
SwallowedException:
active: false
ignoredExceptionTypes: 'InterruptedException,NumberFormatException,ParseException,MalformedURLException'
ignoredExceptionTypes: [ 'InterruptedException', 'NumberFormatException', 'ParseException', 'MalformedURLException' ]
allowedExceptionNameRegex: "^(_|(ignore|expected).*)"
ThrowingExceptionFromFinally:
active: false
@ -174,7 +174,7 @@ exceptions:
active: false
ThrowingExceptionsWithoutMessageOrCause:
active: false
exceptions: 'IllegalArgumentException,IllegalStateException,IOException'
exceptions: [ 'IllegalArgumentException', 'IllegalStateException', 'IOException' ]
ThrowingNewInstanceOfSameException:
active: false
TooGenericExceptionCaught:
@ -210,7 +210,6 @@ naming:
parameterPattern: '[a-z][A-Za-z0-9]*'
privateParameterPattern: '[a-z][A-Za-z0-9]*'
excludeClassPattern: '$^'
ignoreOverridden: true
EnumNaming:
active: true
excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt"
@ -218,7 +217,7 @@ naming:
ForbiddenClassName:
active: false
excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt"
forbiddenName: ''
forbiddenName: [ '' ]
FunctionMaxLength:
active: false
excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt"
@ -232,14 +231,12 @@ naming:
excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt"
functionPattern: '^([a-zA-Z$][a-zA-Z$0-9]*)|(`.*`)$'
excludeClassPattern: '$^'
ignoreOverridden: true
ignoreAnnotated: ['Composable']
ignoreAnnotated: [ 'Composable' ]
FunctionParameterNaming:
active: true
excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt"
parameterPattern: '[a-z][A-Za-z0-9]*'
excludeClassPattern: '$^'
ignoreOverridden: true
InvalidPackageDeclaration:
active: false
rootPackage: ''
@ -278,7 +275,6 @@ naming:
variablePattern: '[a-z][A-Za-z0-9]*'
privateVariablePattern: '(_)?[a-z][A-Za-z0-9]*'
excludeClassPattern: '$^'
ignoreOverridden: true
performance:
active: true
@ -297,8 +293,6 @@ potential-bugs:
active: true
Deprecation:
active: true
DuplicateCaseInWhenExpression:
active: true
EqualsAlwaysReturnsTrueOrFalse:
active: true
EqualsWithHashCodeExist:
@ -318,14 +312,10 @@ potential-bugs:
LateinitUsage:
active: false
excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt"
ignoreAnnotated: []
ignoreAnnotated: [ ]
ignoreOnClassesPattern: ""
MapGetWithNotNullAssertionOperator:
active: false
MissingWhenCase:
active: true
RedundantElseInWhen:
active: true
UnconditionalJumpStatementInLoop:
active: false
UnreachableCode:
@ -345,7 +335,7 @@ style:
active: false
DataClassContainsFunctions:
active: false
conversionFunctionPrefix: 'to'
conversionFunctionPrefix: [ 'to' ]
DataClassShouldBeImmutable:
active: false
EqualsNullCall:
@ -361,18 +351,21 @@ style:
includeLineWrapping: false
ForbiddenComment:
active: true
values: 'TODO:,FIXME:,STOPSHIP:'
comments:
- value: 'TODO:'
reason: 'Forbidden TODO todo marker in comment, please do the changes.'
- value: 'FIXME:'
reason: 'Forbidden FIXME todo marker in comment, please fix the problem.'
- value: 'STOPSHIP:'
reason: 'Forbidden STOPSHIP todo marker in comment, please address the problem before shipping the code.'
allowedPatterns: ""
ForbiddenImport:
active: false
imports: ''
imports: [ '' ]
forbiddenPatterns: ""
ForbiddenMethodCall:
active: false
methods: ''
ForbiddenPublicDataClass:
active: false
ignorePackages: '*.internal,*.internal.*'
methods: [ '' ]
ForbiddenVoid:
active: false
ignoreOverridden: false
@ -380,17 +373,19 @@ style:
FunctionOnlyReturningConstant:
active: true
ignoreOverridableFunction: true
excludedFunctions: 'describeContents'
ignoreAnnotated: ["dagger.Provides"]
LibraryCodeMustSpecifyReturnType:
active: true
excludedFunctions: [ 'describeContents' ]
ignoreAnnotated: [ "dagger.Provides" ]
LoopWithTooManyJumpStatements:
active: true
maxJumpCount: 1
MagicNumber:
active: true
excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt"
ignoreNumbers: '-1,0,1,2'
ignoreNumbers:
- '-1'
- '0'
- '1'
- '2'
ignoreHashCodeFunction: true
ignorePropertyDeclaration: true
ignoreLocalVariableDeclaration: false
@ -400,7 +395,7 @@ style:
ignoreNamedArgument: true
ignoreEnums: false
ignoreRanges: false
MandatoryBracesIfStatements:
BracesOnIfStatements:
active: false
MaxLineLength:
active: true
@ -422,8 +417,6 @@ style:
active: true
OptionalUnit:
active: false
OptionalWhenBraces:
active: false
PreferToOverPairSyntax:
active: false
ProtectedMemberInFinalClass:
@ -435,7 +428,7 @@ style:
ReturnCount:
active: true
max: 2
excludedFunctions: "equals"
excludedFunctions: [ "equals" ]
excludeLabeled: false
excludeReturnFromLambda: true
excludeGuardClauses: false
@ -455,7 +448,7 @@ style:
acceptableLength: 5
UnnecessaryAbstractClass:
active: true
ignoreAnnotated: ["dagger.Module"]
ignoreAnnotated: [ "dagger.Module" ]
UnnecessaryAnnotationUseSiteTarget:
active: false
UnnecessaryApply:
@ -475,14 +468,14 @@ style:
UnusedPrivateMember:
active: false
allowedNames: "(_|ignored|expected|serialVersionUID)"
ignoreAnnotated: ['Preview']
ignoreAnnotated: [ 'Preview' ]
UseArrayLiteralsInAnnotations:
active: false
UseCheckOrError:
active: false
UseDataClass:
active: false
ignoreAnnotated: []
ignoreAnnotated: [ ]
allowVars: false
UseIfInsteadOfWhen:
active: false
@ -497,4 +490,4 @@ style:
WildcardImport:
active: true
excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt"
excludeImports: 'java.util.*,kotlinx.android.synthetic.*'
excludeImports: [ 'java.util.*', 'kotlinx.android.synthetic.*' ]

View File

@ -20,9 +20,10 @@ package org.kiwix.kiwixmobile.core.downloader.model
import android.net.Uri
import org.kiwix.kiwixmobile.core.utils.SharedPreferenceUtil
import org.kiwix.kiwixmobile.core.utils.StorageUtils
import androidx.core.net.toUri
data class DownloadRequest(val urlString: String) {
val uri: Uri get() = Uri.parse(urlString)
val uri: Uri get() = urlString.toUri()
fun getDestination(sharedPreferenceUtil: SharedPreferenceUtil): String =
"${sharedPreferenceUtil.prefStorage}/Kiwix/${StorageUtils.getFileNameFromUrl(urlString)}"

View File

@ -22,7 +22,7 @@ import android.view.View
import android.widget.TextView
fun TextView.setTextAndVisibility(nullableText: String?) =
if (nullableText != null && nullableText.isNotEmpty()) {
if (nullableText?.isNotEmpty() == true) {
text = nullableText
visibility = View.VISIBLE
} else {

View File

@ -20,8 +20,8 @@ package org.kiwix.kiwixmobile.core.help
import android.animation.ObjectAnimator
import android.text.method.LinkMovementMethod
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isGone
import androidx.recyclerview.widget.RecyclerView
import org.kiwix.kiwixmobile.core.base.adapter.BaseViewHolder
import org.kiwix.kiwixmobile.core.databinding.ItemHelpBinding
@ -50,7 +50,7 @@ internal class HelpAdapter(titleDescriptionMap: Map<String, String>) :
BaseViewHolder<HelpItem>(itemHelpBinding.root) {
@SuppressWarnings("MagicNumber")
fun toggleDescriptionVisibility() {
if (itemHelpBinding.itemHelpDescription.visibility == View.GONE) {
if (itemHelpBinding.itemHelpDescription.isGone) {
ObjectAnimator.ofFloat(itemHelpBinding.itemHelpToggleExpand, "rotation", 0f, 180f).start()
itemHelpBinding.itemHelpDescription.expand()
} else {

View File

@ -72,6 +72,7 @@ import androidx.constraintlayout.widget.Group
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.net.toUri
import androidx.core.view.GravityCompat
import androidx.core.view.MenuHost
import androidx.core.view.MenuProvider
@ -890,7 +891,7 @@ abstract class CoreReaderFragment :
ContextCompat.getDrawable(requireActivity(), R.drawable.ic_close_black_24dp)
)
tabSwitcherRoot?.let {
if (it.visibility == View.VISIBLE) {
if (it.isVisible) {
setTabSwitcherVisibility(View.GONE)
startAnimation(it, R.anim.slide_up)
progressBar?.visibility = View.VISIBLE
@ -1535,7 +1536,7 @@ abstract class CoreReaderFragment :
}
private fun safelyGetWebView(position: Int): KiwixWebView? =
if (webViewList.size == 0) newMainPageTab() else webViewList[safePosition(position)]
if (webViewList.isEmpty()) newMainPageTab() else webViewList[safePosition(position)]
private fun safePosition(position: Int): Int =
when {
@ -1545,7 +1546,7 @@ abstract class CoreReaderFragment :
}
override fun getCurrentWebView(): KiwixWebView? {
if (webViewList.size == 0) {
if (webViewList.isEmpty()) {
return newMainPageTab()
}
return if (currentWebViewIndex < webViewList.size && currentWebViewIndex > 0) {
@ -2006,7 +2007,7 @@ abstract class CoreReaderFragment :
@Suppress("MagicNumber")
protected open fun openHomeScreen() {
Handler(Looper.getMainLooper()).postDelayed({
if (webViewList.size == 0) {
if (webViewList.isEmpty()) {
createNewTab()
hideTabSwitcher()
}
@ -2126,7 +2127,7 @@ abstract class CoreReaderFragment :
)
val bottomAppBar = requireActivity()
.findViewById<BottomAppBar>(R.id.bottom_toolbar)
if (bottomAppBar.visibility == VISIBLE) {
if (bottomAppBar.isVisible) {
// if bottomAppBar is visible then add the height of the bottomAppBar.
bottomMargin +=
requireActivity().resources.getDimensionPixelSize(
@ -2301,7 +2302,7 @@ abstract class CoreReaderFragment :
}
private fun contentUrl(articleUrl: String?): String =
Uri.parse(ZimFileReader.CONTENT_PREFIX + articleUrl).toString()
"${ZimFileReader.CONTENT_PREFIX}$articleUrl".toUri().toString()
private fun redirectOrOriginal(contentUrl: String): String {
zimReaderContainer?.let {

View File

@ -18,18 +18,18 @@
package org.kiwix.kiwixmobile.core.main
import android.content.Intent
import android.net.Uri
import org.kiwix.kiwixmobile.core.utils.files.Log
import android.webkit.MimeTypeMap
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.core.net.toUri
import org.kiwix.kiwixmobile.core.CoreApp.Companion.instance
import org.kiwix.kiwixmobile.core.reader.ZimFileReader
import org.kiwix.kiwixmobile.core.reader.ZimReaderContainer
import org.kiwix.kiwixmobile.core.utils.TAG_KIWIX
import org.kiwix.kiwixmobile.core.utils.files.Log
open class CoreWebViewClient(
protected val callback: WebViewCallback,
@ -64,7 +64,7 @@ open class CoreWebViewClient(
}
// Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
val intent = Intent(Intent.ACTION_VIEW, url.toUri())
callback.openExternalUrl(intent)
return true
}
@ -144,7 +144,7 @@ open class CoreWebViewClient(
}
private val LEGACY_CONTENT_PREFIXES = arrayOf(
"zim://content/",
Uri.parse("content://" + instance.packageName + ".zim.base/").toString()
"content://${instance.packageName}.zim.base/".toUri().toString()
)
}
}

View File

@ -425,7 +425,7 @@ class ZimFileReader constructor(
* Uri.parse returns null without android dependencies loaded
*/
@JvmField
val UI_URI: Uri? = Uri.parse("content://org.kiwix.ui/")
val UI_URI: Uri? = "content://org.kiwix.ui/".toUri()
const val CONTENT_PREFIX = "https://kiwix.app/"

View File

@ -18,7 +18,7 @@
package org.kiwix.kiwixmobile.core.utils
import android.net.Uri
import androidx.core.net.toUri
import org.kiwix.kiwixmobile.core.reader.ZimFileReader
import org.kiwix.kiwixmobile.core.reader.ZimReaderContainer
@ -26,7 +26,7 @@ private fun ZimReaderContainer.redirectOrOriginal(contentUrl: String): String =
if (isRedirect(contentUrl)) getRedirect(contentUrl) else contentUrl
private fun contentUrl(articleUrl: String): String =
Uri.parse(ZimFileReader.CONTENT_PREFIX + articleUrl).toString()
"${ZimFileReader.CONTENT_PREFIX}$articleUrl".toUri().toString()
fun ZimReaderContainer.urlSuffixToParsableUrl(suffixUrl: String): String =
redirectOrOriginal(contentUrl(suffixUrl))

View File

@ -20,8 +20,8 @@ package org.kiwix.kiwixmobile.core.utils.dialog
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Intent
import android.net.Uri
import androidx.annotation.IdRes
import androidx.core.net.toUri
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launch
import org.kiwix.kiwixmobile.core.BuildConfig
@ -105,9 +105,9 @@ class RateDialogHandler @Inject constructor(
private fun goToRateApp(activity: Activity) {
val kiwixLocalMarketUri =
Uri.parse("market://details?id=${activity.packageName}")
"market://details?id=${activity.packageName}".toUri()
val kiwixBrowserMarketUri =
Uri.parse("http://play.google.com/store/apps/details?id=${activity.packageName}")
"http://play.google.com/store/apps/details?id=${activity.packageName}".toUri()
val goToMarket = Intent(Intent.ACTION_VIEW, kiwixLocalMarketUri)
goToMarket.addFlags(
Intent.FLAG_ACTIVITY_NO_HISTORY or

View File

@ -32,6 +32,7 @@ import android.provider.DocumentsContract
import android.provider.MediaStore
import android.webkit.URLUtil
import androidx.annotation.RequiresApi
import androidx.core.net.toUri
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
@ -47,6 +48,8 @@ import org.kiwix.kiwixmobile.core.extensions.isFileExist
import org.kiwix.kiwixmobile.core.reader.ZimReaderContainer
import org.kiwix.kiwixmobile.core.utils.SharedPreferenceUtil
import org.kiwix.kiwixmobile.core.utils.TAG_KIWIX
import org.kiwix.kiwixmobile.core.utils.files.FileUtils.getSDCardOrUSBMainPathForAndroid10AndAbove
import org.kiwix.kiwixmobile.core.utils.files.FileUtils.getSdCardOrUSBMainPathForAndroid9AndBelow
import java.io.BufferedReader
import java.io.File
import java.io.FileInputStream
@ -417,7 +420,7 @@ object FileUtils {
for (prefix in contentUriPrefixes) {
contentQuery(
context,
ContentUris.withAppendedId(Uri.parse(prefix), documentId),
ContentUris.withAppendedId(prefix.toUri(), documentId),
documentsContractWrapper
)?.let {
return@queryForActualPath it