path
stringlengths
4
297
contentHash
stringlengths
1
10
content
stringlengths
0
13M
beer-advisor/src/main/kotlin/io/github/mpichler94/beeradvisor/BeerAdvisorApplication.kt
4254707028
package io.github.mpichler94.beeradvisor import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication @SpringBootApplication class BeerAdvisorApplication fun main(args: Array<String>) { runApplication<BeerAdvisorApplication>(*args) }
react-native-android-navbar/android/src/newarch/AndroidNavbarSpec.kt
1941212610
package com.androidnavbar import com.facebook.react.bridge.ReactApplicationContext abstract class AndroidNavbarSpec internal constructor(context: ReactApplicationContext) : NativeAndroidNavbarSpec(context) { }
react-native-android-navbar/android/src/oldarch/AndroidNavbarSpec.kt
3934880775
package com.androidnavbar import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.bridge.ReactContextBaseJavaModule import com.facebook.react.bridge.Promise abstract class AndroidNavbarSpec internal constructor(context: ReactApplicationContext) : ReactContextBaseJavaModule(context) { abstract fun changeNavigationBarColor(color: String, light: Boolean, animated: Boolean, promise: Promise) abstract fun hideNavigationBar(promise: Promise) abstract fun showNavigationBar(promise: Promise) }
react-native-android-navbar/android/src/main/java/com/androidnavbar/AndroidNavbarPackage.kt
1945612491
package com.androidnavbar import com.facebook.react.TurboReactPackage import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.bridge.NativeModule import com.facebook.react.module.model.ReactModuleInfoProvider import com.facebook.react.module.model.ReactModuleInfo import java.util.HashMap class AndroidNavbarPackage : TurboReactPackage() { override fun getModule(name: String, reactContext: ReactApplicationContext): NativeModule? { return if (name == AndroidNavbarModule.NAME) { AndroidNavbarModule(reactContext) } else { null } } override fun getReactModuleInfoProvider(): ReactModuleInfoProvider { return ReactModuleInfoProvider { val moduleInfos: MutableMap<String, ReactModuleInfo> = HashMap() val isTurboModule: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED moduleInfos[AndroidNavbarModule.NAME] = ReactModuleInfo( AndroidNavbarModule.NAME, AndroidNavbarModule.NAME, false, // canOverrideExistingModule false, // needsEagerInit true, // hasConstants false, // isCxxModule isTurboModule // isTurboModule ) moduleInfos } } }
react-native-android-navbar/android/src/main/java/com/androidnavbar/AndroidNavbarModule.kt
439360806
package com.androidnavbar import android.animation.ArgbEvaluator import android.animation.ValueAnimator import android.app.Activity import android.graphics.Color import android.os.Build import android.view.View import android.view.Window import android.view.WindowInsets import android.view.WindowInsetsController import android.view.WindowManager import com.facebook.react.bridge.Promise import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.bridge.ReactMethod import com.facebook.react.bridge.UiThreadUtil import com.facebook.react.module.annotations.ReactModule import com.facebook.react.turbomodule.core.interfaces.TurboModule class AndroidNavbarModule internal constructor(context: ReactApplicationContext) : AndroidNavbarSpec(context) { private val reactContext = context override fun getName(): String { return NAME } private fun setNavigationBarTheme(activity: Activity?, light: Boolean) { if (activity != null) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && Build.VERSION.SDK_INT < Build.VERSION_CODES.S) { val window = activity.window var flags = window.decorView.systemUiVisibility flags = if (light) { flags or View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR } else { flags and View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR.inv() } window.decorView.systemUiVisibility = flags } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { val flag = if (light) { WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS } else { 0 } val insetsController = activity.window.insetsController insetsController?.setSystemBarsAppearance(flag, WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS) } } } @ReactMethod override fun changeNavigationBarColor(color: String, light: Boolean, animated: Boolean, promise: Promise) { val currentActivity = reactContext.currentActivity if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { currentActivity?.let { UiThreadUtil.runOnUiThread { try { val window: Window = it.window // Clear flags for transparent and translucent, set them later if needed window.clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS) window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION) if (color == "transparent" || color == "translucent") { if (color == "transparent") { window.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS) } else { window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION) } } val colorTo: Int = if (color == "transparent") Color.TRANSPARENT else Color.parseColor(color) if (animated) { val colorFrom: Int = window.navigationBarColor val colorAnimation = ValueAnimator.ofObject(ArgbEvaluator(), colorFrom, colorTo) colorAnimation.duration = 200 // Duration of the animation colorAnimation.addUpdateListener { animator -> window.navigationBarColor = animator.animatedValue as Int } colorAnimation.start() } else { window.navigationBarColor = colorTo } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { // For Android 11 (API level 30) and above val windowInsetsController = window.insetsController if (light) { windowInsetsController?.setSystemBarsAppearance( WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS, WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS ) } else { windowInsetsController?.setSystemBarsAppearance( 0, WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS ) } } else { // For Android 8 (API level 26) to Android 10 (API level 29) var flags: Int = window.decorView.systemUiVisibility flags = if (light) { flags or View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR } else { flags and View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR.inv() } window.decorView.systemUiVisibility = flags } promise.resolve(true) } catch (e: Exception) { promise.reject("error", e) } } } ?: run { promise.reject("E_NO_ACTIVITY", Throwable("Tried to change the navigation bar while not attached to an Activity")) } } else { promise.reject("API_LEVEL", Throwable("Only Android Lollipop and above is supported")) } } @ReactMethod override fun hideNavigationBar(promise: Promise) { val currentActivity = reactContext.currentActivity if (currentActivity != null) { UiThreadUtil.runOnUiThread { try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { // Use WindowInsetsController for Android 11 (API level 30) and above currentActivity.window.insetsController?.hide(WindowInsets.Type.navigationBars()) } else { // Use systemUiVisibility for API levels below 30 val decorView: View = currentActivity.window.decorView decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) } promise.resolve(true) } catch (e: Exception) { promise.reject("error", e) } } } else { promise.reject("E_NO_ACTIVITY", Throwable("Tried to hide the navigation bar while not attached to an Activity")) } } @ReactMethod override fun showNavigationBar(promise: Promise) { val currentActivity = reactContext.currentActivity if (currentActivity != null) { UiThreadUtil.runOnUiThread { try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { // Use WindowInsetsController for Android 11 (API level 30) and above currentActivity.window.insetsController?.show(WindowInsets.Type.navigationBars()) } else { // Use systemUiVisibility for API levels below 30 val decorView: View = currentActivity.window.decorView decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE } promise.resolve(true) } catch (e: Exception) { promise.reject("error", e) } } } else { promise.reject("E_NO_ACTIVITY", Throwable("Tried to show the navigation bar while not attached to an Activity")) } } companion object { const val NAME = "AndroidNavbar" } }
grapkl/configer/src/main/kotlin/Configer.kt
2642287407
import org.gradle.api.Plugin import org.gradle.api.initialization.Settings import org.gradle.api.plugins.JavaApplication import org.gradle.kotlin.dsl.apply import org.gradle.kotlin.dsl.configure import org.pkl.config.java.ConfigEvaluator import org.pkl.config.kotlin.forKotlin import org.pkl.config.kotlin.to import org.pkl.core.ModuleSource import java.io.File class Configer : Plugin<Settings> { override fun apply(settings: Settings) { settings.gradle.beforeProject { val buildFile = File(project.rootDir, "build.gradle.pkl") val config = ConfigEvaluator.preconfigured().forKotlin().use { evaluator -> evaluator.evaluate(ModuleSource.file(buildFile)) } val product = config["product"].to<String>() if (product == "jvm/app") { apply(plugin = "java") apply(plugin = "application") extensions.configure<JavaApplication> { // yeah this shouldn't be hard coded mainClass.set("Main") } } /* tasks.create("createConfig") { val buildFile = File(project.rootDir, "build.gradle.pkl") val sourceModules = listOf(buildFile.toURI()) val baseOptions = CliBaseOptions(sourceModules) val options = CliKotlinCodeGeneratorOptions( base = baseOptions, outputDir = project.rootDir.toPath(), ) CliKotlinCodeGenerator(options).run() } */ } } }
CoupProject/app/src/androidTest/java/com/example/coupproject/ExampleInstrumentedTest.kt
4286613483
package com.example.coupproject import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.coupproject", appContext.packageName) } }
CoupProject/app/src/test/java/com/example/coupproject/ExampleUnitTest.kt
954523722
package com.example.coupproject import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
CoupProject/app/src/main/java/com/example/coupproject/viewmodel/MainViewModel.kt
515338443
package com.example.coupproject.viewmodel import android.util.Log import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.coupproject.domain.model.User import com.example.coupproject.domain.usecase.login.HasAccessTokenUseCase import com.example.coupproject.domain.usecase.main.CheckPermissionUseCase import com.example.coupproject.domain.usecase.main.GetFriendUseCase import com.example.coupproject.domain.usecase.main.GetMembershipUseCase import com.example.coupproject.domain.usecase.main.SetMembershipUseCase import com.google.android.gms.tasks.OnSuccessListener import com.google.firebase.database.DataSnapshot import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class MainViewModel @Inject constructor( private val getFriendUseCase: GetFriendUseCase, private val hasAccessTokenUseCase: HasAccessTokenUseCase, private val checkPermissionUseCase: CheckPermissionUseCase, private val getMembershipUseCase: GetMembershipUseCase, private val setMembershipUseCase: SetMembershipUseCase ) : ViewModel() { private val _hasMembership = MutableStateFlow(User()) val hasMembership: StateFlow<User> = _hasMembership fun getFriend(memberId: String, callback: OnSuccessListener<DataSnapshot>) { viewModelScope.launch(Dispatchers.Main) { getFriendUseCase(memberId, callback) .catch { exception -> Log.e(TAG, exception.message, exception) }.collect() } } fun saveFriend(user: User) { viewModelScope.launch { _hasMembership.emit(user) } } fun getMembership(callback: OnSuccessListener<DataSnapshot>) { viewModelScope.launch { getMembershipUseCase(callback).catch { exception -> Log.e(TAG, exception.message, exception) } } } companion object { const val TAG = "MainViewModel" } }
CoupProject/app/src/main/java/com/example/coupproject/viewmodel/LoginViewModel.kt
3584146071
package com.example.coupproject.viewmodel import android.util.Log import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.coupproject.domain.usecase.login.GetAccessTokenInfoUseCase import com.example.coupproject.domain.usecase.login.HasAccessTokenUseCase import com.example.coupproject.domain.usecase.login.StartKakaoLoginUseCase import com.example.coupproject.domain.usecase.main.GetFriendUseCase import com.example.coupproject.domain.usecase.main.GetMembershipUseCase import com.example.coupproject.view.login.LoginActivity import com.google.android.gms.tasks.OnSuccessListener import com.google.firebase.database.DataSnapshot import com.kakao.sdk.auth.model.OAuthToken import com.kakao.sdk.user.model.AccessTokenInfo import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class LoginViewModel @Inject constructor( private val startKakaoLoginUseCase: StartKakaoLoginUseCase, private val hasAccessTokenUseCase: HasAccessTokenUseCase, private val getAccessTokenInfoUseCase: GetAccessTokenInfoUseCase, private val getMembershipUseCase: GetMembershipUseCase, private val getFriendUseCase: GetFriendUseCase, ) : ViewModel() { private val _loginResult = MutableSharedFlow<Boolean>() val loginResult: SharedFlow<Boolean> = _loginResult fun startKakaoLogin(activity: LoginActivity, callback: (OAuthToken?, Throwable?) -> Unit) { viewModelScope.launch { startKakaoLoginUseCase.invoke(activity, callback) .catch { exception -> Log.e(TAG, exception.message, exception) } .collect { Log.i(TAG, "ViewModel Collect") } } } fun hasAccessToken() { viewModelScope.launch { hasAccessTokenUseCase().catch { exception -> Log.e( TAG, exception.message, exception ) }.collect { _loginResult.emit(it) } } } fun getAccessTokenInfo(callback: (AccessTokenInfo?, Throwable?) -> Unit) { viewModelScope.launch { getAccessTokenInfoUseCase(callback).catch { exception -> Log.e( TAG, exception.message, exception ) } } } fun getMembership(callback: OnSuccessListener<DataSnapshot>) { viewModelScope.launch { getMembershipUseCase(callback).catch { Log.e(TAG, "Failed getMembership()", it) } .collect { Log.i(TAG, "getMembership success") } } } companion object { const val TAG = "LoginViewModel" } }
CoupProject/app/src/main/java/com/example/coupproject/viewmodel/MemberViewModel.kt
3619314968
package com.example.coupproject.viewmodel import android.util.Log import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.coupproject.domain.usecase.main.SetMembershipUseCase import com.google.android.gms.tasks.OnSuccessListener import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class MemberViewModel @Inject constructor( private val setMembershipUseCase: SetMembershipUseCase ) : ViewModel() { fun setMembership(name: String, memberId: String, callback: OnSuccessListener<Void>) { viewModelScope.launch { setMembershipUseCase.invoke(name, memberId, callback) .catch { exception -> Log.e(TAG, exception.message, exception) }.collect { Log.i(TAG, "Success SetMemberShip") } } } companion object { const val TAG = "MemberViewModel" } }
CoupProject/app/src/main/java/com/example/coupproject/di/AppModule.kt
3132041494
package com.example.coupproject.di import android.content.Context import com.example.coupproject.data.repository.KakaoRepositoryImpl import com.example.coupproject.data.repository.FirebaseRepositoryImpl import com.example.coupproject.domain.repository.KakaoRepository import com.example.coupproject.domain.repository.MainRepository import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object AppModule { @Provides @Singleton fun provideLoginRepositoryImpl(@ApplicationContext context: Context): KakaoRepository { return KakaoRepositoryImpl(context) } @Provides @Singleton fun provideMainRepositoryImpl(@ApplicationContext context: Context): MainRepository { return FirebaseRepositoryImpl(context) } }
CoupProject/app/src/main/java/com/example/coupproject/CoupBroadcastReceiver.kt
2344761496
package com.example.coupproject import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.util.Log class CoupBroadcastReceiver : BroadcastReceiver() { override fun onReceive(p0: Context?, intent: Intent?) { Log.i("CoupBroadcastReceiver", "성공") intent?.action?.let { Log.i("CoupBroadcastReceiver", "$it 액션") } } }
CoupProject/app/src/main/java/com/example/coupproject/view/member/AddMemberActivity.kt
3384086120
package com.example.coupproject.view.member import android.content.Intent import android.os.Bundle import android.util.Log import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import com.example.coupproject.R import com.example.coupproject.databinding.ActivityAddMemberBinding import com.example.coupproject.view.login.LoginActivity import com.example.coupproject.view.main.MainActivity import com.example.coupproject.viewmodel.MemberViewModel import com.kakao.sdk.user.UserApiClient import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class AddMemberActivity : AppCompatActivity() { private lateinit var binding: ActivityAddMemberBinding private val viewModel: MemberViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityAddMemberBinding.bind( layoutInflater.inflate( R.layout.activity_add_member, null ) ) binding.btnOk.setOnClickListener { if (binding.edtName.text.isNotEmpty()) { me(binding.edtName.text.toString()) } } setContentView(binding.root) } fun me(name: String) { UserApiClient.instance.me { user, error -> user?.let { users -> viewModel.setMembership(name, users.id.toString()) { startActivity( Intent(this@AddMemberActivity, MainActivity::class.java).putExtra( "token", users.id.toString() ) ) } } error?.let { Log.e(LoginActivity.TAG, it.message, it) } } } companion object { const val TAG = "AddMemberActivity" } }
CoupProject/app/src/main/java/com/example/coupproject/view/dialog/ProgressDialog.kt
2686704539
package com.example.coupproject.view.dialog import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.DialogFragment import com.example.coupproject.databinding.ActivityMainBinding class ProgressDialog : DialogFragment() { private lateinit var binding: ActivityMainBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return super.onCreateView(inflater, container, savedInstanceState) } }
CoupProject/app/src/main/java/com/example/coupproject/view/dialog/DialogActivity.kt
1552723022
package com.example.coupproject.view.dialog import android.os.Build import android.os.Bundle import android.util.DisplayMetrics import android.util.Log import android.view.ViewGroup import android.view.WindowInsets import androidx.appcompat.app.AppCompatActivity import com.bumptech.glide.Glide import com.example.coupproject.BuildConfig import com.example.coupproject.R import com.example.coupproject.databinding.ActivityDialogBinding import com.google.firebase.database.ktx.database import com.google.firebase.ktx.Firebase import com.google.firebase.storage.FirebaseStorage class DialogActivity : AppCompatActivity() { private lateinit var binding: ActivityDialogBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityDialogBinding.bind(layoutInflater.inflate(R.layout.activity_dialog, null)) var width = 0 var height = 0 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { val windowMetrics = windowManager.currentWindowMetrics val insets = windowMetrics.windowInsets.getInsetsIgnoringVisibility(WindowInsets.Type.systemBars()) val navi = windowMetrics.windowInsets.getInsetsIgnoringVisibility(WindowInsets.Type.systemBars()) width = windowMetrics.bounds.width() - insets.left - insets.right height = windowMetrics.bounds.height() - navi.top + navi.bottom } else { val windowMetrics = DisplayMetrics() windowManager.defaultDisplay.getMetrics(windowMetrics) width = windowMetrics.widthPixels height = windowMetrics.heightPixels } binding.root.layoutParams = ViewGroup.LayoutParams(width, height) Log.i(TAG, intent.getStringExtra("fileName").toString()) val reference = FirebaseStorage.getInstance() .getReferenceFromUrl("${BuildConfig.FIREBASE_URI_KEY}images/${intent.getStringExtra("fileName")}") // reference.getBytes(1024 * 1024).addOnSuccessListener { // Log.i(TAG, "$it.") // }.addOnFailureListener { Log.e(TAG, it.message, it) } reference.downloadUrl.addOnSuccessListener { Glide.with(this).load(it).into(binding.dialogImage) }.addOnFailureListener { Log.e(TAG, it.message, it) } binding.root.setOnClickListener { finish() } setContentView(binding.root) } override fun onDestroy() { super.onDestroy() photoDelete() } private fun photoDelete() { val storageRef = FirebaseStorage.getInstance(BuildConfig.FIREBASE_URI_KEY).reference val riversRef = storageRef.child("images/${intent.getStringExtra("fileName")}") riversRef.delete().addOnSuccessListener { Log.i(TAG, "${intent.getStringExtra("fileName")} - delete()") }.addOnFailureListener { Log.e(TAG, "${intent.getStringExtra("fileName")} - deleteFail()") } Firebase.database.reference.child(intent.getStringExtra("token").toString()) .removeValue().addOnSuccessListener { Log.i(TAG, "${intent.getStringExtra("token")} - delete()") } } companion object { const val TAG = "DialogActivity" } }
CoupProject/app/src/main/java/com/example/coupproject/view/CoupApplication.kt
3465439063
package com.example.coupproject.view import android.Manifest import android.app.Application import android.content.pm.PackageManager import android.os.Build import android.util.Log import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import com.example.coupproject.BuildConfig import com.kakao.sdk.common.KakaoSdk import com.kakao.sdk.common.util.Utility import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class CoupApplication : Application() { override fun onCreate() { super.onCreate() KakaoSdk.init(this, BuildConfig.KAKAO_NATIVE_KEY) Log.i("CoupApplication", Utility.getKeyHash(this)) } }
CoupProject/app/src/main/java/com/example/coupproject/view/main/MainActivity.kt
11240638
package com.example.coupproject.view.main import android.app.ActivityManager import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.net.Uri import android.os.Build import android.os.Bundle import android.provider.Settings import android.util.Log import android.view.View import android.widget.Toast import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.viewModelScope import com.example.coupproject.BuildConfig import com.example.coupproject.R import com.example.coupproject.data.service.CoupService import com.example.coupproject.databinding.ActivityMainBinding import com.example.coupproject.domain.model.Photo import com.example.coupproject.domain.model.User import com.example.coupproject.viewmodel.MainViewModel import com.google.firebase.database.ktx.database import com.google.firebase.database.ktx.getValue import com.google.firebase.ktx.Firebase import com.google.firebase.storage.FirebaseStorage import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.launch import java.text.SimpleDateFormat @AndroidEntryPoint class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding private val viewModel: MainViewModel by viewModels() private val activityResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { Log.i(TAG, "성공 ${it.data?.data}") it.data?.data?.let { photoUri -> photoUpload(photoUri) } } private val broadcastReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { when (intent?.action) { "com.example.coup_project.START_COUP_SERVICE" -> binding.btnStartService.text = "서비스 중지" "com.example.coup_project.END_COUP_SERVICE" -> binding.btnStartService.text = "서비스 시작" } } } private var count = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.bind(layoutInflater.inflate(R.layout.activity_main, null)) binding.activity = this viewModel.getFriend(intent.getStringExtra("token").toString()) { val member = it.getValue<User>() member?.let { user -> viewModel.saveFriend(user) } } if (isMyServiceRunning(CoupService::class.java)) binding.btnStartService.text = "서비스 중지" else binding.btnStartService.text = "서비스 시작" viewModel.viewModelScope.launch { viewModel.hasMembership.collect { user -> binding.btnAddFriends.visibility = if (user.friend?.isNotEmpty() == true) View.GONE else View.VISIBLE } } binding.btnAddFriends.setOnClickListener { } val intentFilter = IntentFilter().apply { addAction("com.example.coup_project.START_COUP_SERVICE") addAction("com.example.coup_project.END_COUP_SERVICE") } registerReceiver(broadcastReceiver, intentFilter) setContentView(binding.root) } override fun onDestroy() { super.onDestroy() unregisterReceiver(broadcastReceiver) } private fun isMyServiceRunning(serviceClass: Class<*>): Boolean { try { val manager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager for (service in manager.getRunningServices( Int.MAX_VALUE )) { if (serviceClass.name == service.service.className) { return true } } } catch (e: Exception) { return false } return false } override fun onResume() { super.onResume() checkPermission() } private fun checkPermission() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (!Settings.canDrawOverlays(this)) { if (count > 0) { Toast.makeText(this, "다른 앱 위에 표시 권한을 체크해주세요.", Toast.LENGTH_SHORT).show() finish() return } val intent = Intent( Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:$packageName") ) startActivity(intent) count += 1 } // else { // startService(Intent(this, CoupService::class.java)) // } } // else { // startService(Intent(this, CoupService::class.java)) // } } fun startService() { val token = intent.getStringExtra("token").toString() if (token.isNotEmpty()) { if (isMyServiceRunning(CoupService::class.java)) { Log.i(TAG, "StopService - CoupService") stopService(Intent(this, CoupService::class.java).putExtra("token", token)) } else { Log.i(TAG, "StartService - CoupService") startService(Intent(this, CoupService::class.java).putExtra("token", token)) } } } private fun photoUpload(uri: Uri) { val storageRef = FirebaseStorage.getInstance(BuildConfig.FIREBASE_URI_KEY).reference val sdf = SimpleDateFormat("yyyyMMddhhmmss") val fileName = "taetaewon1"//sdf.format(Date()) + ".jpg" val riversRef = storageRef.child("images/$fileName") riversRef.putFile(uri).addOnProgressListener { taskSnapshot -> val btf = taskSnapshot.bytesTransferred val tbc = taskSnapshot.totalByteCount val progress: Double = 100.0 * btf / tbc Log.i(TAG, "progress : $progress") }.addOnFailureListener { Log.e(TAG, "Fail $fileName Upload") } .addOnSuccessListener { Log.i(TAG, "Success $fileName Upload") viewModel.hasMembership.value.friend?.let { Log.i(TAG, "$it let 진") Firebase.database.reference.child(it) .child("photo") .setValue( Photo(it, "taetaewon1"), "" ) } } Log.i(TAG, "End $fileName Upload") } fun selectPhoto() { val intent = Intent(Intent.ACTION_GET_CONTENT).apply { type = "image/*" } activityResultLauncher.launch(intent) } companion object { const val TAG = "MainActivity" } }
CoupProject/app/src/main/java/com/example/coupproject/view/login/LoginActivity.kt
4153129970
package com.example.coupproject.view.login import android.Manifest import android.content.Intent import android.content.pm.PackageManager import android.os.Build import android.os.Bundle import android.util.Log import android.view.View import android.widget.Toast import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import com.example.coupproject.R import com.example.coupproject.databinding.ActivityLoginBinding import com.example.coupproject.view.main.MainActivity import com.example.coupproject.view.member.AddMemberActivity import com.example.coupproject.viewmodel.LoginViewModel import com.kakao.sdk.user.UserApiClient import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class LoginActivity : AppCompatActivity() { private lateinit var binding: ActivityLoginBinding private val viewModel: LoginViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityLoginBinding.bind(layoutInflater.inflate(R.layout.activity_login, null)) binding.activity = this setContentView(binding.root) } override fun onResume() { super.onResume() binding.progress.visibility = View.VISIBLE // me() /** 가상머신테스트용 로그인*/ startActivity( Intent(this@LoginActivity, MainActivity::class.java).putExtra( "token", "1223334444" ) ) requestPermission() } fun logout() { UserApiClient.instance.logout { Log.e(TAG, "Kakao Logout") } } fun me() { UserApiClient.instance.me { user, error -> user?.let { viewModel.getMembership { snapshot -> if (snapshot.hasChild(it.id.toString())) { startActivity( Intent(this@LoginActivity, MainActivity::class.java).putExtra( "token", it.id.toString() ) ) } } } error?.let { Log.e(TAG, it.message, it) } } binding.progress.visibility = View.GONE } fun startKakaoLogin() { viewModel.startKakaoLogin(this) { token, error -> error?.let { Toast.makeText(this, "KakaoLogin Fail : ${it.message}", Toast.LENGTH_SHORT) .show() } token?.let { finish() Log.i(TAG, "$it") startActivity(Intent(this, AddMemberActivity::class.java)) } ?: Toast.makeText(this, "Error KakaoLogin", Toast.LENGTH_SHORT).show() } } private fun requestPermission() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && PackageManager.PERMISSION_DENIED == ContextCompat.checkSelfPermission( this, Manifest.permission.POST_NOTIFICATIONS ) ) { // 푸쉬 권한 없음 ActivityCompat.requestPermissions( this, arrayOf(Manifest.permission.POST_NOTIFICATIONS), NOTIFICATION_PERMISSION_REQUEST_CODE ) } } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) when (requestCode) { NOTIFICATION_PERMISSION_REQUEST_CODE -> { if (grantResults.isNotEmpty()) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { } else { Toast.makeText( applicationContext, "NOTIFICATION_PERMISSION_DENIED", Toast.LENGTH_SHORT ) .show() finish() } } } else -> "" } } private fun getAccessToken() { viewModel.getAccessTokenInfo { accessTokenInfo, throwable -> accessTokenInfo?.let { startActivity(Intent(this@LoginActivity, MainActivity::class.java)) } } } companion object { const val TAG = "LoginActivity" const val NOTIFICATION_PERMISSION_REQUEST_CODE = 1995 } }
CoupProject/app/src/main/java/com/example/coupproject/data/repository/FirebaseRepositoryImpl.kt
2347427209
package com.example.coupproject.data.repository import android.content.Context import android.util.Log import com.example.coupproject.domain.model.User import com.example.coupproject.domain.repository.MainRepository import com.google.android.gms.tasks.OnSuccessListener import com.google.firebase.database.DataSnapshot import com.google.firebase.database.ktx.database import com.google.firebase.ktx.Firebase import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import javax.inject.Inject class FirebaseRepositoryImpl @Inject constructor(private val context: Context) : MainRepository { override fun getFriend( memberId: String, callback: OnSuccessListener<DataSnapshot> ): Flow<Void> { /**roomDb써서 관리할것*/ return flow { Firebase.database.reference.child("users").child(memberId).get() .addOnSuccessListener(callback).addOnFailureListener { Log.e(TAG, it.message, it) } } } override fun getMembership(callback: OnSuccessListener<DataSnapshot>): Flow<Void> { return flow { Log.i(TAG, "getMembership start") Firebase.database.reference.child("users").get().addOnSuccessListener(callback) .addOnFailureListener { Log.e(TAG, it.message, it) } } } override fun setMembership( name: String, memberId: String, callback: OnSuccessListener<Void> ): Flow<Unit> { return flow { Firebase.database.reference.child("users").child(memberId) .setValue(User(name, memberId, null, null)) .addOnSuccessListener(callback) .addOnFailureListener { Log.e(TAG, it.message, it) } } } override fun checkPermission(): Flow<Unit> { return flow { Firebase.database.reference.child("users").setValue(User("이름", "123213213")) emit(Unit) // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // if (!Settings.canDrawOverlays(context)) { // val intent = Intent( // Settings.ACTION_MANAGE_OVERLAY_PERMISSION, // Uri.parse("package:$packageName") // ) // } // } } } companion object { const val TAG = "MainRepositoryImpl" } }
CoupProject/app/src/main/java/com/example/coupproject/data/repository/KakaoRepositoryImpl.kt
1067222834
package com.example.coupproject.data.repository import android.content.Context import com.example.coupproject.domain.repository.KakaoRepository import com.example.coupproject.view.login.LoginActivity import com.kakao.sdk.auth.AuthApiClient import com.kakao.sdk.auth.TokenManagerProvider import com.kakao.sdk.auth.model.OAuthToken import com.kakao.sdk.user.UserApiClient import com.kakao.sdk.user.model.AccessTokenInfo import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import javax.inject.Inject class KakaoRepositoryImpl @Inject constructor(private val context: Context) : KakaoRepository { private val userApiClient: UserApiClient = UserApiClient.instance private val tokenManagerProvider: TokenManagerProvider = TokenManagerProvider.instance private val authApiClient = AuthApiClient.instance override fun startKakaoLogin( activity: LoginActivity, callback: (OAuthToken?, Throwable?) -> Unit ): Flow<Void> { return flow { if (!userApiClient.isKakaoTalkLoginAvailable(activity)) { throw IllegalAccessException("KakaoTalk Not Install") } userApiClient.loginWithKakaoTalk(activity, callback = callback) } } override fun hasAccessToken(): Flow<Boolean> { return flow { // if (authApiClient.hasToken()) { // emit(true) // userApiClient.accessTokenInfo(callback) // } else { // Log.e(TAG, "authApiClient.hasToken() = false") // emit(false) // } emit(authApiClient.hasToken()) } } override fun getAccessTokenInfo(callback: (tokenInfo: AccessTokenInfo?, error: Throwable?) -> Unit): Flow<Unit> { return flow { userApiClient.accessTokenInfo(callback) } } companion object { const val TAG = "LoginRepositoryImpl" const val LOGIN_ACCESS_TOKEN = 0 const val LOGOUT_ACCESS_TOKEN = 1 } }
CoupProject/app/src/main/java/com/example/coupproject/data/service/CoupService.kt
4216381101
package com.example.coupproject.data.service import android.app.NotificationChannel import android.app.NotificationManager import android.app.Service import android.content.Context import android.content.Intent import android.os.Build import android.os.IBinder import android.util.Log import androidx.core.app.NotificationCompat import com.example.coupproject.R import com.example.coupproject.domain.model.Photo import com.example.coupproject.view.dialog.DialogActivity import com.google.firebase.database.ChildEventListener import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.ktx.database import com.google.firebase.database.ktx.getValue import com.google.firebase.ktx.Firebase class CoupService : Service() { private var token = "" private val addValueListener = object : ChildEventListener { override fun onChildAdded(snapshot: DataSnapshot, previousChildName: String?) { Log.i(TAG, "onChildAdded()- ${snapshot.key}//${snapshot.value}") val photo = snapshot.getValue<Photo>() startActivity( Intent( this@CoupService, DialogActivity::class.java ).putExtra("token", photo?.token) .putExtra( "fileName", photo?.fileName ) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) ) } override fun onChildChanged(snapshot: DataSnapshot, previousChildName: String?) { Log.i(TAG, snapshot.key.toString() + "////") // startActivity( // Intent( // this@CoupService, // DialogActivity::class.java // ) // .putExtra( // "fileName", // snapshot.getValue<Photo>()?.fileName // ) // .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) // ) } override fun onChildRemoved(snapshot: DataSnapshot) { Log.i(TAG, "onChildRemoved()") } override fun onChildMoved(snapshot: DataSnapshot, previousChildName: String?) { Log.i(TAG, "onChildMoved()") } override fun onCancelled(error: DatabaseError) { Log.e(TAG, error.message, error.toException()) } } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val name = "name"//getString(R.string.channel_name) val descriptionText = "descriptionText"//getString(R.string.channel_description) val importance = NotificationManager.IMPORTANCE_DEFAULT val channel = NotificationChannel("ServiceStart", name, importance).apply { description = descriptionText } val notificationManager: NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.createNotificationChannel(channel) } val notification = NotificationCompat.Builder(this, "ServiceStart") .setSmallIcon(R.drawable.ic_launcher_foreground) .setContentTitle("CoupService") .setContentText("Play CoupService..") .setOngoing(true) .setPriority(NotificationCompat.PRIORITY_DEFAULT) token = intent?.let { it.getStringExtra("token") }.toString() Firebase.database.reference.child(token).addChildEventListener(addValueListener) sendBroadcast(Intent("com.example.coup_project.START_COUP_SERVICE")) startForeground(1, notification.build()) return START_NOT_STICKY } override fun onBind(p0: Intent?): IBinder? { return null } override fun onCreate() { super.onCreate() } override fun onDestroy() { super.onDestroy() Firebase.database.reference.child(token).removeEventListener(addValueListener) sendBroadcast(Intent("com.example.coup_project.END_COUP_SERVICE")) Log.i(TAG, "End CoupService") } companion object { const val TAG = "CoupService" } }
CoupProject/app/src/main/java/com/example/coupproject/domain/repository/MainRepository.kt
1561842366
package com.example.coupproject.domain.repository import com.google.android.gms.tasks.OnSuccessListener import com.google.firebase.database.DataSnapshot import kotlinx.coroutines.flow.Flow interface MainRepository { fun getFriend(memberId: String,callback: OnSuccessListener<DataSnapshot>): Flow<Void> fun getMembership(callback: OnSuccessListener<DataSnapshot>): Flow<Void> fun setMembership( name: String, memberId: String, callback: OnSuccessListener<Void> ): Flow<Unit> fun checkPermission(): Flow<Unit> }
CoupProject/app/src/main/java/com/example/coupproject/domain/repository/KakaoRepository.kt
2140595178
package com.example.coupproject.domain.repository import com.example.coupproject.view.login.LoginActivity import com.kakao.sdk.auth.model.OAuthToken import com.kakao.sdk.user.model.AccessTokenInfo import kotlinx.coroutines.flow.Flow interface KakaoRepository { fun startKakaoLogin( activity: LoginActivity, callback: (OAuthToken?, Throwable?) -> Unit ): Flow<Void> fun hasAccessToken(): Flow<Boolean> fun getAccessTokenInfo(callback: (tokenInfo: AccessTokenInfo?, error: Throwable?) -> Unit): Flow<Unit> }
CoupProject/app/src/main/java/com/example/coupproject/domain/model/Photo.kt
2128669428
package com.example.coupproject.domain.model import java.util.Date data class Photo( val token: String? = "", val fileName: String? = "", val name: String? = null, val date: Date? = null )
CoupProject/app/src/main/java/com/example/coupproject/domain/model/User.kt
4213644129
package com.example.coupproject.domain.model data class User( val name: String? = null, val token: String? = null, val friend: String? = null, val requestFriend: List<User>? = arrayListOf() )
CoupProject/app/src/main/java/com/example/coupproject/domain/model/Friend.kt
475833182
package com.example.coupproject.domain.model data class Friend(val name: String, val id: String)
CoupProject/app/src/main/java/com/example/coupproject/domain/usecase/main/CheckPermissionUseCase.kt
3897966434
package com.example.coupproject.domain.usecase.main import com.example.coupproject.domain.repository.MainRepository import javax.inject.Inject class CheckPermissionUseCase @Inject constructor(private val repository: MainRepository) { operator fun invoke() = repository.checkPermission() }
CoupProject/app/src/main/java/com/example/coupproject/domain/usecase/main/GetFriendUseCase.kt
4245096086
package com.example.coupproject.domain.usecase.main import com.example.coupproject.domain.repository.MainRepository import com.google.android.gms.tasks.OnSuccessListener import com.google.firebase.database.DataSnapshot import javax.inject.Inject class GetFriendUseCase @Inject constructor(private val repository: MainRepository) { operator fun invoke(memberId: String, callback: OnSuccessListener<DataSnapshot>) = repository.getFriend(memberId, callback) }
CoupProject/app/src/main/java/com/example/coupproject/domain/usecase/main/SetMembershipUseCase.kt
2170075584
package com.example.coupproject.domain.usecase.main import com.example.coupproject.domain.repository.MainRepository import com.google.android.gms.tasks.OnSuccessListener import javax.inject.Inject class SetMembershipUseCase @Inject constructor(private val repository: MainRepository) { operator fun invoke(name: String, memberId: String, callback: OnSuccessListener<Void>) = repository.setMembership(name, memberId, callback) }
CoupProject/app/src/main/java/com/example/coupproject/domain/usecase/main/GetMembershipUseCase.kt
3450353332
package com.example.coupproject.domain.usecase.main import com.example.coupproject.domain.repository.MainRepository import com.google.android.gms.tasks.OnSuccessListener import com.google.firebase.database.DataSnapshot import javax.inject.Inject class GetMembershipUseCase @Inject constructor(private val repository: MainRepository) { operator fun invoke(callback: OnSuccessListener<DataSnapshot>) = repository.getMembership(callback) }
CoupProject/app/src/main/java/com/example/coupproject/domain/usecase/login/StartKakaoLoginUseCase.kt
1485340983
package com.example.coupproject.domain.usecase.login import com.example.coupproject.domain.repository.KakaoRepository import com.example.coupproject.view.login.LoginActivity import com.kakao.sdk.auth.model.OAuthToken import javax.inject.Inject class StartKakaoLoginUseCase @Inject constructor(private val repository: KakaoRepository) { operator fun invoke( activity: LoginActivity, callback: (OAuthToken?, Throwable?) -> Unit ) = repository.startKakaoLogin(activity, callback) }
CoupProject/app/src/main/java/com/example/coupproject/domain/usecase/login/GetAccessTokenInfoUseCase.kt
1001297834
package com.example.coupproject.domain.usecase.login import com.example.coupproject.domain.repository.KakaoRepository import com.kakao.sdk.user.model.AccessTokenInfo import javax.inject.Inject class GetAccessTokenInfoUseCase @Inject constructor(private val repository: KakaoRepository) { operator fun invoke(callback: (AccessTokenInfo?, Throwable?) -> Unit) = repository.getAccessTokenInfo(callback) }
CoupProject/app/src/main/java/com/example/coupproject/domain/usecase/login/HasAccessTokenUseCase.kt
1254325496
package com.example.coupproject.domain.usecase.login import com.example.coupproject.domain.repository.KakaoRepository import javax.inject.Inject class HasAccessTokenUseCase @Inject constructor(private val repository: KakaoRepository) { operator fun invoke() = repository.hasAccessToken() }
jb1/app/src/androidTest/java/com/example/myapplication/ExampleInstrumentedTest.kt
1188990709
package com.example.myapplication import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.myapplication", appContext.packageName) } }
jb1/app/src/test/java/com/example/myapplication/ExampleUnitTest.kt
2019423820
package com.example.myapplication import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
jb1/app/src/main/java/com/example/myapplication/MainActivity.kt
1643621873
package com.example.myapplication import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.EditText import android.widget.TextView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.hallo_word) val nameEditText: EditText = findViewById(R.id.NameEditText) val buttonButton: Button = findViewById(R.id.buttonButton) val buttonTextView: TextView = findViewById(R.id.buttonTextView) buttonTextView.text = "Halo" buttonButton.setOnClickListener{ val name = nameEditText.text.toString() buttonTextView.text = "Halo $name" } } }
git-ccs/src/jvmTest/kotlin/de/fruiture/cor/ccs/CCSApplicationTest.kt
2318356779
package de.fruiture.cor.ccs import de.fruiture.cor.ccs.cc.Type import de.fruiture.cor.ccs.git.* import de.fruiture.cor.ccs.git.VersionTag.Companion.versionTag import de.fruiture.cor.ccs.semver.AlphaNumericIdentifier.Companion.alphanumeric import de.fruiture.cor.ccs.semver.PreReleaseIndicator.Strategy.Companion.counter import de.fruiture.cor.ccs.semver.Version.Companion.version import io.kotest.matchers.shouldBe import io.mockk.every import io.mockk.mockk import kotlin.test.Test class CCSApplicationTest { private val oneFeatureAfterMajorRelease = mockk<Git>().apply { every { getLatestVersionTag() } returns versionTag("1.0.0") every { getLatestReleaseTag() } returns versionTag("1.0.0") every { getLogX(from = TagName("1.0.0")) } returns listOf( GitCommit("cafebabe", ZonedDateTime("2001-01-01T13:00Z"), "feat: a feature is born") ) } private val noReleaseYet = mockk<Git>().apply { every { getLatestVersionTag() } returns null every { getLatestReleaseTag() } returns null every { getLogX(from = null) } returns listOf( GitCommit("cafebabe", ZonedDateTime("2001-01-01T13:00Z"), "feat: a feature is born") ) } private val hadABreakingChangeAfterSnapshot = mockk<Git>().apply { every { getLatestVersionTag() } returns versionTag("1.2.3-SNAPSHOT.5") every { getLogX(from = TagName("1.2.3-SNAPSHOT.5")) } returns listOf( GitCommit("cafebabe", ZonedDateTime("2001-01-01T13:00Z"), "feat!: a feature with a breaking change") ) } private val afterMultipleReleases = mockk<Git>().apply { every { getLatestVersionTag(before(version("1.0.0"))) } returns versionTag("1.0.0-RC.3") every { getLatestReleaseTag(before(version("1.0.0"))) } returns versionTag("vers0.3.7") every { getLatestVersionTag(until(version("1.0.0"))) } returns versionTag("v1.0.0") every { getLogX(from = TagName("vers0.3.7"), to = TagName("v1.0.0")) } returns listOf( GitCommit("cafebabe", ZonedDateTime("2001-01-01T13:00Z"), "feat: range change") ) } private val mixedBagOfCommits = mockk<Git>().apply { every { getLatestVersionTag() } returns versionTag("1.0.0") every { getLogX(from = TagName("1.0.0")) } returns listOf( GitCommit("0001", ZonedDateTime("2001-01-01T13:01Z"), "feat: feature1"), GitCommit("002", ZonedDateTime("2001-01-01T13:02Z"), "fix: fix2"), GitCommit("003", ZonedDateTime("2001-01-01T13:03Z"), "perf: perf3"), GitCommit("004", ZonedDateTime("2001-01-01T13:04Z"), "none4") ) } @Test fun `get next release version`() { CCSApplication(oneFeatureAfterMajorRelease).getNextRelease() shouldBe version("1.1.0") } @Test fun `get next pre-release version`() { CCSApplication(oneFeatureAfterMajorRelease).getNextPreRelease(counter()) shouldBe version("1.1.0-RC.1") CCSApplication(oneFeatureAfterMajorRelease).getNextPreRelease(counter("alpha".alphanumeric)) shouldBe version("1.1.0-alpha.1") } @Test fun `get initial release or snapshot`() { CCSApplication(noReleaseYet).getNextRelease() shouldBe version("0.0.1") CCSApplication(noReleaseYet).getNextPreRelease(counter("RC".alphanumeric)) shouldBe version("0.0.1-RC.1") CCSApplication(noReleaseYet).getNextPreRelease(counter()) shouldBe version("0.0.1-RC.1") } @Test fun `get change log`() { CCSApplication(oneFeatureAfterMajorRelease).getChangeLogJson() shouldBe """[{"hash":"cafebabe","date":"2001-01-01T13:00Z","message":"feat: a feature is born",""" + """"conventional":{"type":"feat","description":"a feature is born"}}]""" CCSApplication(noReleaseYet).getChangeLogJson() shouldBe """[{"hash":"cafebabe","date":"2001-01-01T13:00Z","message":"feat: a feature is born",""" + """"conventional":{"type":"feat","description":"a feature is born"}}]""" } @Test fun `get change log before a certain version`() { CCSApplication(afterMultipleReleases).getChangeLogJson(release = true, before = version("1.0.0")) shouldBe """[{"hash":"cafebabe","date":"2001-01-01T13:00Z","message":"feat: range change",""" + """"conventional":{"type":"feat","description":"range change"}}]""" } @Test fun `breaking change is recognized`() { CCSApplication(hadABreakingChangeAfterSnapshot).getNextRelease() shouldBe version("2.0.0") CCSApplication(hadABreakingChangeAfterSnapshot).getNextPreRelease(counter()) shouldBe version("2.0.0-RC.1") } @Test fun `get latest release`() { CCSApplication(oneFeatureAfterMajorRelease).getLatestVersion(true) shouldBe "1.0.0" CCSApplication(noReleaseYet).getLatestVersion(true) shouldBe null } @Test fun `get latest version`() { CCSApplication(hadABreakingChangeAfterSnapshot).getLatestVersion() shouldBe "1.2.3-SNAPSHOT.5" } @Test fun `get latest version before another version`() { CCSApplication(afterMultipleReleases).getLatestVersion(before = version("1.0.0")) shouldBe "1.0.0-RC.3" CCSApplication(afterMultipleReleases).getLatestVersion( release = true, before = version("1.0.0") ) shouldBe "0.3.7" } @Test fun `get markdown`() { CCSApplication(oneFeatureAfterMajorRelease).getChangeLogMarkdown( release = false, sections = Sections(mapOf("Neue Funktionen" to setOf(Type("feat")))) ) shouldBe """ ## Neue Funktionen * a feature is born """.trimIndent() } @Test fun `get markdown with breaking changes`() { CCSApplication(hadABreakingChangeAfterSnapshot).getChangeLogMarkdown( release = false, sections = Sections().setBreakingChanges("API broken") ) shouldBe """ ## API broken * a feature with a breaking change """.trimIndent() } @Test fun `summarize various types`() { CCSApplication(mixedBagOfCommits).getChangeLogMarkdown() shouldBe """ ## Features * feature1 ## Bugfixes * fix2 ## Other * perf3 * none4 """.trimIndent() } }
git-ccs/src/jvmTest/kotlin/de/fruiture/cor/ccs/CLITest.kt
1922482177
package de.fruiture.cor.ccs import VERSION import com.github.ajalt.clikt.testing.test import de.fruiture.cor.ccs.cc.Type import de.fruiture.cor.ccs.semver.AlphaNumericIdentifier.Companion.alphanumeric import de.fruiture.cor.ccs.semver.ChangeType import de.fruiture.cor.ccs.semver.PreRelease import de.fruiture.cor.ccs.semver.PreReleaseIndicator.Strategy.Companion.counter import de.fruiture.cor.ccs.semver.PreReleaseIndicator.Strategy.Companion.plus import de.fruiture.cor.ccs.semver.PreReleaseIndicator.Strategy.Companion.static import de.fruiture.cor.ccs.semver.Release import de.fruiture.cor.ccs.semver.Version.Companion.version import io.kotest.matchers.shouldBe import io.kotest.matchers.string.shouldStartWith import io.mockk.called import io.mockk.every import io.mockk.mockk import io.mockk.verify import kotlin.test.Test class CLITest { private val app = mockk<CCSApplication>(relaxed = true) private val cli = CLI(app) init { every { app.getNextRelease() } returns version("1.2.3") as Release every { app.getNextPreRelease(counter()) } returns version("1.2.3-RC.5") as PreRelease } @Test fun `next release`() { cli.test("next release").output shouldBe "1.2.3" verify { app.getNextRelease() } } @Test fun `next pre-release`() { cli.test("next pre-release").output shouldBe "1.2.3-RC.5" verify { app.getNextPreRelease(counter()) } } @Test fun `next pre-release custom`() { every { app.getNextPreRelease(counter("alpha".alphanumeric)) } returns version("1.2.3-alpha.5") as PreRelease cli.test("next pre-release -f alpha.1").output shouldBe "1.2.3-alpha.5" } @Test fun `combined counter and static strategy`() { every { app.getNextPreRelease( counter("alpha".alphanumeric) + static("snap".alphanumeric) ) } returns version("1.2.3-alpha.1.snap") as PreRelease cli.test("next pre-release -f alpha.1.snap").output shouldBe "1.2.3-alpha.1.snap" } @Test fun `show help`() { cli.test("next --help").output shouldStartWith """ Usage: git-ccs next [<options>] <command> [<args>]... compute the next semantic version based on changes since the last version tag """.trimIndent() verify { app wasNot called } } @Test fun `show help when nothing`() { cli.test("").output shouldStartWith "Usage: git-ccs" } @Test fun `illegal command`() { cli.test("nope").stderr shouldBe """ Usage: git-ccs [<options>] <command> [<args>]... Error: no such subcommand nope """.trimIndent() verify { app wasNot called } } @Test fun `allow non-bumps`() { every { app.getNextRelease( ChangeMapping() + (Type("default") to ChangeType.NONE) ) } returns version("1.1.1") as Release cli.test("next release -n default").output shouldBe "1.1.1" } @Test fun `get latest release tag`() { every { app.getLatestVersion(true) } returns "0.2.3" cli.test("latest -r").output shouldBe "0.2.3" } @Test fun `get latest release fails if no release yet`() { every { app.getLatestVersion(true) } returns null val result = cli.test("latest -r") result.statusCode shouldBe 1 result.stderr shouldBe "no version found\n" } @Test fun `get latest version tag`() { every { app.getLatestVersion() } returns "0.2.3-SNAP" cli.test("latest").output shouldBe "0.2.3-SNAP" } @Test fun `get latest -t`() { every { app.getLatestVersion(before = version("1.0.0")) } returns "1.0.0-RC.5" cli.test("latest -t 1.0.0").output shouldBe "1.0.0-RC.5" } @Test fun `get log since release`() { every { app.getChangeLogJson(true) } returns "[{json}]" cli.test("log --release").output shouldBe "[{json}]" } @Test fun `log -t`() { every { app.getChangeLogJson(true, before = version("1.0.0")) } returns "[{json}]" cli.test("log --release --target 1.0.0").output shouldBe "[{json}]" } @Test fun `get markdown`() { every { app.getChangeLogMarkdown(false) } returns "*markdown*" cli.test("changes").output shouldBe "*markdown*" } @Test fun `changes -t`() { every { app.getChangeLogMarkdown(true, target = version("1.0.0")) } returns "*markdown of changes leading to 1.0.0" cli.test("changes -rt 1.0.0").output shouldBe "*markdown of changes leading to 1.0.0" } @Test fun `markdown with custom headings`() { every { app.getChangeLogMarkdown( release = false, sections = Sections(mapOf("Fun" to setOf(Type("feat")))), level = 1 ) } returns "# Fun" cli.test("changes -s 'Fun=feat' -l 1").output shouldBe "# Fun" } @Test fun `show version`() { cli.test("--version").output shouldBe "git-ccs version $VERSION\n" } }
git-ccs/src/jvmTest/kotlin/de/fruiture/cor/ccs/ChangeMappingTest.kt
1632591763
package de.fruiture.cor.ccs import de.fruiture.cor.ccs.cc.Type import de.fruiture.cor.ccs.git.GitCommit import de.fruiture.cor.ccs.git.NON_CONVENTIONAL_COMMIT_TYPE import de.fruiture.cor.ccs.git.ZonedDateTime import de.fruiture.cor.ccs.semver.ChangeType import io.kotest.matchers.shouldBe import kotlin.test.Test class ChangeMappingTest { private val mapping = ChangeMapping() @Test fun `default mapping`() { mapping.of(Type("feat")) shouldBe ChangeType.MINOR mapping.of(NON_CONVENTIONAL_COMMIT_TYPE) shouldBe ChangeType.PATCH mapping.of(DEFAULT_COMMIT_TYPE) shouldBe ChangeType.PATCH } @Test fun `commit mapping`() { mapping.of( GitCommit("cafe", ZonedDateTime("2001-01-01T12:00:00Z"), "perf!: break API for speed") ) shouldBe ChangeType.MAJOR mapping.of( GitCommit("cafe", ZonedDateTime("2001-01-01T12:00:00Z"), "perf: break API for speed") ) shouldBe ChangeType.PATCH } @Test fun `adjust mapping to none-bump`() { val adjusted = mapping + (DEFAULT_COMMIT_TYPE to ChangeType.NONE) adjusted.of(Type("doc")) shouldBe ChangeType.NONE } }
git-ccs/src/jvmTest/kotlin/de/fruiture/cor/ccs/semver/VersionTest.kt
2444821065
package de.fruiture.cor.ccs.semver import de.fruiture.cor.ccs.semver.AlphaNumericIdentifier.Companion.alphanumeric import de.fruiture.cor.ccs.semver.DigitIdentifier.Companion.digits import de.fruiture.cor.ccs.semver.NumericIdentifier.Companion.numeric import de.fruiture.cor.ccs.semver.Version.Companion.version import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.shouldBe import kotlin.test.Test class VersionTest { @Test fun `represent version cores`() { VersionCore.of( major = 1, minor = 0, patch = 0 ).toString() shouldBe "1.0.0" } @Test fun `represent pre-release`() { PreReleaseIndicator( listOf( PreReleaseIdentifier.identifier("alpha".alphanumeric), PreReleaseIdentifier.identifier(26.numeric) ) ).toString() shouldBe "alpha.26" } @Test fun `compare release versions`() { val v100 = Release(VersionCore.of(1, 0, 0)) val v101 = Release(VersionCore.of(1, 0, 1)) v100.compareTo(v101) shouldBe -1 v101.compareTo(v100) shouldBe 1 } @Test fun `compare pre-release versions with releases`() { val v100Alpha = PreRelease( VersionCore.of(1, 0, 0), PreReleaseIndicator.of( PreReleaseIdentifier.identifier("alpha".alphanumeric) ) ) val v100 = Release(VersionCore.of(1, 0, 0)) val v001 = Release(VersionCore.of(0, 0, 1)) v100Alpha.compareTo(v100) shouldBe -1 v100.compareTo(v100Alpha) shouldBe 1 v100Alpha.compareTo(v001) shouldBe 1 v001.compareTo(v100Alpha) shouldBe -1 } @Test fun `compare pre-releases`() { val alpha = PreRelease( VersionCore.of(1, 0, 0), PreReleaseIndicator.of( PreReleaseIdentifier.identifier("alpha".alphanumeric) ) ) val beta = PreRelease( VersionCore.of(1, 0, 0), PreReleaseIndicator.of( PreReleaseIdentifier.identifier("beta".alphanumeric) ) ) val betaPlus = PreRelease( VersionCore.of(1, 0, 0), PreReleaseIndicator.of( PreReleaseIdentifier.identifier("beta".alphanumeric), PreReleaseIdentifier.identifier("plus".alphanumeric) ) ) alpha.compareTo(beta) shouldBe -1 beta.compareTo(alpha) shouldBe 1 beta.compareTo(betaPlus) shouldBe -1 } @Test fun `allow build identifiers`() { Release( VersionCore.of(2, 1, 3), Build( listOf( BuildIdentifier.identifier("build".alphanumeric), BuildIdentifier.identifier("000".digits) ) ) ).toString() shouldBe "2.1.3+build.000" PreRelease( VersionCore.of(2, 1, 3), PreReleaseIndicator.of( PreReleaseIdentifier.identifier("alpha".alphanumeric) ), Build( listOf( BuildIdentifier.identifier("build".alphanumeric), BuildIdentifier.identifier("000".digits) ) ) ).toString() shouldBe "2.1.3-alpha+build.000" } @Test fun `version strings`() { Release(VersionCore.of(1, 2, 3)).toString() shouldBe "1.2.3" PreRelease( VersionCore.of(1, 2, 3), PreReleaseIndicator.of( PreReleaseIdentifier.identifier("alpha".alphanumeric) ) ).toString() shouldBe "1.2.3-alpha" } @Test fun `valid alphanumeric identifiers`() { AlphaNumericIdentifier("foo") AlphaNumericIdentifier("foo-bar") shouldThrow<IllegalArgumentException> { AlphaNumericIdentifier("0000") } AlphaNumericIdentifier("0000a") } @Test fun `parsing versions`() { version("1.2.3") shouldBe Release(VersionCore.of(1, 2, 3)) version("1.2.3+x23.005") shouldBe Release( VersionCore.of(1, 2, 3), Build(listOf(BuildIdentifier.identifier("x23".alphanumeric), BuildIdentifier.identifier("005".digits))) ) version("1.2.3-alpha.7.go-go+x23.005") shouldBe PreRelease( VersionCore.of(1, 2, 3), PreReleaseIndicator( listOf( PreReleaseIdentifier.identifier("alpha".alphanumeric), PreReleaseIdentifier.identifier(7.numeric), PreReleaseIdentifier.identifier("go-go".alphanumeric) ) ), Build(listOf(BuildIdentifier.identifier("x23".alphanumeric), BuildIdentifier.identifier("005".digits))) ) version("1.2.3-alpha.7.go-go") shouldBe PreRelease( VersionCore.of(1, 2, 3), PreReleaseIndicator( listOf( PreReleaseIdentifier.identifier("alpha".alphanumeric), PreReleaseIdentifier.identifier(7.numeric), PreReleaseIdentifier.identifier("go-go".alphanumeric) ) ) ) } @Test fun `extracting version out of strings`() { Version.extractVersion("v1.2.3") shouldBe version("1.2.3") Version.extractVersion("version:2.1.0-SNAPSHOT.2") shouldBe version("2.1.0-SNAPSHOT.2") Version.extractVersion("1.3.9 other stuff") shouldBe version("1.3.9") Version.extractVersion("1.2prefix1.3.9-RC.7/suffix") shouldBe version("1.3.9-RC.7") } }
git-ccs/src/jvmTest/kotlin/de/fruiture/cor/ccs/semver/VersionUsageTest.kt
3110317512
package de.fruiture.cor.ccs.semver import de.fruiture.cor.ccs.semver.AlphaNumericIdentifier.Companion.alphanumeric import de.fruiture.cor.ccs.semver.Build.Companion.build import de.fruiture.cor.ccs.semver.PreReleaseIndicator.Companion.preRelease import de.fruiture.cor.ccs.semver.PreReleaseIndicator.Strategy.Companion.counter import de.fruiture.cor.ccs.semver.PreReleaseIndicator.Strategy.Companion.plus import de.fruiture.cor.ccs.semver.PreReleaseIndicator.Strategy.Companion.static import de.fruiture.cor.ccs.semver.Version.Companion.version import io.kotest.matchers.shouldBe import kotlin.test.Test class VersionUsageTest { @Test fun `special releases`() { Version.initial shouldBe version("0.0.1") Version.stable shouldBe version("1.0.0") } @Test fun `bumping releases`() { version("1.0.0").next(ChangeType.MINOR) shouldBe version("1.1.0") version("1.0.0").next(ChangeType.PATCH) shouldBe version("1.0.1") version("1.0.0").next(ChangeType.MAJOR) shouldBe version("2.0.0") version("2.3.25").next(ChangeType.PATCH) shouldBe version("2.3.26") version("2.3.25").next(ChangeType.MINOR) shouldBe version("2.4.0") version("2.3.25").next(ChangeType.MAJOR) shouldBe version("3.0.0") version("2.3.25").next(ChangeType.NONE) shouldBe version("2.3.25") } @Test fun `bumping pre-releases drops pre-release but may not bump release`() { version("1.0.7-rc.1").next(ChangeType.MAJOR) shouldBe version("2.0.0") version("1.0.7-rc.1").next(ChangeType.MINOR) shouldBe version("1.1.0") version("1.0.7-rc.1").next(ChangeType.PATCH) shouldBe version("1.0.7") version("2.3.0-rc.1").next(ChangeType.MAJOR) shouldBe version("3.0.0") version("2.3.0-rc.1").next(ChangeType.MINOR) shouldBe version("2.3.0") version("2.3.0-rc.1").next(ChangeType.PATCH) shouldBe version("2.3.0") version("3.0.0-rc.1").next(ChangeType.MAJOR) shouldBe version("3.0.0") version("3.0.0-rc.1").next(ChangeType.MINOR) shouldBe version("3.0.0") version("3.0.0-rc.1").next(ChangeType.PATCH) shouldBe version("3.0.0") version("1.0.7-rc.1").next(ChangeType.NONE) shouldBe version("1.0.7") } @Test fun `bumping any releases drops build metadata`() { version("1.0.7-rc.1+commit").next(ChangeType.PATCH) shouldBe version("1.0.7") version("1.0.7-rc.1+commit").next(ChangeType.MAJOR) shouldBe version("2.0.0") version("1.0.7+commit").next(ChangeType.MAJOR) shouldBe version("2.0.0") version("1.0.7+commit").next(ChangeType.PATCH) shouldBe version("1.0.8") } @Test fun `attach pre-release and build metadata`() { version("1.2.3-snapshot").release shouldBe version("1.2.3") version("3.2.0").release.preRelease("rc.1") shouldBe version("3.2.0-rc.1") version("3.2.0").build("job.267") shouldBe version("3.2.0+job.267") version("3.2.0+job.123").build("job.267") shouldBe version("3.2.0+job.267") version("4.0.99-RC.1").build("job.008") shouldBe version("4.0.99-RC.1+job.008") } @Test fun `more sugar - append arbitrary pre-release and build metadata`() { version("1.2.3") + preRelease("RC.5") shouldBe version("1.2.3-RC.5") version("1.2.3-RC.3") + preRelease("RC.5") shouldBe version("1.2.3-RC.3.RC.5") version("1.2.3+cafe") + preRelease("RC.5") shouldBe version("1.2.3-RC.5+cafe") version("1.2.3-alpha+cafe") + preRelease("RC.5") shouldBe version("1.2.3-alpha.RC.5+cafe") version("1.2.3") + build("c1f2e3") shouldBe version("1.2.3+c1f2e3") version("1.2.3-pre") + build("c1f2e3") shouldBe version("1.2.3-pre+c1f2e3") version("1.2.3-pre+cafe") + build("c1f2e3") shouldBe version("1.2.3-pre+cafe.c1f2e3") } @Test fun `bump pre-release only`() { version("1.2.3-rc.1").nextPreRelease(counter("rc".alphanumeric)) shouldBe version("1.2.3-rc.2") version("1.2.3-rc").nextPreRelease(counter("rc".alphanumeric)) shouldBe version("1.2.3-rc.2") version("1.2.3").nextPreRelease() shouldBe version("1.2.3-RC.1") version("1.2.3").nextPreRelease(counter("RC".alphanumeric)) shouldBe version("1.2.3-RC.1") val alpha = counter("alpha".alphanumeric) version("1.2.3-beta").nextPreRelease(alpha) shouldBe version("1.2.3-beta.alpha.1") version("1.2.3-alpha").nextPreRelease(alpha) shouldBe version("1.2.3-alpha.2") version("1.2.3-alpha.7").nextPreRelease(alpha) shouldBe version("1.2.3-alpha.8") version("1.2.3").nextPreRelease(alpha) shouldBe version("1.2.3-alpha.1") version("1.2.3-alpha.7.junk").nextPreRelease(alpha) shouldBe version("1.2.3-alpha.8.junk") } @Test fun `static pre-releases`() { version("1.2.3").nextPreRelease(static()) shouldBe version("1.2.3-SNAPSHOT") version("1.2.3").nextPreRelease(ChangeType.MINOR, static()) shouldBe version("1.3.0-SNAPSHOT") version("1.2.3-SNAPSHOT").nextPreRelease(ChangeType.PATCH, static()) shouldBe version("1.2.3-SNAPSHOT") version("1.2.3").nextPreRelease(ChangeType.PATCH, static("foo".alphanumeric)) shouldBe version("1.2.4-foo") } @Test fun `pre release strategy`() { val lastRelease = version("1.2.3") as Release val lastPreRelease = version("1.2.4-RC.1") as PreRelease lastRelease.next(ChangeType.PATCH).nextPreRelease() shouldBe lastPreRelease lastRelease.nextPreRelease(ChangeType.PATCH) shouldBe lastPreRelease lastPreRelease.nextPreRelease(ChangeType.NONE) shouldBe version("1.2.4-RC.2") lastPreRelease.nextPreRelease(ChangeType.PATCH) shouldBe version("1.2.4-RC.2") lastPreRelease.nextPreRelease(ChangeType.MINOR) shouldBe version("1.3.0-RC.1") lastPreRelease.nextPreRelease(ChangeType.MAJOR) shouldBe version("2.0.0-RC.1") (version("2.0.0-RC.1") as PreRelease).nextPreRelease(ChangeType.PATCH) shouldBe version("2.0.0-RC.2") } @Test fun `counter pre-releases with static suffix`() { val strategy = counter("RC".alphanumeric) + static("SNAPSHOT".alphanumeric) val inverse = static("SNAPSHOT".alphanumeric) + counter("RC".alphanumeric) version("1.2.3").nextPreRelease(ChangeType.PATCH, strategy) shouldBe version("1.2.4-RC.1.SNAPSHOT") version("1.2.3").nextPreRelease(ChangeType.PATCH, inverse) shouldBe version("1.2.4-SNAPSHOT.RC.1") version("1.2.4-RC.1.SNAPSHOT").nextPreRelease(ChangeType.PATCH, strategy) shouldBe version("1.2.4-RC.2.SNAPSHOT") } }
git-ccs/src/jvmTest/kotlin/de/fruiture/cor/ccs/cc/ConventionalCommitMessageTest.kt
1941636800
package de.fruiture.cor.ccs.cc import de.fruiture.cor.ccs.cc.ConventionalCommitMessage.Companion.message import io.kotest.matchers.shouldBe import kotlin.test.Test class ConventionalCommitMessageTest { @Test fun `parse a conventional commit`() { val msg = message("docs: correct spelling of CHANGELOG") msg.type shouldBe Type("docs") msg.description shouldBe Description("correct spelling of CHANGELOG") msg.scope shouldBe null } @Test fun `parse with scope`() { val msg = message("fix(parser): support scopes") msg.type shouldBe Type("fix") msg.scope shouldBe Scope("parser") } @Test fun `parse with body`() { val msg = message( """ fix: prevent racing of requests Introduce a request id and a reference to latest request. Dismiss incoming responses other than from latest request. """.trimIndent() ) msg.type shouldBe Type("fix") msg.description shouldBe Description("prevent racing of requests") msg.body shouldBe Body("Introduce a request id and a reference to latest request. Dismiss\nincoming responses other than from latest request.") } @Test fun `multi-paragraph body`() { message( """ fix: prevent racing of requests Introduce a request id and a reference to latest request. Dismiss incoming responses other than from latest request. Remove timeouts which were used to mitigate the racing issue but are obsolete now. """.trimIndent() ).body shouldBe Body( """ Introduce a request id and a reference to latest request. Dismiss incoming responses other than from latest request. Remove timeouts which were used to mitigate the racing issue but are obsolete now. """.trimIndent() ) } @Test fun `breaking change in headline`() { message("fix!: bugfix breaks API").breakingChange shouldBe "bugfix breaks API" } @Test fun `breaking change in the footer (and useless newlines)`() { message( """ feat: cool stuff BREAKING CHANGE: but the api changes BREAKING CHANGE: but the api changes """.trimIndent() ).breakingChange shouldBe "but the api changes" } @Test fun `breaking change in the footer after body`() { val msg = message( """ feat: cool stuff Paragraph1 Paragraph2 BREAKING CHANGE: but the api changes """.trimIndent() ) msg.breakingChange shouldBe "but the api changes" msg.body shouldBe Body( """ Paragraph1 Paragraph2 """.trimIndent() ) } @Test fun footers() { val msg = message( """ fun: Fun Done-By: Me BREAKING CHANGE: Me too """.trimIndent() ) msg.breakingChange shouldBe "Me too" msg.footers shouldBe listOf( GenericFooter("Done-By", "Me"), BreakingChange("Me too") ) } @Test fun `convert to string`() { ConventionalCommitMessage( type = Type("feat"), description = Description("some text"), scope = Scope("test") ).toString() shouldBe "feat(test): some text" } @Test fun `all aspects in and out`() { message( """ fun(fun)!: Fun Fun Fun Fun! More Fun Done-By: Me BREAKING-CHANGE: Me too """.trimIndent() ).toString() shouldBe """ fun(fun)!: Fun Fun Fun Fun! More Fun Done-By: Me BREAKING-CHANGE: Me too """.trimIndent() } }
git-ccs/src/jvmTest/kotlin/de/fruiture/cor/ccs/git/KommandSystemCallerTest.kt
2054064752
package de.fruiture.cor.ccs.git import io.kotest.matchers.shouldBe import io.kotest.matchers.string.shouldContain import kotlin.test.Test class KommandSystemCallerTest { private val caller = KommandSystemCaller() @Test fun `invoke git -v`() { val result = caller.call("git", listOf("-v")) result.code shouldBe 0 result.stderr shouldBe emptyList() result.stdout.first() shouldContain Regex("^git version") } @Test fun `invoke git -invalid-option`() { val result = caller.call("git", listOf("-invalid-option")) result.code shouldBe 129 result.stderr.first() shouldBe "unknown option: -invalid-option" } }
git-ccs/src/jvmTest/kotlin/de/fruiture/cor/ccs/git/GitCommitTest.kt
1913711391
package de.fruiture.cor.ccs.git import de.fruiture.cor.ccs.cc.ConventionalCommitMessage import de.fruiture.cor.ccs.cc.ConventionalCommitMessage.Companion.message import de.fruiture.cor.ccs.cc.Description import de.fruiture.cor.ccs.cc.Type import io.kotest.matchers.shouldBe import kotlin.test.Test class GitCommitTest { @Test fun `parse conventional commit`() { val commit = GitCommit( hash = "cafe", date = ZonedDateTime("2001-01-01T12:00:00Z"), message = "feat: a feature" ) commit.conventional shouldBe message("feat: a feature") commit.type shouldBe Type("feat") commit.hasBreakingChange shouldBe false } @Test fun `tolerate invalid commit message`() { val commit = GitCommit( hash = "cafe", date = ZonedDateTime("2001-01-01T12:00:00Z"), message = "non-conventional commit" ) commit.conventional shouldBe ConventionalCommitMessage( type = NON_CONVENTIONAL_COMMIT_TYPE, description = Description("non-conventional commit") ) commit.type shouldBe Type("none") commit.hasBreakingChange shouldBe false } }
git-ccs/src/jvmTest/kotlin/de/fruiture/cor/ccs/git/GitTest.kt
543333548
package de.fruiture.cor.ccs.git import de.fruiture.cor.ccs.git.VersionTag.Companion.versionTag import de.fruiture.cor.ccs.semver.Version.Companion.version import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.collections.shouldHaveSize import io.kotest.matchers.shouldBe import io.mockk.every import io.mockk.mockk import kotlin.test.Test class GitTest { private val forEachRef = listOf( "for-each-ref", "--merged", "HEAD", "--sort=-committerdate", "--format=%(refname:short)", "refs/tags/*.*.*" ) @Test fun `get latest version or release tag using git for-each-ref`() { val sys = mockk<SystemCaller>().apply { every { call("git", forEachRef) } returns SystemCallResult( code = 0, stdout = listOf( "v2.1.0-SNAPSHOT.1", "2.1.0-SNAPSHOT.2", "rel2.0.0", "1.3.9", "1.3.9-RC.7" ) ) } val git = Git(sys) git.getLatestVersionTag() shouldBe versionTag("2.1.0-SNAPSHOT.2") git.getLatestVersionTag(before(version("2.1.0-SNAPSHOT.2"))) shouldBe versionTag("v2.1.0-SNAPSHOT.1") git.getLatestVersionTag(before(version("2.1.0-SNAPSHOT.1"))) shouldBe versionTag("rel2.0.0") git.getLatestReleaseTag() shouldBe versionTag("rel2.0.0") git.getLatestReleaseTag(before(version("2.1.0-SNAPSHOT.2"))) shouldBe versionTag("rel2.0.0") git.getLatestReleaseTag(before(version("2.0.0"))) shouldBe versionTag("1.3.9") git.getLatestReleaseTag(before(version("1.3.9"))) shouldBe null git.getLatestVersionTag(before(version("1.3.9"))) shouldBe versionTag("1.3.9-RC.7") git.getLatestVersionTag(before(version("1.3.9-RC.7"))) shouldBe null } @Test fun `find no version`() { val sys = mockk<SystemCaller>().apply { every { call("git", forEachRef) } returns SystemCallResult( code = 0, stdout = emptyList() ) } Git(sys).getLatestReleaseTag() shouldBe null Git(sys).getLatestVersionTag() shouldBe null } @Test fun `tolerate non-versions`() { val sys = mockk<SystemCaller>().apply { every { call("git", forEachRef) } returns SystemCallResult( code = 0, stdout = listOf( "2.1.0-SNAPSHOT.1", "2.1.0-SNAPSHOT.2", "accidental.version.string", "2.0.0" ) ) } Git(sys).getLatestReleaseTag() shouldBe versionTag("2.0.0") } @Test fun `any error`() { val sys = object : SystemCaller { override fun call(command: String, arguments: List<String>): SystemCallResult { return SystemCallResult( code = 127, stderr = listOf("command not found: $command") ) } } shouldThrow<RuntimeException> { Git(sys).getLatestVersionTag() } } @Test fun `get machine readable log`() { val sys = object : SystemCaller { override fun call(command: String, arguments: List<String>): SystemCallResult { command shouldBe "git" arguments shouldBe listOf("log", "--format=format:%H %aI%n%B%n%x1E", "1.0.0..HEAD") return SystemCallResult( code = 0, stdout = """ 948f00f8b349c6f9652809f924254ffe7a497227 2024-01-20T21:51:33+01:00 feat: blablabla BREAKING CHANGE: did something dudu here ${RECORD_SEPARATOR} b8d181d9e803da9ceba0c3c4918317124d678656 2024-01-20T21:31:01+01:00 non conventional commit """.trimIndent().lines() ) } } Git(sys).getLogX( from = TagName("1.0.0") ) shouldBe listOf( GitCommit( hash = "948f00f8b349c6f9652809f924254ffe7a497227", date = ZonedDateTime("2024-01-20T21:51:33+01:00"), message = """ feat: blablabla BREAKING CHANGE: did something dudu here """.trimIndent() ), GitCommit( hash = "b8d181d9e803da9ceba0c3c4918317124d678656", date = ZonedDateTime("2024-01-20T21:31:01+01:00"), message = "non conventional commit" ) ) } @Test fun `get full log`() { val sys = object : SystemCaller { override fun call(command: String, arguments: List<String>): SystemCallResult { command shouldBe "git" arguments shouldBe listOf("log", "--format=format:%H %aI%n%B%n%x1E", "HEAD") return SystemCallResult( code = 0, stdout = """ b8d181d9e803da9ceba0c3c4918317124d678656 2024-01-20T21:31:01+01:00 non conventional commit """.trimIndent().lines() ) } } Git(sys).getLogX() shouldBe listOf( GitCommit( hash = "b8d181d9e803da9ceba0c3c4918317124d678656", date = ZonedDateTime("2024-01-20T21:31:01+01:00"), message = "non conventional commit" ) ) } @Test fun `get log until a version`() { val sys = mockk<SystemCaller>().apply { every { call( "git", listOf( "log", "--format=format:%H %aI%n%B%n%x1E", "v1.0.0" ) ) } returns SystemCallResult( 0, stdout = """ b8d181d9e803da9ceba0c3c4918317124d678656 2024-01-20T21:31:01+01:00 first commit """.trimIndent().lines() ) } Git(sys).getLogX(to = TagName("v1.0.0")) shouldHaveSize 1 } }
git-ccs/src/commonMain/kotlin/main.kt
4031198852
import de.fruiture.cor.ccs.CCSApplication import de.fruiture.cor.ccs.CLI import de.fruiture.cor.ccs.git.Git import de.fruiture.cor.ccs.git.KommandSystemCaller fun main(args: Array<String>) { CLI(CCSApplication(Git(KommandSystemCaller()))).main(args) }
git-ccs/src/commonMain/kotlin/version.kt
2675147533
// this entire file is overridden in CI, don't put anything else but the following line here: const val VERSION = "0.0.1-DEV.SNAPSHOT"
git-ccs/src/commonMain/kotlin/de/fruiture/cor/ccs/CLI.kt
337591374
package de.fruiture.cor.ccs import VERSION import com.github.ajalt.clikt.core.CliktCommand import com.github.ajalt.clikt.core.NoOpCliktCommand import com.github.ajalt.clikt.core.ProgramResult import com.github.ajalt.clikt.core.subcommands import com.github.ajalt.clikt.parameters.groups.* import com.github.ajalt.clikt.parameters.options.* import com.github.ajalt.clikt.parameters.types.int import de.fruiture.cor.ccs.cc.Type import de.fruiture.cor.ccs.semver.ChangeType import de.fruiture.cor.ccs.semver.PreReleaseIndicator import de.fruiture.cor.ccs.semver.PreReleaseIndicator.Strategy.Companion.counter import de.fruiture.cor.ccs.semver.PreReleaseIndicator.Strategy.Companion.static import de.fruiture.cor.ccs.semver.Version.Companion.version private class MappingOptions : OptionGroup( name = "Version Bumping Options", help = "adjust which conventional commit types have which semantic version effect\n\n" + " - each option takes a list (comma-separated) of commit types,\n" + " - 'default' will match all other commit types,\n" + " - 'none' will match commits that are not valid conventional commits" ) { val noChangeTypes by option( "-n", "--none", help = "commit types that should trigger no version change, empty by default" ).convert { Type(it) }.split(",").default(emptyList()) val patchTypes by option( "-p", "--patch", help = "commit types that should trigger a patch level change, default: 'default', i.e." + "usually all commits trigger at least a patch level change" ).convert { Type(it) }.split(",").default(emptyList()) val minorTypes by option( "-m", "--minor", help = "commit types that should trigger a minor level change, by default: 'feat'" ).convert { Type(it) }.split(",").default(emptyList()) val majorTypes by option( "-M", "--major", help = "commit types that should trigger a major level change, empty by default" ).convert { Type(it) }.split(",").default(emptyList()) fun getMapping() = ChangeMapping() .add(ChangeType.NONE, noChangeTypes) .add(ChangeType.PATCH, patchTypes) .add(ChangeType.MINOR, minorTypes) .add(ChangeType.MAJOR, majorTypes) } private class LogOptions : OptionGroup() { val release by option( "-r", "--release", help = "only consider releases (ignore pre-releases)" ).flag() val target by option( "-t", "--target", help = "look for latest version before a given version (instead of HEAD)" ).convert { version(it) } } class CLI(app: CCSApplication) : NoOpCliktCommand( name = "git-ccs", help = "Conventional Commits & Semantic Versioning Utility for Git Repositories" ) { init { versionOption(VERSION) subcommands(object : NoOpCliktCommand( name = "next", help = "compute the next semantic version based on changes since the last version tag", ) { init { subcommands( object : CliktCommand( name = "release", help = "create a release version, e.g. 1.2.3" ) { val mappingOptions by MappingOptions() override fun run() { echo( app.getNextRelease(mappingOptions.getMapping()), trailingNewline = false ) } }, object : CliktCommand( name = "pre-release", help = "create a pre-release version, e.g. 1.2.3-RC.1" ) { val strategy by mutuallyExclusiveOptions( option( "-c", "--counter", help = "(default) add a numeric release candidate counter, e.g. 1.2.3-RC.3" ).flag().convert { counter() }, option( "-s", "--static", help = "just append a fixed pre-release identifier 'SNAPSHOT' (maven convention), e.g. 1.2.3-SNAPSHOT" ).flag().convert { static() }, option( "-f", "--format", help = "specify a pattern, like: RC.1.DEV, where 'RC.1' would become a counter and 'DEV' would be static" ).convert { PreReleaseIndicator.Strategy.deduct(it) } ).single().default(counter()) val mappingOptions by MappingOptions() override fun run() { echo( message = app.getNextPreRelease( strategy = strategy, changeMapping = mappingOptions.getMapping() ), trailingNewline = false ) } }) } }, object : CliktCommand( name = "log", help = "get commit log since last version as machine-friendly JSON representation" ) { val logOptions by LogOptions() override fun run() { echo( app.getChangeLogJson(release = logOptions.release, before = logOptions.target), trailingNewline = false ) } }, object : CliktCommand( name = "latest", help = "find the latest version (release or pre-release)" ) { val logOptions by LogOptions() override fun run() { val latestVersion = app.getLatestVersion(release = logOptions.release, before = logOptions.target) if (latestVersion != null) { echo(latestVersion, trailingNewline = false) } else { echo("no version found", err = true) throw ProgramResult(1) } } }, object : CliktCommand( name = "changes", help = "summarize changes (see `log`) as markdown document (changelog)" ) { val logOptions by LogOptions() val sections by option( "-s", "--section", help = "specify section headlines and their types, types can be comma-separated'\n\n" + "e.g. (default) -s 'Features=feat' -s 'Bugfixes=fix'" ).splitPair().convert { (hl, types) -> hl to types.split(',').map { Type(it) }.toSet() }.multiple().toMap() val breakingChanges by option( "-b", "--breaking-changes", help = "adjust the headline for the breaking changes section (default 'Breaking Changes')" ).default("Breaking Changes") val level by option( "-l", "--level", help = "level of headlines in markdown, default is 2: ## Headline" ).int().default(2).check(message = "must be in 1 .. 7") { it in 1..7 } override fun run() { val config = if (sections.isEmpty()) Sections.default() else Sections(sections) echo( app.getChangeLogMarkdown( release = logOptions.release, target = logOptions.target, sections = config.setBreakingChanges(breakingChanges), level = level ), trailingNewline = false ) } }) } }
git-ccs/src/commonMain/kotlin/de/fruiture/cor/ccs/ChangeMapping.kt
171597580
package de.fruiture.cor.ccs import de.fruiture.cor.ccs.cc.Type import de.fruiture.cor.ccs.git.GitCommit import de.fruiture.cor.ccs.semver.ChangeType val DEFAULT_COMMIT_TYPE = Type("default") val FEATURE_COMMIT_TYPE = Type("feat") val FIX_COMMIT_TYPE = Type("fix") data class ChangeMapping( private val types: Map<Type, ChangeType> = mapOf( FEATURE_COMMIT_TYPE to ChangeType.MINOR, FIX_COMMIT_TYPE to ChangeType.PATCH, DEFAULT_COMMIT_TYPE to ChangeType.PATCH ) ) { private val defaultChange = types[DEFAULT_COMMIT_TYPE]!! fun of(history: List<GitCommit>): ChangeType = history.maxOfOrNull(::of) ?: defaultChange fun of(commit: GitCommit) = if (commit.hasBreakingChange) ChangeType.MAJOR else of(commit.type) fun of(type: Type) = types.getOrElse(type) { defaultChange } operator fun plus(type: Pair<Type, ChangeType>) = copy(types = types + type) fun add(changeType: ChangeType, types: List<Type>) = copy(types = this.types + types.associateWith { changeType }) }
git-ccs/src/commonMain/kotlin/de/fruiture/cor/ccs/Sections.kt
1113246759
package de.fruiture.cor.ccs import de.fruiture.cor.ccs.cc.Type data class Sections( val config: Map<String, Set<Type>> = emptyMap(), val breakingChanges: String = "Breaking Changes" ) { interface TypeFilter { operator fun contains(type: Type): Boolean } companion object { fun default() = Sections( mapOf( "Features" to setOf(FEATURE_COMMIT_TYPE), "Bugfixes" to setOf(FIX_COMMIT_TYPE), "Other" to setOf(DEFAULT_COMMIT_TYPE), ) ) } private val allAssignedTypes = config.values.flatten().toSet() fun toFilter(set: Set<Type>): TypeFilter { val matchesDefault = set.contains(DEFAULT_COMMIT_TYPE) return object : TypeFilter { override fun contains(type: Type): Boolean { if (matchesDefault) { if (type !in allAssignedTypes) return true } return set.contains(type) } } } operator fun plus(mappings: Map<String, Set<Type>>): Sections { return copy(config = config + mappings) } inline fun forEach(function: (String, TypeFilter) -> Unit) { config.forEach { function(it.key, toFilter(it.value.toSet())) } } fun setBreakingChanges(headline: String) = copy(breakingChanges = headline) }
git-ccs/src/commonMain/kotlin/de/fruiture/cor/ccs/semver/Version.kt
3353056321
package de.fruiture.cor.ccs.semver import de.fruiture.cor.ccs.semver.Build.Companion.add import de.fruiture.cor.ccs.semver.Build.Companion.suffix import de.fruiture.cor.ccs.semver.NumericIdentifier.Companion.numeric import de.fruiture.cor.ccs.semver.PreReleaseIndicator.Strategy.Companion.counter enum class ChangeType { NONE, PATCH, MINOR, MAJOR } private fun Int.then(compare: () -> Int) = if (this == 0) compare() else this internal data class VersionCore( val major: NumericIdentifier, val minor: NumericIdentifier, val patch: NumericIdentifier ) : Comparable<VersionCore> { init { require((major.zero && minor.zero && patch.zero).not()) } companion object { fun of(major: Int, minor: Int, patch: Int) = VersionCore( NumericIdentifier(major), NumericIdentifier(minor), NumericIdentifier(patch) ) fun parse(string: String): VersionCore { val (ma, mi, pa) = string.split('.') return of(ma.toInt(), mi.toInt(), pa.toInt()) } } override fun compareTo(other: VersionCore) = major.compareTo(other.major) .then { minor.compareTo(other.minor) } .then { patch.compareTo(other.patch) } override fun toString() = "$major.$minor.$patch" fun bump(type: ChangeType) = when (type) { ChangeType.NONE -> this ChangeType.PATCH -> copy(patch = patch + 1) ChangeType.MINOR -> copy(minor = minor + 1, patch = 0.numeric) ChangeType.MAJOR -> copy(major = major + 1, minor = 0.numeric, patch = 0.numeric) } val type: ChangeType by lazy { if (patch.nonZero) ChangeType.PATCH else if (minor.nonZero) ChangeType.MINOR else if (major.nonZero) ChangeType.MAJOR else throw IllegalStateException("v0.0.0 is not defined") } } private val searchRegexp = Regex("\\d+\\.\\d+\\.\\d+(?:[-+.\\w]+)?") sealed class Version : Comparable<Version> { abstract val release: Release abstract val build: Build? internal abstract val core: VersionCore val type get() = core.type abstract fun build(suffix: String): Version abstract operator fun plus(preRelease: PreReleaseIndicator): PreRelease abstract operator fun plus(build: Build): Version abstract fun next(type: ChangeType): Release internal abstract fun nextPreRelease(strategy: PreReleaseIndicator.Strategy = counter()): PreRelease abstract fun nextPreRelease(type: ChangeType, strategy: PreReleaseIndicator.Strategy = counter()): PreRelease companion object { val initial = Release(VersionCore.of(0, 0, 1)) val stable = Release(VersionCore.of(1, 0, 0)) fun version(string: String): Version { val (prefix, build) = string.indexOf('+').let { if (it == -1) string to null else { val prefix = string.substring(0, it) val buildSuffix = string.substring(it + 1) val build = Build.build(buildSuffix) prefix to build } } val hyphen = prefix.indexOf('-') return if (hyphen == -1) Release(VersionCore.parse(prefix), build) else { PreRelease( VersionCore.parse(prefix.substring(0, hyphen)), PreReleaseIndicator.preRelease(prefix.substring(hyphen + 1)), build ) } } fun extractVersion(string: String) = searchRegexp.find(string)?.let { match -> runCatching { version(match.value) }.getOrNull() } } } data class PreRelease internal constructor( override val core: VersionCore, val pre: PreReleaseIndicator, override val build: Build? = null ) : Version() { override val release = Release(core) override fun compareTo(other: Version): Int { return when (other) { is PreRelease -> core.compareTo(other.core) .then { pre.compareTo(other.pre) } is Release -> core.compareTo(other.core).then { -1 } } } override fun toString() = "$core-$pre${build.suffix}" override fun build(suffix: String) = copy(build = Build.build(suffix)) override fun plus(preRelease: PreReleaseIndicator) = copy(pre = pre + preRelease) override fun plus(build: Build) = copy(build = this.build add build) override fun nextPreRelease(strategy: PreReleaseIndicator.Strategy) = copy(pre = strategy.next(pre), build = null) override fun next(type: ChangeType): Release { val changeToHere = release.type return if (changeToHere >= type) release else release.next(type) } override fun nextPreRelease(type: ChangeType, strategy: PreReleaseIndicator.Strategy): PreRelease { val changeToHere = release.type return if (changeToHere >= type) nextPreRelease(strategy) else release.next(type).nextPreRelease(strategy) } } data class Release internal constructor(override val core: VersionCore, override val build: Build? = null) : Version() { override val release = this override fun compareTo(other: Version): Int { return when (other) { is PreRelease -> -other.compareTo(this) is Release -> core.compareTo(other.core) } } override fun toString() = "$core${build.suffix}" fun preRelease(suffix: String) = plus(PreReleaseIndicator.preRelease(suffix)) override fun build(suffix: String) = copy(build = Build.build(suffix)) override fun plus(preRelease: PreReleaseIndicator) = PreRelease(core, preRelease, build) override fun plus(build: Build) = copy(build = this.build add build) override fun next(type: ChangeType) = Release(core.bump(type)) override fun nextPreRelease(strategy: PreReleaseIndicator.Strategy) = PreRelease(core, strategy.start()) override fun nextPreRelease(type: ChangeType, strategy: PreReleaseIndicator.Strategy) = next(type).nextPreRelease(strategy) }
git-ccs/src/commonMain/kotlin/de/fruiture/cor/ccs/semver/PreReleaseIndicator.kt
2464811486
package de.fruiture.cor.ccs.semver import de.fruiture.cor.ccs.semver.AlphaNumericIdentifier.Companion.alphanumeric import de.fruiture.cor.ccs.semver.NumericIdentifier.Companion.numeric import de.fruiture.cor.ccs.semver.PreReleaseIdentifier.Companion.identifier sealed class PreReleaseIdentifier : Comparable<PreReleaseIdentifier> { data class AlphaNumeric(val identifier: AlphaNumericIdentifier) : PreReleaseIdentifier() { override fun compareTo(other: PreReleaseIdentifier) = when (other) { is AlphaNumeric -> identifier.compareTo(other.identifier) is Numeric -> 1 } override fun toString() = identifier.toString() } data class Numeric(val identifier: NumericIdentifier) : PreReleaseIdentifier() { override fun compareTo(other: PreReleaseIdentifier) = when (other) { is Numeric -> identifier.compareTo(other.identifier) is AlphaNumeric -> -1 } override fun toString() = identifier.toString() fun bump() = Numeric(identifier + 1) } companion object { fun identifier(identifier: AlphaNumericIdentifier) = AlphaNumeric(identifier) fun identifier(identifier: NumericIdentifier) = Numeric(identifier) fun identifier(string: String) = if (string.all { it.digit }) identifier(NumericIdentifier(string.toInt())) else identifier(AlphaNumericIdentifier(string)) } } data class PreReleaseIndicator(val identifiers: List<PreReleaseIdentifier>) : Comparable<PreReleaseIndicator> { init { require(identifiers.isNotEmpty()) { "at least one identifier required" } } override fun compareTo(other: PreReleaseIndicator): Int { return identifiers.asSequence().zip(other.identifiers.asSequence()) { a, b -> a.compareTo(b) }.firstOrNull { it != 0 } ?: identifiers.size.compareTo(other.identifiers.size) } override fun toString() = identifiers.joinToString(".") operator fun plus(other: PreReleaseIndicator) = PreReleaseIndicator(this.identifiers + other.identifiers) companion object { fun of(vararg identifiers: PreReleaseIdentifier) = PreReleaseIndicator(listOf(*identifiers)) fun preRelease(string: String): PreReleaseIndicator = PreReleaseIndicator(string.split('.').map { identifier(it) }) } interface Strategy { fun next(indicator: PreReleaseIndicator): PreReleaseIndicator fun start(): PreReleaseIndicator companion object { val DEFAULT_STATIC = "SNAPSHOT".alphanumeric val DEFAULT_COUNTER = "RC".alphanumeric fun counter(identifier: AlphaNumericIdentifier = DEFAULT_COUNTER): Strategy = CounterStrategy(identifier) private data class CounterStrategy(val identifier: AlphaNumericIdentifier) : Strategy { override fun next(indicator: PreReleaseIndicator) = indicator.bumpCounter(identifier(identifier)) override fun start() = of(identifier(identifier), identifier(1.numeric)) } private fun PreReleaseIndicator.bumpCounter(identifier: PreReleaseIdentifier): PreReleaseIndicator { val replaced = sequence { var i = 0 var found = false while (i < identifiers.size) { val k = identifiers[i] if (k == identifier) { found = true if (i + 1 < identifiers.size) { val v = identifiers[i + 1] if (v is PreReleaseIdentifier.Numeric) { yield(k) yield(v.bump()) i += 2 continue } } yield(k) yield(PreReleaseIdentifier.Numeric(2.numeric)) i += 1 continue } yield(k) i += 1 continue } if (!found) { yield(identifier) yield(identifier(1.numeric)) } }.toList() return copy(identifiers = replaced) } fun static(identifier: AlphaNumericIdentifier = DEFAULT_STATIC): Strategy = Static(identifier) private data class Static(val identifier: AlphaNumericIdentifier) : Strategy { override fun next(indicator: PreReleaseIndicator) = identifier(identifier).let { if (it in indicator.identifiers) indicator else indicator + of(it) } override fun start() = of(identifier(identifier)) } operator fun Strategy.plus(then: Strategy): Strategy = Combined(this, then) fun deduct(spec: String): Strategy { val identifiers = preRelease(spec).identifiers return sequence { var i = 0 while (i < identifiers.size) { val k = identifiers[i] if (k is PreReleaseIdentifier.AlphaNumeric) { if (i + 1 < identifiers.size) { val v = identifiers[i + 1] if (v is PreReleaseIdentifier.Numeric) { this.yield(counter(k.identifier)) i += 2 continue } } this.yield(static(k.identifier)) } i++ } }.reduce { a, b -> a + b } } private data class Combined(val first: Strategy, val second: Strategy) : Strategy { override fun next(indicator: PreReleaseIndicator): PreReleaseIndicator { return indicator.let(first::next).let(second::next) } override fun start(): PreReleaseIndicator { return first.start().let(second::next) } } } } }
git-ccs/src/commonMain/kotlin/de/fruiture/cor/ccs/semver/Build.kt
3429490097
package de.fruiture.cor.ccs.semver sealed class BuildIdentifier { data class AlphaNumeric(val identifier: AlphaNumericIdentifier) : BuildIdentifier() { override fun toString() = identifier.toString() } data class Digits(val digits: DigitIdentifier) : BuildIdentifier() { override fun toString() = digits.toString() } companion object { fun identifier(identifier: AlphaNumericIdentifier) = AlphaNumeric(identifier) fun identifier(digits: DigitIdentifier) = Digits(digits) fun identifier(string: String) = if (string.all { it.digit }) identifier(DigitIdentifier(string)) else identifier(AlphaNumericIdentifier(string)) } } data class Build(val identifiers: List<BuildIdentifier>) { init { require(identifiers.isNotEmpty()) } override fun toString() = identifiers.joinToString(".") operator fun plus(build: Build): Build = Build(identifiers + build.identifiers) companion object { fun build(suffix: String) = Build(suffix.split('.').map(BuildIdentifier.Companion::identifier)) val Build?.suffix get() = this?.let { "+$it" } ?: "" infix fun Build?.add(build: Build) = this?.let { it + build } ?: build } }
git-ccs/src/commonMain/kotlin/de/fruiture/cor/ccs/semver/Identifiers.kt
2120321050
package de.fruiture.cor.ccs.semver import kotlin.jvm.JvmInline private const val LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" private const val NON_DIGITS = "-$LETTERS" private const val POSITIVE_DIGITS = "123456789" private const val DIGITS = "0$POSITIVE_DIGITS" private const val IDENTIFIER_CHARACTERS = "$NON_DIGITS$DIGITS" internal val Char.digit get() = this in DIGITS internal val Char.nonDigit get() = this in NON_DIGITS internal val Char.identifier get() = this in IDENTIFIER_CHARACTERS @JvmInline value class AlphaNumericIdentifier(private val value: String) : Comparable<AlphaNumericIdentifier> { init { require(value.isNotEmpty()) { "identifier cannot be empty" } require(value.all { it.identifier }) { "identifier '$value' must only contain: $IDENTIFIER_CHARACTERS" } require(value.any { it.nonDigit }) { "identifier '$value' must contain at leas one non-digit" } } override fun compareTo(other: AlphaNumericIdentifier) = value.compareTo(other.value) override fun toString() = value companion object { val String.alphanumeric get() = AlphaNumericIdentifier(this) } } @JvmInline value class NumericIdentifier(private val value: Int) : Comparable<NumericIdentifier> { init { require(value >= 0) { "numeric identifier must be positive integer" } } override fun compareTo(other: NumericIdentifier) = value.compareTo(other.value) override fun toString() = value.toString() operator fun plus(i: Int): NumericIdentifier { require(i >= 0) return NumericIdentifier(value + i) } val zero get() = value == 0 val nonZero get() = !zero companion object { val Int.numeric get() = NumericIdentifier(this) } } @JvmInline value class DigitIdentifier(private val value: String) { init { require(value.isNotEmpty()) { "identifier cannot be empty" } require(value.all { it.digit }) { "identifier '$value' must only contain digits" } } override fun toString() = value companion object { val String.digits get() = DigitIdentifier(this) } }
git-ccs/src/commonMain/kotlin/de/fruiture/cor/ccs/CCSApplication.kt
922663514
package de.fruiture.cor.ccs import de.fruiture.cor.ccs.git.* import de.fruiture.cor.ccs.semver.PreRelease import de.fruiture.cor.ccs.semver.PreReleaseIndicator.Strategy import de.fruiture.cor.ccs.semver.Release import de.fruiture.cor.ccs.semver.Version import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json class CCSApplication( private val git: Git ) { private fun getChangeType(latestVersion: VersionTag, mapping: ChangeMapping) = mapping.of(git.getLogX(latestVersion.tag)) fun getNextRelease(changeMapping: ChangeMapping = ChangeMapping()): Release { val latestVersion = git.getLatestVersionTag() ?: return Version.initial val changeType = getChangeType(latestVersion, changeMapping) return latestVersion.version.next(changeType) } fun getNextPreRelease(strategy: Strategy, changeMapping: ChangeMapping = ChangeMapping()): PreRelease { val latestVersion = git.getLatestVersionTag() ?: return initialPreRelease(strategy) val changeType = getChangeType(latestVersion, changeMapping) return latestVersion.version.nextPreRelease(changeType, strategy) } private fun initialPreRelease(strategy: Strategy) = Version.initial + strategy.start() @OptIn(ExperimentalSerializationApi::class) private val json = Json { explicitNulls = false } fun getChangeLogJson(release: Boolean = false, before: Version? = null): String { val commits = getChanges(release, before) return json.encodeToString(commits) } private fun getChanges(release: Boolean, before: Version? = null): List<GitCommit> { val from = getLatest(release, optionalFilterBefore(before)) val to = if (before == null) null else getLatest(false, until(before)) return git.getLogX(from = from?.tag, to = to?.tag) } fun getLatestVersion(release: Boolean = false, before: Version? = null): String? = getLatest(release, optionalFilterBefore(before))?.version?.toString() private fun optionalFilterBefore(before: Version?) = if (before == null) any else before(before) private fun getLatest(release: Boolean, filter: VersionFilter): VersionTag? { return if (release) git.getLatestReleaseTag(filter) else git.getLatestVersionTag(filter) } fun getChangeLogMarkdown( release: Boolean = false, target: Version? = null, sections: Sections = Sections.default(), level: Int = 2 ) = sequence { val hl = "#".repeat(level) val commits = getChanges(release, target).map { it.conventional } val breakingChanges = commits.mapNotNull { it.breakingChange } if (breakingChanges.isNotEmpty()) { yield("$hl ${sections.breakingChanges}\n") breakingChanges.forEach { yield("* $it") } yield("") } sections.forEach { headline, types -> val selectedCommits = commits.filter { it.type in types } if (selectedCommits.isNotEmpty()) { yield("$hl $headline\n") selectedCommits.forEach { yield("* ${it.description}") } yield("") } } }.joinToString("\n") }
git-ccs/src/commonMain/kotlin/de/fruiture/cor/ccs/cc/ConventionalCommitMessage.kt
302653052
package de.fruiture.cor.ccs.cc import de.fruiture.cor.ccs.cc.Scope.Companion.suffix import kotlinx.serialization.* import kotlinx.serialization.builtins.MapSerializer import kotlinx.serialization.builtins.serializer import kotlinx.serialization.descriptors.mapSerialDescriptor import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder import kotlin.jvm.JvmInline @JvmInline @Serializable value class Type(private val value: String) { init { require(value.isNotBlank()) } override fun toString() = value } @JvmInline @Serializable value class Description(val value: String) { init { require(value.isNotBlank()) } override fun toString() = value } @JvmInline @Serializable value class Body(private val value: String) { constructor(paragraphs: List<String>) : this(paragraphs.joinToString("\n\n")) init { require(value.isNotBlank()) } override fun toString() = value } sealed class Footer { abstract val key: String abstract val value: String override fun toString() = "$key: $value" } data class GenericFooter(override val key: String, override val value: String) : Footer() { init { require(key.none { it.isWhitespace() }) require(value.isNotBlank()) } override fun toString() = super.toString() } private val VALID_KEYS = listOf("BREAKING CHANGE", "BREAKING-CHANGE") private val DEFAULT_KEY = VALID_KEYS.first() @Serializable data class BreakingChange(override val key: String, override val value: String) : Footer() { constructor(value: String) : this(DEFAULT_KEY, value) init { require(key in VALID_KEYS) require(value.isNotBlank()) } override fun toString() = super.toString() } @JvmInline @Serializable value class Scope(private val value: String) { init { require(value.isNotBlank()) } override fun toString() = value companion object { val Scope?.suffix get() = if (this == null) "" else "($this)" } } @OptIn(ExperimentalSerializationApi::class) @Serializable data class ConventionalCommitMessage( val type: Type, val description: Description, val scope: Scope? = null, val body: Body? = null, val footers: @Serializable(with = FootersSerializer::class) List<@Contextual Footer> = emptyList(), val headlineBreakingChange: Boolean = false ) { private val exclamation: String get() = if (headlineBreakingChange) "!" else "" private val effectiveBreakingChange: BreakingChange? = if (headlineBreakingChange) BreakingChange(description.value) else footers.filterIsInstance<BreakingChange>().firstOrNull() @EncodeDefault val breakingChange = effectiveBreakingChange?.value val hasBreakingChange: Boolean = breakingChange != null companion object { fun message(text: String): ConventionalCommitMessage { val paragraphs = text.split(Regex("\\n\\n")).map(String::trim).filter(String::isNotEmpty) val headline = headline(paragraphs.first()) val tail = paragraphs.drop(1) return if (tail.isNotEmpty()) { val footers = footers(tail.last()) if (footers.isNotEmpty()) { val body = tail.dropLast(1) if (body.isNotEmpty()) headline + Body(body) + footers else headline + footers } else { headline + Body(tail) } } else { headline } } private fun headline(headline: String): ConventionalCommitMessage { return Regex("(\\w+)(?:\\((\\w+)\\))?(!)?: (.+)") .matchEntire(headline)?.destructured?.let { (type, scope, excl, description) -> return ConventionalCommitMessage( type = Type(type), description = Description(description), scope = if (scope.isNotEmpty()) Scope(scope) else null, headlineBreakingChange = excl.isNotEmpty() ) } ?: throw IllegalArgumentException("no valid headline: '$headline‘") } private fun footers(paragraph: String) = Regex("^([\\S-]+|BREAKING CHANGE): (.+?)$", RegexOption.MULTILINE).findAll(paragraph) .map { it.destructured } .map { (k, v) -> footer(k, v) } .toList() private fun footer(k: String, v: String) = if (k == "BREAKING CHANGE" || k == "BREAKING-CHANGE") BreakingChange(k, v) else GenericFooter(k, v) object FootersSerializer : KSerializer<List<Footer>> { override val descriptor = mapSerialDescriptor<String, String>() private val mapSerializer = MapSerializer(String.serializer(), String.serializer()) override fun deserialize(decoder: Decoder): List<Footer> { return decoder.decodeSerializableValue(mapSerializer) .map { (k, v) -> footer(k, v) } } override fun serialize(encoder: Encoder, value: List<Footer>) { return encoder.encodeSerializableValue(mapSerializer, value.associate { it.key to it.value }) } } } private operator fun plus(footers: List<Footer>) = copy(footers = this.footers + footers) private operator fun plus(body: Body) = copy(body = body) override fun toString(): String { val out = StringBuilder() out.append(headline()) body?.let { out.appendLine() out.appendLine() out.append(it) } if (footers.isNotEmpty()) { out.appendLine() out.appendLine() out.append(footers.joinToString("\n")) } return out.toString() } private fun headline() = "$type${scope.suffix}$exclamation: $description" }
git-ccs/src/commonMain/kotlin/de/fruiture/cor/ccs/git/KommandSystemCaller.kt
355279750
package de.fruiture.cor.ccs.git import com.kgit2.kommand.process.Command import com.kgit2.kommand.process.Stdio class KommandSystemCaller : SystemCaller { override fun call(command: String, arguments: List<String>): SystemCallResult { val child = Command(command) .args(arguments) .stdout(Stdio.Pipe) .stderr(Stdio.Pipe) .spawn() val code = child.wait() return SystemCallResult( code = code, stdout = child.bufferedStdout()?.lines()?.toList() ?: emptyList(), stderr = child.bufferedStderr()?.lines()?.toList() ?: emptyList() ) } }
git-ccs/src/commonMain/kotlin/de/fruiture/cor/ccs/git/Git.kt
3498903309
package de.fruiture.cor.ccs.git import de.fruiture.cor.ccs.semver.Release import de.fruiture.cor.ccs.semver.Version import kotlin.jvm.JvmInline const val RECORD_SEPARATOR = '\u001e' typealias VersionFilter = (Version) -> Boolean val any: VersionFilter = { true } @JvmInline private value class BeforeFilter(val maxExclusive: Version) : VersionFilter { override fun invoke(it: Version) = it < maxExclusive } fun before(maxExclusive: Version): VersionFilter = BeforeFilter(maxExclusive) @JvmInline private value class UntilFilter(val maxInclusive: Version) : VersionFilter { override fun invoke(it: Version) = it <= maxInclusive } fun until(maxInclusive: Version): VersionFilter = UntilFilter(maxInclusive) class Git(private val sys: SystemCaller) { fun getLatestVersionTag(filter: VersionFilter = any): VersionTag? { return getAllVersionTags(filter).maxOrNull() } fun getLatestReleaseTag(filter: VersionFilter = any): VersionTag? { return getAllVersionTags(filter).filter { it.version is Release }.maxOrNull() } private fun getAllVersionTags(filter: VersionFilter): List<VersionTag> { val tagFilter = { tag: VersionTag -> filter(tag.version) } return git( listOf( "for-each-ref", "--merged", "HEAD", "--sort=-committerdate", "--format=%(refname:short)", "refs/tags/*.*.*" ) ).mapNotNull { VersionTag.versionTag(it) }.filter(tagFilter) } fun getLogX(from: TagName? = null, to: TagName? = null): List<GitCommit> { val end = to?.toString() ?: "HEAD" val arguments = listOf("log", "--format=format:%H %aI%n%B%n%x1E", from?.let { "$it..$end" } ?: end ) val result = git(arguments) return result.joinToString("\n").split(RECORD_SEPARATOR).map(String::trim).mapNotNull { Regex("^(\\S+) (\\S+)\\n").matchAt(it, 0)?.let { match -> val (hash, date) = match.destructured GitCommit( hash = hash, date = ZonedDateTime(date), message = it.substring(match.range.last + 1) ) } } } private fun git(arguments: List<String>, success: (SystemCallResult) -> Boolean = { it.code == 0 }): List<String> { val result = sys.call("git", arguments) if (success(result)) { return result.stdout } else { throw RuntimeException("unexpected result from system call (git $arguments): $result") } } }
git-ccs/src/commonMain/kotlin/de/fruiture/cor/ccs/git/GitCommit.kt
1354227209
package de.fruiture.cor.ccs.git import de.fruiture.cor.ccs.cc.Body import de.fruiture.cor.ccs.cc.ConventionalCommitMessage import de.fruiture.cor.ccs.cc.Description import de.fruiture.cor.ccs.cc.Type import de.fruiture.cor.ccs.semver.Version import kotlinx.serialization.EncodeDefault import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.Serializable import kotlin.jvm.JvmInline @JvmInline @Serializable value class ZonedDateTime(private val iso8601: String) { override fun toString() = iso8601 } val NON_CONVENTIONAL_COMMIT_TYPE = Type("none") @Serializable data class GitCommit( val hash: String, val date: ZonedDateTime, val message: String ) { @OptIn(ExperimentalSerializationApi::class) @EncodeDefault val conventional = runCatching { ConventionalCommitMessage.message(message) }.getOrElse { val lines = message.lines() val bodyText = lines.dropLast(1).joinToString("\n").trim() ConventionalCommitMessage( type = NON_CONVENTIONAL_COMMIT_TYPE, description = Description(lines.first()), body = if (bodyText.isNotBlank()) Body(bodyText) else null ) } val type = conventional.type val hasBreakingChange = conventional.hasBreakingChange } @JvmInline value class TagName(val value: String) { override fun toString() = value } data class VersionTag(val tag: TagName, val version: Version) : Comparable<VersionTag> { init { require(tag.value.contains(version.toString())) { "tag '$tag' does not contain version number '$version'" } } override fun compareTo(other: VersionTag) = version.compareTo(other.version) override fun toString() = tag.toString() companion object { fun versionTag(tagName: String) = Version.extractVersion(tagName)?.let { VersionTag(TagName(tagName), it) } } }
git-ccs/src/commonMain/kotlin/de/fruiture/cor/ccs/git/SystemCaller.kt
3201990921
package de.fruiture.cor.ccs.git interface SystemCaller { fun call(command: String, arguments: List<String> = emptyList()): SystemCallResult } data class SystemCallResult( val code: Int, val stdout: List<String> = emptyList(), val stderr: List<String> = emptyList() )
TugasPPB/app/src/androidTest/java/com/example/aplikasiteman/ExampleInstrumentedTest.kt
3728867410
package com.example.aplikasiteman import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.aplikasiteman", appContext.packageName) } }
TugasPPB/app/src/test/java/com/example/aplikasiteman/ExampleUnitTest.kt
1128709288
package com.example.aplikasiteman import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
TugasPPB/app/src/main/java/com/example/aplikasiteman/MainActivity.kt
1469467048
package com.example.aplikasiteman import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.text.TextUtils import android.view.View import android.widget.Toast import com.example.aplikasiteman.databinding.ActivityMainBinding import com.firebase.ui.auth.AuthUI import com.google.android.gms.tasks.OnCompleteListener import com.google.android.gms.tasks.Task import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.DatabaseReference import com.google.firebase.database.FirebaseDatabase class MainActivity : AppCompatActivity(), View.OnClickListener { private var auth:FirebaseAuth? = null private val RC_SIGN_IN = 1 private lateinit var binding : ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) //inisiasi ID (button) binding.logout.setOnClickListener(this) binding.save.setOnClickListener(this) binding.showData.setOnClickListener(this) //mendapatkan Instance Firebase Autentikasi auth = FirebaseAuth.getInstance() } private fun isEmpty(s: String): Boolean { return TextUtils.isEmpty(s) } override fun onClick(p0: View?) { when (p0?.getId()) { R.id.save -> { //Mendapatkan UserID dari pengguna yang terauth val getUserID = auth!!.currentUser!!.uid //Mendapatkan instance dari Database val database = FirebaseDatabase.getInstance() //Mendapatkan Data yang diinputkan User ke dalam variabel val getNama: String = binding.nama.getText().toString() val getAlamat: String = binding.alamat.getText().toString() val getNoHP: String = binding.noHp.getText().toString() //Mendapatkan referensi dari database val getReference: DatabaseReference getReference = database.reference //mengecek apakah ada data yang kosong if (isEmpty(getNama) || isEmpty(getAlamat) || isEmpty(getNoHP)) { //Jika ada, maka akan menampilkan pesan singkat seperti berikut Toast.makeText( this@MainActivity, "Data tidak boleh ada yang kosong", Toast.LENGTH_SHORT).show() } else { //Jika tidak ada, maka menyimpan ke databse sesuai ID masing-masing akun getReference.child("Admin").child(getUserID).child("DataTeman").push() .setValue(data_teman(getNama, getAlamat, getNoHP)) .addOnCompleteListener(this) { //bagian isi terjadi ketika user berhasil menyimpan data binding.nama.setText("") binding.alamat.setText("") binding.noHp.setText("") Toast.makeText(this@MainActivity, "Data Tersimpan", Toast.LENGTH_SHORT).show() } } } R.id.logout -> { AuthUI.getInstance().signOut(this) .addOnCompleteListener(object : OnCompleteListener<Void> { override fun onComplete(p0: Task<Void>) { Toast.makeText(this@MainActivity, "Logout Berhasil", Toast.LENGTH_SHORT).show() intent = Intent(applicationContext, LoginActivity::class.java) startActivity(intent) finish() } }) } R.id.show_data -> { startActivity(Intent(this@MainActivity, MyListData::class.java)) } } } }
TugasPPB/app/src/main/java/com/example/aplikasiteman/UpdateData.kt
505561647
package com.example.aplikasiteman import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.text.TextUtils import android.view.View import android.widget.Toast import com.example.aplikasiteman.databinding.ActivityUpdateDataBinding import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.DatabaseReference import com.google.firebase.database.FirebaseDatabase class UpdateData : AppCompatActivity() { //deklarasikan variabel private var database: DatabaseReference? = null private var auth: FirebaseAuth? = null private var cekNama: String? = null private var cekAlamat: String? = null private var cekNoHP: String? = null private lateinit var binding: ActivityUpdateDataBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityUpdateDataBinding.inflate(layoutInflater) setContentView(binding.root) supportActionBar?.title = "Update Data" //mendapatkan instance otentikasi dan refrensi dari DB auth = FirebaseAuth.getInstance() database = FirebaseDatabase.getInstance().reference data // memanggil method data binding.update.setOnClickListener { //mendapatkan data teman yang akan dicek cekNama = binding.newNama.text.toString() cekAlamat = binding.newAlamat.text.toString() cekNoHP = binding.newNohp.text.toString() //mengecek agar tidak ada yang kosong if ( isEmpty(cekNama!!) || isEmpty(cekAlamat!!) || isEmpty(cekNoHP!!)) { Toast.makeText(this@UpdateData, "Data tidak boleh kosong", Toast.LENGTH_SHORT).show() } else { //menjalankan update data val setTeman = data_teman() setTeman.nama = binding.newNama.text.toString() setTeman.alamat = binding.newAlamat.text.toString() setTeman.no_hp = binding.newNohp.text.toString() updateTeman(setTeman) } } } //mengecek apakah ada data kosong private fun isEmpty(s: String): Boolean { return TextUtils.isEmpty(s) } //menampilkan data yang akan diupdate private val data: Unit private get() { //menampilkan data dari item yang sudah dipilih val getNama = intent.getStringExtra("dataNama") val getAlamat = intent.getStringExtra("dataAlamat") val getNoHP = intent.getStringExtra("dataNoHP") binding.newNama.setText(getNama) binding.newAlamat.setText(getAlamat) binding.newNohp.setText(getNoHP) } //proses update private fun updateTeman(teman: data_teman) { val userID = auth!!.uid val getKey = intent.getStringExtra("getPrimaryKey") database!!.child("Admin") .child(userID!!) .child("DataTeman") .child(getKey!!) .setValue(teman) .addOnSuccessListener { binding.newNama.setText("") binding.newAlamat.setText("") binding.newNohp.setText("") Toast.makeText(this@UpdateData, "Data berhasil diupdate", Toast.LENGTH_SHORT).show() finish() } } }
TugasPPB/app/src/main/java/com/example/aplikasiteman/data_teman.kt
3508904898
package com.example.aplikasiteman class data_teman { //deklarasi variabel var nama : String? = null var alamat : String? = null var no_hp : String? = null var key : String? = null //Membuat constructor kosong untuk membaca data snapshot constructor() {} //Konstruktor dengan beberapa parameter, untuk mendapatkan Input Data dari User constructor(nama: String?, alamat: String?, no_hp: String?) { this.nama = nama this.alamat = alamat this.no_hp = no_hp } }
TugasPPB/app/src/main/java/com/example/aplikasiteman/MyListData.kt
3448120670
package com.example.aplikasiteman import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.widget.Toast import androidx.core.content.ContextCompat import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.aplikasiteman.databinding.ActivityMyListDataBinding import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.ValueEventListener class MyListData : AppCompatActivity() { //deklarasikan variabel ubtuk RC private var recyclerView : RecyclerView? = null private var adapter: RecyclerView.Adapter<*>? = null private var layoutManager: RecyclerView.LayoutManager? = null //deklarasi variabel DB Refrence & Arraylist dengan parameter ClassModel val database = FirebaseDatabase.getInstance() private var DataTeman = ArrayList<data_teman>() private var auth: FirebaseAuth? = null private lateinit var binding: ActivityMyListDataBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMyListDataBinding.inflate(layoutInflater) setContentView(binding.root) recyclerView = findViewById(R.id.datalist) setSupportActionBar(findViewById(R.id.my_toolbar)) supportActionBar!!.title = "Data Teman" auth = FirebaseAuth.getInstance() MyRecyclerView() GetData() } //kode untuk mengambil data databse & menamplikan ke dalam adapter private fun GetData(){ Toast.makeText(applicationContext, "Mohon tunggu sebentar...", Toast.LENGTH_LONG).show() val getUserID: String = auth?.getCurrentUser()?.getUid().toString() val getReference = database.getReference() getReference.child("Admin").child(getUserID).child("DataTeman") .addValueEventListener(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { if (dataSnapshot.exists()){ DataTeman.clear() for (snapshot in dataSnapshot.children) { //mapping data pada DataSnapshot ke dalam objek DataTeman val teman = snapshot.getValue(data_teman::class.java) //mengambil Primaary Key untuk proses update/delete teman?.key = snapshot.key DataTeman.add(teman!!) } //Inisialisasi adapter dan data teman dalam bentuk array adapter = RecyclerViewAdapter(DataTeman, this@MyListData) //memasang adapter pada RC recyclerView?.adapter = adapter (adapter as RecyclerViewAdapter).notifyDataSetChanged() Toast.makeText(applicationContext, "Data berhasil dimuat", Toast.LENGTH_LONG).show() } } override fun onCancelled(databaseError: DatabaseError) { //kode ini dijalankan ketika error, disimpan ke logcat Toast.makeText(applicationContext, "Data Gagal dimuat", Toast.LENGTH_LONG).show() Log.e("MyListActivity", databaseError.details +" "+ databaseError.message) } }) } //baris kode untuk mengatur RC private fun MyRecyclerView(){ layoutManager = LinearLayoutManager(this) recyclerView?.layoutManager = layoutManager recyclerView?.setHasFixedSize(true) //buat garis bawah setiap item data val itemDecoration = DividerItemDecoration(applicationContext, DividerItemDecoration.VERTICAL) itemDecoration.setDrawable(ContextCompat.getDrawable(applicationContext, R.drawable.line)!!) recyclerView?.addItemDecoration(itemDecoration) } }
TugasPPB/app/src/main/java/com/example/aplikasiteman/RecyclerViewAdapter.kt
2350423717
package com.example.aplikasiteman import android.annotation.SuppressLint import android.app.AlertDialog import android.app.LauncherActivity.ListItem import android.content.Context import android.content.DialogInterface import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.FirebaseDatabase class RecyclerViewAdapter (private val DataTeman: ArrayList<data_teman>, context: Context) : RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> () { private val context: Context //view holder digunakan untuk menyimpan referensi daro view-view inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val Nama: TextView val Alamat: TextView val NoHP: TextView val ListItem: LinearLayout //meninisialisasi view yang terpasang pada layout RecyclerView init { Nama = itemView.findViewById(R.id.namax) Alamat = itemView.findViewById(R.id.alamatx) NoHP = itemView.findViewById(R.id.no_hpx) ListItem = itemView.findViewById(R.id.list_item) } } init { this.context = context } //membuat view untuk menyiapkan dan memasang layout yg digunakan pada RecyclerView override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val V: View = LayoutInflater.from(parent.getContext()).inflate( R.layout.view_design, parent, false ) return ViewHolder(V) } @SuppressLint("SetTextI18n") override fun onBindViewHolder(holder: ViewHolder, @SuppressLint("RecyclerView") position: Int) { val Nama: String? = DataTeman.get(position).nama val Alamat: String? = DataTeman.get(position).alamat val NoHP: String? = DataTeman.get(position).no_hp //masukkan nilai atau value ke dalam view holder.Nama.text = "Nama: $Nama" holder.Alamat.text = "Alamat: $Alamat" holder.NoHP.text = "No Handphone: $NoHP" //membuat fungsi edit dan delete holder.ListItem.setOnLongClickListener { view -> val action = arrayOf("Update", "Delete") val alertDialogBuilder= AlertDialog.Builder(view.context) alertDialogBuilder.setItems(action) { dialog, i -> when (i) { 0 -> { //berpindah ke halaman update val bundle = Bundle().apply { putString("dataNama", DataTeman[position].nama) putString("dataAlamat", DataTeman[position].nama) putString("dataNoHP", DataTeman[position].no_hp) putString("getPrimaryKey", DataTeman[position].key) } val intent = Intent(view.context, UpdateData::class.java).apply { putExtras(bundle) } context.startActivity(intent) } 1 -> { deleteData(position) } } } alertDialogBuilder.create().show() true } } //menghitung Ukuran/jumlah Data yng akan ditampilkan pada RC override fun getItemCount(): Int { return DataTeman.size } private fun deleteData(position: Int) { val database = FirebaseDatabase.getInstance().reference val userID = FirebaseAuth.getInstance().currentUser?.uid val key = DataTeman[position].key if (userID != null && key != null) { database.child("Admin").child(userID).child("DataTeman").child(key) .removeValue() } } }
TugasPPB/app/src/main/java/com/example/aplikasiteman/LoginActivity.kt
3903512873
package com.example.aplikasiteman import android.app.Activity import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Toast import com.example.aplikasiteman.databinding.ActivityLoginBinding import com.firebase.ui.auth.AuthUI import com.firebase.ui.auth.IdpResponse import com.google.firebase.auth.FirebaseAuth class LoginActivity : AppCompatActivity(), View.OnClickListener { private var auth: FirebaseAuth? = null private val RC_SIGN_IN = 1 private lateinit var binding : ActivityLoginBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityLoginBinding.inflate(layoutInflater) setContentView(binding.root) binding.progress.visibility = View.GONE binding.login.setOnClickListener(this) auth = FirebaseAuth.getInstance() if (auth!!.currentUser == null) { } else { intent = Intent(applicationContext, MainActivity::class.java) startActivity(intent) finish() } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == RC_SIGN_IN) { val response = IdpResponse.fromResultIntent(data) if (resultCode == Activity.RESULT_OK) { val user = FirebaseAuth.getInstance().currentUser Toast.makeText(this, "Login Berhasil", Toast.LENGTH_SHORT).show() startActivity(intent) finish() } else { Toast.makeText(this, "Login Dibatalkan", Toast.LENGTH_SHORT).show() } } } override fun onClick(v: View?) { val provider = arrayListOf(AuthUI.IdpConfig.GoogleBuilder().build()) startActivityForResult( AuthUI.getInstance() .createSignInIntentBuilder() .setAvailableProviders(provider) .build(), RC_SIGN_IN) } }
countries-server/src/test/kotlin/example/com/ApplicationTest.kt
856673311
package example.com class ApplicationTest { }
countries-server/src/test/kotlin/example/com/fake/FakeCountryRepository.kt
3031977076
package example.com.fake import example.com.models.ApiResponse import example.com.models.Country import example.com.repository.CountryRepository class FakeCountryRepository : CountryRepository{ override var countries: Map<Int, List<Country>> = FakeCountryDataSource().createFakeCountriesDataSource() override var pageCount: Int = countries.size override suspend fun getCountries(page: Int): ApiResponse { val (prevPage, nextPage) = calculatePage(page) return ApiResponse( success = true, message = "ok", prevPage = prevPage, nextPage = nextPage, countries = countries[page-1]!! // Adjusting for zero-based array index (page - 1) ) } private fun calculatePage(page: Int): Pair<Int?, Int?> { val prevPage = if (page in 2..pageCount) page - 1 else null val nextPage = if (page in 1 until pageCount) page + 1 else null return Pair(prevPage, nextPage) } }
countries-server/src/test/kotlin/example/com/fake/FakeCountryDataSource.kt
4168573780
package example.com.fake import example.com.models.* class FakeCountryDataSource { fun createFakeCountriesDataSource(): Map<Int, List<Country>> { return listOf( createFakeCountry("Country1", "Flag1", "SVG1", "Alt1"), createFakeCountry("Country2", "Flag2", "SVG2", "Alt2"), createFakeCountry("Country3", "Flag3", "SVG3", "Alt3"), createFakeCountry("Country4", "Flag4", "SVG4", "Alt4"), createFakeCountry("Country5", "Flag5", "SVG5", "Alt5"), createFakeCountry("Country6", "Flag6", "SVG6", "Alt6"), ).chunked(2).withIndex().associate { (index, list) -> index to list } } private fun createFakeCountry( name: String, flagAlt: String, flagSvg: String, flagPng: String ): Country { return Country( flags = Flag( png = flagPng, svg = flagSvg, alt = flagAlt ), name = Name( common = name, official = "Official $name", nativeName = mapOf( "en" to NativeName( official = "Official English Name $name", common = "Common English Name $name" ) ) ), currencies = mapOf( "USD" to Currencies( name = "US Dollar", symbol = "$" ) ), capital = listOf("Capital $name"), region = "Region $name", subregion = "Subregion $name", languages = mapOf( "en" to "English", "fr" to "French" // Add more language mappings as needed ), population = 1000000, // Replace with the desired population value borders = listOf("Border1", "Border2") // Add more fields as needed ) } }
countries-server/src/test/kotlin/example/com/routes/GetAllCountriesTest.kt
526237988
package example.com.routes import example.com.base.BaseRoutingTest import example.com.fake.FakeCountryRepository import example.com.models.ApiResponse import example.com.repository.CountryRepository import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.routing.* import kotlinx.serialization.json.Json import org.junit.Before import org.koin.dsl.module import kotlin.test.Test import kotlin.test.assertEquals class GetAllCountriesTest : BaseRoutingTest() { private val countryRepository: CountryRepository = FakeCountryRepository() @Before fun setup() { testModule = module { single { countryRepository } } testRouting = { install(Routing) { getAllCountries() } } } @Test fun `access countries endpoint, with valid page query, assert correct response`() = withBaseTestApplication { val pageQuery = 3 client.get("/countries?page=$pageQuery").apply { val actual = Json.decodeFromString<ApiResponse>(this.bodyAsText()) val expected = countryRepository.getCountries(pageQuery) assertEquals(HttpStatusCode.OK, status) assertEquals(actual, expected) } } @Test fun `access countries endpoint, with non-numeric page query, assert error`() = withBaseTestApplication { client.get("/countries?page=").apply { val actual = Json.decodeFromString<ApiResponse>(this.bodyAsText()) val expected = ApiResponse( success = false, message = "Only Numbers Allowed." ) assertEquals(HttpStatusCode.BadRequest, status) assertEquals(expected, actual) } } @Test fun `access countries endpoint, with invalid page size, assert error`() = withBaseTestApplication { client.get("/countries?page=${countryRepository.pageCount + 1}").apply { val actual = Json.decodeFromString<ApiResponse>(this.bodyAsText()) val expected = ApiResponse( success = false, message = "Countries not Found." ) assertEquals(HttpStatusCode.NotFound, status) assertEquals(expected, actual) } } }
countries-server/src/test/kotlin/example/com/routes/RootTest.kt
2183370798
package example.com.routes import example.com.base.BaseRoutingTest import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.routing.* import io.ktor.server.testing.* import kotlinx.serialization.ExperimentalSerializationApi import org.junit.Before import kotlin.test.Test import kotlin.test.assertEquals class RootTest : BaseRoutingTest(){ @Before fun setup() { testRouting = { install(Routing) { root() } } } @Test fun `access root endpoint assert correct information`() = withBaseTestApplication{ client.get("/").apply { assertEquals(HttpStatusCode.OK, status) assertEquals("Welcome to Countries API!", bodyAsText()) } } @ExperimentalSerializationApi @Test fun `access non existing endpoint,assert not found`() = testApplication { val response = client.get("/unknown") assertEquals(expected = HttpStatusCode.NotFound, actual = response.status) assertEquals(expected = "Page not Found.", actual = response.bodyAsText()) } }
countries-server/src/test/kotlin/example/com/base/BaseRoutingTest.kt
3059062234
package example.com.base import example.com.plugins.configureSerialization import io.ktor.server.application.* import io.ktor.server.config.* import io.ktor.server.testing.* import org.koin.core.context.GlobalContext.stopKoin import org.koin.core.module.Module import org.koin.ktor.plugin.Koin abstract class BaseRoutingTest { protected var testModule: Module? = null protected var testRouting: Application.() -> Unit = { } init { stopKoin() } fun <R> withBaseTestApplication(test: suspend ApplicationTestBuilder.() -> R) = testApplication { environment { config = MapApplicationConfig("ktor.environment" to "test") } application { testModule?.let { install(Koin) { modules(it) } configureSerialization() } testRouting() } test() } }
countries-server/src/main/kotlin/example/com/repository/CountryRepository.kt
955522295
package example.com.repository import example.com.models.ApiResponse import example.com.models.Country interface CountryRepository { val pageCount: Int val countries: Map<Int, List<Country>> suspend fun getCountries(page: Int = 1): ApiResponse }
countries-server/src/main/kotlin/example/com/repository/CountryRepositoryImpl.kt
3562850444
package example.com.repository import example.com.models.ApiResponse import example.com.models.Country import kotlinx.serialization.json.Json import java.io.File const val PAGE_SIZE = 10 class CountryRepositoryImpl : CountryRepository { override var countries: Map<Int, List<Country>> override var pageCount: Int init { countries = fetchCountriesFromFileConvertToMap( "/Users/ahmetfurkansevim/Desktop/ktor/countries-server/src/main/resources/countries.json" ) pageCount = countries.size } override suspend fun getCountries(page: Int): ApiResponse { val (prevPage, nextPage) = calculatePage(page) return ApiResponse( success = true, message = "ok", prevPage = prevPage, nextPage = nextPage, countries = countries[page-1]!! // Adjusting for zero-based array index (page - 1) ) } private fun fetchCountriesFromFileConvertToMap(filePath: String): Map<Int, List<Country>> { try { val json = File(filePath).readText() val content = Json.decodeFromString<List<Country>>(json) return content.chunked(PAGE_SIZE).withIndex().associate { (index, list) -> index to list } } catch (e: Exception) { // Log the exception or handle it appropriately throw RuntimeException("Failed to fetch countries from file.", e) } } private fun calculatePage(page: Int): Pair<Int?, Int?> { val prevPage = if (page in 2..pageCount) page - 1 else null val nextPage = if (page in 1 until pageCount) page + 1 else null return Pair(prevPage, nextPage) } }
countries-server/src/main/kotlin/example/com/di/KoinModule.kt
382378058
package example.com.di import example.com.repository.CountryRepository import example.com.repository.CountryRepositoryImpl import org.koin.dsl.module val koinModule = module { single<CountryRepository> { CountryRepositoryImpl() } }
countries-server/src/main/kotlin/example/com/Application.kt
2232139715
package example.com import example.com.plugins.* import io.ktor.server.application.* fun main(args: Array<String>) = io.ktor.server.netty.EngineMain.main(args) fun Application.module() { configureKoin() configureDefaultHeader() configureSerialization() configureMonitoring() configureRouting() configureStatusPages() }
countries-server/src/main/kotlin/example/com/plugins/Routing.kt
111307526
package example.com.plugins import example.com.routes.getAllCountries import example.com.routes.root import io.ktor.server.application.* import io.ktor.server.routing.* fun Application.configureRouting() { routing { root() getAllCountries() } }
countries-server/src/main/kotlin/example/com/plugins/DefaultHeaders.kt
3580199622
package example.com.plugins import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.plugins.defaultheaders.* fun Application.configureDefaultHeader() { install(DefaultHeaders) { val oneYearInSeconds = java.time.Duration.ofDays(365).seconds header( name = HttpHeaders.CacheControl, value = "public, max-age=$oneYearInSeconds, immutable" ) } }
countries-server/src/main/kotlin/example/com/plugins/Serialization.kt
1708166843
package example.com.plugins import io.ktor.serialization.kotlinx.json.* import io.ktor.server.application.* import io.ktor.server.plugins.contentnegotiation.* fun Application.configureSerialization() { install(ContentNegotiation) { json() } }
countries-server/src/main/kotlin/example/com/plugins/Koin.kt
3989498826
package example.com.plugins import example.com.di.koinModule import io.ktor.server.application.* import org.koin.ktor.plugin.Koin import org.koin.logger.slf4jLogger fun Application.configureKoin() { install(Koin) { slf4jLogger() modules(koinModule) } }
countries-server/src/main/kotlin/example/com/plugins/StatusPage.kt
4189587939
package example.com.plugins import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.plugins.statuspages.* import io.ktor.server.response.* fun Application.configureStatusPages() { install(StatusPages) { status(HttpStatusCode.NotFound) { call, _ -> call.respond( message = "Page not Found.", status = HttpStatusCode.NotFound ) } } }
countries-server/src/main/kotlin/example/com/plugins/Monitoring.kt
3599556082
package example.com.plugins import io.ktor.server.application.* import io.ktor.server.plugins.callloging.* fun Application.configureMonitoring() { install(CallLogging) }
countries-server/src/main/kotlin/example/com/models/Country.kt
3494280079
package example.com.models import kotlinx.serialization.Serializable @Serializable data class Country( val flags: Flag, val name: Name, val currencies: Map<String, Currencies>, val capital: List<String>, val region: String, val subregion: String, val languages: Map<String, String>, val population: Int, val borders: List<String> ) @Serializable data class Flag( val png: String, val svg: String, val alt: String ) @Serializable data class NativeName( val official: String, val common: String ) @Serializable data class Name( val common: String, val official: String, val nativeName: Map<String, NativeName> ) @Serializable data class Currencies( val name: String, val symbol: String ) @Serializable data class Language( val code: String, val name: String )
countries-server/src/main/kotlin/example/com/models/ApiResponse.kt
2067181215
package example.com.models import kotlinx.serialization.Serializable @Serializable data class ApiResponse( val success: Boolean, val message: String? = null, val prevPage: Int? = null, val nextPage: Int? = null, val countries: List<Country> = emptyList() )
countries-server/src/main/kotlin/example/com/routes/Root.kt
1400361153
package example.com.routes import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.response.* import io.ktor.server.routing.* fun Route.root() { get("/") { call.respond( message = "Welcome to Countries API!", status = HttpStatusCode.OK ) } }
countries-server/src/main/kotlin/example/com/routes/GetAllCountries.kt
3768436109
package example.com.routes import example.com.models.ApiResponse import example.com.repository.CountryRepository import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.response.* import io.ktor.server.routing.* import org.koin.ktor.ext.inject fun Route.getAllCountries() { val countryRepository: CountryRepository by inject() get("/countries") { try { val page = call.request.queryParameters["page"]?.toInt() ?: 1 require(page in 1..countryRepository.pageCount) val apiResponse = countryRepository.getCountries(page) call.respond( message = apiResponse, status = HttpStatusCode.OK ) } catch (e: NumberFormatException) { call.respond( message = ApiResponse(success = false, message = "Only Numbers Allowed."), status = HttpStatusCode.BadRequest ) } catch (e: IllegalArgumentException) { call.respond( message = ApiResponse(success = false, message = "Countries not Found."), status = HttpStatusCode.NotFound ) } } }
LangDroid/core/src/commonMain/kotlin/com/langdroid/core/LangDroidModelActions.kt
3849046894
package com.langdroid.core import com.langdroid.core.models.GenerativeModel import com.langdroid.core.models.GenerativeModelApiActions import com.langdroid.core.models.request.config.GenerativeConfig import kotlinx.coroutines.flow.Flow public class LangDroidModelActions<M : GenerativeModel>( private val model: M, config: GenerativeConfig<M>? ) : GenerativeModelApiActions { init { model.config = config } public override suspend fun generateText(prompt: String): Result<String> = generateText(createSimplePrompt(prompt)) public override suspend fun generateText(prompts: List<ChatPrompt>): Result<String> = model.actions.generateText(prompts) public override suspend fun generateTextStream(prompt: String): Result<Flow<String?>> = generateTextStream(createSimplePrompt(prompt)) public override suspend fun generateTextStream(prompts: List<ChatPrompt>): Result<Flow<String?>> = model.actions.generateTextStream(prompts) public override suspend fun sanityCheck(): Boolean = model.actions.sanityCheck() public override suspend fun calculateTokens(prompts: List<ChatPrompt>): Result<Int> = model.actions.calculateTokens(prompts) private fun createSimplePrompt(prompt: String): List<ChatPrompt> = listOf(ChatRole.User to prompt) }
LangDroid/core/src/commonMain/kotlin/com/langdroid/core/utils.kt
1654205365
package com.langdroid.core internal inline fun <T> actionWithResult( noinline specificExceptionHandler: ((Exception) -> Result<T>)? = null, block: () -> T ): Result<T> { return try { Result.success(block()) } catch (e: Exception) { // Check if a specific exception handler is provided and use it specificExceptionHandler?.invoke(e) ?: Result.failure(e) } }
LangDroid/core/src/commonMain/kotlin/com/langdroid/core/ChatRole.kt
2034644325
package com.langdroid.core @JvmInline public value class ChatRole(public val role: String) { public companion object { public val System: ChatRole = ChatRole("system") public val User: ChatRole = ChatRole("user") public val Assistant: ChatRole = ChatRole("assistant") public val Function: ChatRole = ChatRole("function") public val Tool: ChatRole = ChatRole("tool") public val Model: ChatRole = ChatRole("model") } } public typealias ChatPrompt = Pair<ChatRole, String?>
LangDroid/core/src/commonMain/kotlin/com/langdroid/core/models/gemini/GeminiModelActions.kt
1651375600
package com.langdroid.core.models.gemini import com.langdroid.core.ChatPrompt import com.langdroid.core.models.GenerativeModelActions import kotlinx.coroutines.flow.Flow @Suppress("EXPECT_ACTUAL_CLASSIFIERS_ARE_IN_BETA_WARNING") public expect class GeminiModelActions(model: GeminiModel) : GenerativeModelActions { internal val model: GeminiModel override suspend fun generateText(prompts: List<ChatPrompt>): Result<String> override suspend fun generateTextStream(prompts: List<ChatPrompt>): Result<Flow<String?>> override suspend fun sanityCheck(): Boolean override suspend fun calculateTokens(prompts: List<ChatPrompt>): Result<Int> }
LangDroid/core/src/commonMain/kotlin/com/langdroid/core/models/gemini/GeminiModel.kt
1643683370
package com.langdroid.core.models.gemini import com.langdroid.core.models.GenerativeModel import com.langdroid.core.models.GenerativeModelActions public sealed class GeminiModel( override val id: String, override val tokenLimit: Int, override val outputTokenLimit: Int? = null ) : GenerativeModel() { private val modelActions: GenerativeModelActions by lazy { GeminiModelActions(this) } public override val actions: GenerativeModelActions = modelActions public data class Pro(override val apiKey: String?) : GeminiModel( id = "models/gemini-pro", tokenLimit = GEMINI_TOKEN_LIMIT, outputTokenLimit = GEMINI_TOKEN_OUTPUT_LIMIT ) public data class Ultra(override val apiKey: String?) : GeminiModel( id = "models/gemini-ultra", tokenLimit = GEMINI_TOKEN_LIMIT, outputTokenLimit = GEMINI_TOKEN_OUTPUT_LIMIT ) public data class Custom( override val id: String, override val apiKey: String?, override val tokenLimit: Int = GEMINI_TOKEN_LIMIT, override val outputTokenLimit: Int? = GEMINI_TOKEN_OUTPUT_LIMIT, ) : GeminiModel(id, tokenLimit, outputTokenLimit) } private const val GEMINI_TOKEN_OUTPUT_LIMIT = 2048 private const val GEMINI_TOKEN_LIMIT = 30720 + GEMINI_TOKEN_OUTPUT_LIMIT
LangDroid/core/src/commonMain/kotlin/com/langdroid/core/models/gemini/GeminiRequestConfigFields.kt
2624503780
package com.langdroid.core.models.gemini import com.langdroid.core.models.request.config.fields.RequestConfigFields public class GeminiRequestConfigFields( override val maxOutputTokens: String = "maxOutputTokens", override val temperature: String = "temperature", override val topP: String? = "topP", override val topK: String? = "topK", override val configObjectName: String? = "generationConfig" ) : RequestConfigFields
LangDroid/core/src/commonMain/kotlin/com/langdroid/core/models/GenerativeModelActions.kt
4246871982
package com.langdroid.core.models import com.langdroid.core.ChatPrompt import kotlinx.coroutines.flow.Flow public interface GenerativeModelActions { public suspend fun generateText(prompts: List<ChatPrompt>): Result<String> public suspend fun generateTextStream(prompts: List<ChatPrompt>): Result<Flow<String?>> public suspend fun sanityCheck(): Boolean public suspend fun calculateTokens(prompts: List<ChatPrompt>): Result<Int> }
LangDroid/core/src/commonMain/kotlin/com/langdroid/core/models/GenerativeModelApiActions.kt
531818099
package com.langdroid.core.models import kotlinx.coroutines.flow.Flow public interface GenerativeModelApiActions : GenerativeModelActions { public suspend fun generateText(prompt: String): Result<String> public suspend fun generateTextStream(prompt: String): Result<Flow<String?>> }
LangDroid/core/src/commonMain/kotlin/com/langdroid/core/models/request/config/fields/RequestConfigFields.kt
1759085569
package com.langdroid.core.models.request.config.fields public interface RequestConfigFields { public val maxOutputTokens: String? /** * Defines the wrapping object name for LLM API request configurations. * * - `configObjectName`: The name of the outer object (e.g., "generationConfig"). If provided, configuration settings like * `temperature`, `topP`, `topK`, and `maxOutputTokens` are nested within. If `null`, settings are at the top level, adapting to APIs with different structuring needs. */ public val configObjectName: String? public val temperature: String? public val topP: String? public val topK: String? }
LangDroid/core/src/commonMain/kotlin/com/langdroid/core/models/request/config/fields/DefaultRequestConfigFields.kt
3532348790
package com.langdroid.core.models.request.config.fields // Maybe make all fields equal to null public class DefaultRequestConfigFields( override val maxOutputTokens: String = "max_tokens", override val temperature: String = "temperature", override val topP: String? = "top_p", override val topK: String? = "top_k", override val configObjectName: String? = null ) : RequestConfigFields
LangDroid/core/src/commonMain/kotlin/com/langdroid/core/models/request/config/GenerativeConfig.kt
907016658
package com.langdroid.core.models.request.config import com.langdroid.core.models.GenerativeModel public interface GenerativeConfig<M : GenerativeModel> { public val temperature: Float? public val topP: Float? public val topK: Int? public val maxOutputTokens: Int? public companion object { public inline fun <reified M : GenerativeModel> create(onCreate: Builder<M>.() -> Unit = {}): GenerativeConfig<M> { // val requestConfigFields = when (M::class) { // OpenAiModel::class -> OpenAiRequestConfigFields() // GeminiModel::class -> GeminiRequestConfigFields() // else -> DefaultRequestConfigFields() // } val builder = Builder<M>() onCreate(builder) return builder.build() } } public class Builder<M : GenerativeModel> { public var temperature: Float? = null public var topP: Float? = null public var topK: Int? = null public var maxOutputTokens: Int? = null public fun temperature(temperature: Float): Builder<M> = apply { this.temperature = temperature } public fun topP(topP: Float): Builder<M> = apply { this.topP = topP } public fun topK(topK: Int): Builder<M> = apply { this.topK = topK } public fun maxOutputTokens(maxOutputTokens: Int): Builder<M> = apply { this.maxOutputTokens = maxOutputTokens } public fun build(): GenerativeConfig<M> = object : GenerativeConfig<M> { override val temperature: Float? = [email protected] override val topP: Float? = [email protected] override val topK: Int? = [email protected] override val maxOutputTokens: Int? = [email protected] } } }