Skip to content

Commit

Permalink
Code cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
JetpackDuba committed Dec 24, 2023
1 parent 13f00e2 commit 9e31145
Show file tree
Hide file tree
Showing 81 changed files with 289 additions and 148 deletions.
2 changes: 1 addition & 1 deletion .github/FUNDING.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# These are supported funding model platforms

github: [JetpackDuba] # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
github: [ JetpackDuba ] # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
Expand Down
24 changes: 16 additions & 8 deletions DEVELOPMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,16 @@

## Requirements

- **JDK 17 or higher**: You don't need this if you only use the JDK installed by IntelliJ IDEA. If you want to build using the CLI, check this [section](#alternative-setting-up-jdk-for-use-on-cli).
- **Rust:** Gitnuro is mainly written in Kotlin (JVM) but also uses Rust for some specific tasks. To set up your Rust environment,
please read [its documentation](https://www.rust-lang.org/). `cargo` and `rustc` must be available in the path in order to build Gitnuro properly.
- **JDK 17 or higher**: You don't need this if you only use the JDK installed by IntelliJ IDEA. If you want to build
using the CLI, check this [section](#alternative-setting-up-jdk-for-use-on-cli).
- **Rust:** Gitnuro is mainly written in Kotlin (JVM) but also uses Rust for some specific tasks. To set up your Rust
environment,
please read [its documentation](https://www.rust-lang.org/). `cargo` and `rustc` must be available in the path in
order to build Gitnuro properly.
- **Perl:** Perl is required to build openssl (which is required for LibSSH to work).
- **Packages for Linux ARM64/aarch64**: You need to install the `aarch64-linux-gnu-gcc` package to cross compile the
Rust components to ARM from x86_64. You will also need to use `rustup` to add a new target: `rustup target add aarch64-unknown-linux-gnu`
- **Packages for Linux ARM64/aarch64**: You need to install the `aarch64-linux-gnu-gcc` package to cross compile the
Rust components to ARM from x86_64. You will also need to use `rustup` to add a new
target: `rustup target add aarch64-unknown-linux-gnu`

## Setting up an IDE

Expand All @@ -16,9 +20,12 @@ If you don't have another preference, the recommendation is to download and inst
(possibly through the JetBrains Toolbox, if you have it already). The recommended plugins to improve the DX are:

- [Compose Multiplatform IDE Support](https://plugins.jetbrains.com/plugin/16541-compose-multiplatform-ide-support)
- [Rust Plugin](https://plugins.jetbrains.com/plugin/8182-rust) (deprecated due to [RustRover IDE](https://blog.jetbrains.com/rust/2023/09/13/introducing-rustrover-a-standalone-rust-ide-by-jetbrains/) but still works).
- [Rust Plugin](https://plugins.jetbrains.com/plugin/8182-rust) (deprecated due
to [RustRover IDE](https://blog.jetbrains.com/rust/2023/09/13/introducing-rustrover-a-standalone-rust-ide-by-jetbrains/)
but still works).

By default, the JDK used by "IntelliJ IDEA Community Edition (2023.1.3)" is "JetBrains Runtime version 21" which is not currently supported by the project.
By default, the JDK used by "IntelliJ IDEA Community Edition (2023.1.3)" is "JetBrains Runtime version 21" which is not
currently supported by the project.

## Alternative: Setting up JDK for use on CLI

Expand All @@ -32,7 +39,8 @@ sudo apt install openjdk-17-jre openjdk-17-jdk
export JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64
```

Once it works (e.g. `./gradlew build`). On Linux, you may want to add that latter line to your `/etc/environment` or user-specific files such as `.profile` or `.bashrc`.
Once it works (e.g. `./gradlew build`). On Linux, you may want to add that latter line to your `/etc/environment` or
user-specific files such as `.profile` or `.bashrc`.

## Running the app / unit tests

Expand Down
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@ can use it nor relying on web technologies.
Linux:

- Available as Flatpak [here](https://flathub.org/apps/details/com.jetpackduba.Gitnuro) or by
running `flatpak install com.jetpackduba.Gitnuro` if you have Flatpak & Flathub already setup.
- If Flathub is not set up, you can add the source with the following command `flatpak remote-add --if-not-exists flathub https://dl.flathub.org/repo/flathub.flatpakrepo`.
running `flatpak install com.jetpackduba.Gitnuro` if you have Flatpak & Flathub already setup.
- If Flathub is not set up, you can add the source with the following
command `flatpak remote-add --if-not-exists flathub https://dl.flathub.org/repo/flathub.flatpakrepo`.
- JAR file can be executed as a portable version (Requires JRE 17).

Windows:
Expand Down Expand Up @@ -139,6 +140,7 @@ it if it's a very requested feature but not for now.
> Authentication has failed. What's wrong?
Currently there are some limitations regarding this topic. Here are some known problematic setups:

- Multicast DNS remote URL (https://github.com/JetpackDuba/Gitnuro/issues/19) with this
workaround (https://github.com/JetpackDuba/Gitnuro/issues/19#issuecomment-1374431720).
- Self signed server certificate (https://github.com/JetpackDuba/Gitnuro/issues/48)
Expand Down
4 changes: 2 additions & 2 deletions rs/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ name = "gitnuro_rs"
uniffi = { version = "0.25.0" }
notify = "6.0.1"
thiserror = "1.0.43"
libssh-rs = { version = "0.2.2", features = [ "vendored", "vendored-openssl" ] }
libssh-rs = { version = "0.2.2", features = ["vendored", "vendored-openssl"] }

[build-dependencies]
uniffi = { version = "0.25.0", features = [ "build" ] }
uniffi = { version = "0.25.0", features = ["build"] }

[[bin]]
name = "uniffi-bindgen"
Expand Down
11 changes: 6 additions & 5 deletions rs/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
mod ssh;
mod watch_directory;

use watch_directory::{ * };
use ssh::{ * };
#[allow(unused_imports)] // Needed to map it to the enum in the UDL file
use libssh_rs::AuthStatus;

use ssh::{*};
use watch_directory::{*};

mod ssh;
mod watch_directory;

uniffi::include_scaffolding!("gitnuro");
8 changes: 5 additions & 3 deletions rs/src/ssh.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use libssh_rs::{AuthStatus, PollStatus, SshOption};
use std::io::Write;
use std::sync::{Arc, RwLock};
use std::io::{Write};

use libssh_rs::{AuthStatus, PollStatus, SshOption};

const ACCEPTED_SSH_TYPES: &str = "ssh-ed25519,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-rsa,rsa-sha2-512,rsa-sha2-256,ssh-dss";

Expand Down Expand Up @@ -63,6 +64,7 @@ pub struct Channel {
}

unsafe impl Send for Channel {}

unsafe impl Sync for Channel {}

impl Channel {
Expand Down Expand Up @@ -105,7 +107,7 @@ impl Channel {
}
}

pub fn read(&self, is_stderr: bool, len: u64) -> ReadResult {
pub fn read(&self, is_stderr: bool, len: u64) -> ReadResult {
let ulen = len as usize;

let channel = self.channel.write().unwrap();
Expand Down
1 change: 1 addition & 0 deletions rs/src/watch_directory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use std::fmt::Debug;
use std::path::{Path, PathBuf};
use std::sync::mpsc::{channel, RecvTimeoutError};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use notify::{Config, Error, ErrorKind, Event, RecommendedWatcher, RecursiveMode, Watcher};

const MIN_TIME_IN_MS_BETWEEN_REFRESHES: u128 = 500;
Expand Down
8 changes: 5 additions & 3 deletions src/main/kotlin/com/jetpackduba/gitnuro/App.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

package com.jetpackduba.gitnuro

import androidx.compose.foundation.*
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.text.LocalTextContextMenu
import androidx.compose.material.MaterialTheme
Expand All @@ -17,7 +18,9 @@ import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.*
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application
import androidx.compose.ui.window.rememberWindowState
import com.jetpackduba.gitnuro.di.DaggerAppComponent
import com.jetpackduba.gitnuro.extensions.preferenceValue
import com.jetpackduba.gitnuro.extensions.toWindowPlacement
Expand All @@ -44,7 +47,6 @@ import java.io.File
import java.net.Authenticator
import java.net.PasswordAuthentication
import java.nio.file.Paths
import java.util.*
import javax.inject.Inject


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ private const val KEY_LENGTH = 16
class CredentialsCacheRepository @Inject constructor() {
private val credentialsCached = mutableListOf<CredentialsType>()
private val credentialsLock = Mutex(false)

// having a random key to encrypt the password may help in case of a memory dump attack
private val encryptionKey = getRandomKey()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ class GSessionManager @Inject constructor(

class MySessionFactory @Inject constructor(
private val sessionProvider: Provider<SshRemoteSession>
) : SshSessionFactory(), CredentialsCache {
) : SshSessionFactory(), CredentialsCache {
override fun getSession(
uri: URIish,
credentialsProvider: CredentialsProvider?,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,7 @@ import org.eclipse.jgit.api.Git
import org.eclipse.jgit.internal.JGitText
import org.eclipse.jgit.lib.Config
import org.eclipse.jgit.transport.CredentialItem
import org.eclipse.jgit.transport.CredentialItem.Password
import org.eclipse.jgit.transport.CredentialItem.Username
import org.eclipse.jgit.transport.CredentialItem.YesNoType
import org.eclipse.jgit.transport.CredentialItem.*
import org.eclipse.jgit.transport.CredentialsProvider
import org.eclipse.jgit.transport.URIish
import java.io.*
Expand Down
2 changes: 0 additions & 2 deletions src/main/kotlin/com/jetpackduba/gitnuro/di/TabComponent.kt
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package com.jetpackduba.gitnuro.di

import com.jetpackduba.gitnuro.di.modules.NetworkModule
import com.jetpackduba.gitnuro.di.modules.ShellModule
import com.jetpackduba.gitnuro.di.modules.TabModule
import com.jetpackduba.gitnuro.ui.components.TabInformation
import dagger.Component
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
package com.jetpackduba.gitnuro.exceptions

class FetchException(msg: String): GitnuroException(msg)
class FetchException(msg: String) : GitnuroException(msg)
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
package com.jetpackduba.gitnuro.extensions

import androidx.compose.foundation.*
import androidx.compose.foundation.gestures.*
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.gestures.waitForUpOrCancellation
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
Expand Down Expand Up @@ -95,17 +98,17 @@ fun Modifier.onDoubleClick(
@Composable
fun Modifier.onMiddleMouseButtonClick(key: Any = Unit, key2: Any = Unit, onClick: () -> Unit) =
this.pointerInput(key, key2) {
while (true) {
val lastMouseEvent = awaitPointerEventScope { awaitFirstDownEvent() }
val mouseEvent = lastMouseEvent.awtEventOrNull
while (true) {
val lastMouseEvent = awaitPointerEventScope { awaitFirstDownEvent() }
val mouseEvent = lastMouseEvent.awtEventOrNull

if (mouseEvent != null) {
if (lastMouseEvent.button.isTertiary) {
onClick()
}
if (mouseEvent != null) {
if (lastMouseEvent.button.isTertiary) {
onClick()
}
}
}
}

@Composable
private fun Modifier.hoverBackground(): Modifier {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package com.jetpackduba.gitnuro.git

import com.jetpackduba.gitnuro.managers.TempFilesManager
import com.jetpackduba.gitnuro.extensions.fileName
import com.jetpackduba.gitnuro.managers.TempFilesManager
import org.eclipse.jgit.diff.ContentSource
import org.eclipse.jgit.diff.DiffEntry
import org.eclipse.jgit.diff.RawText
Expand Down
1 change: 0 additions & 1 deletion src/main/kotlin/com/jetpackduba/gitnuro/git/TaskEvent.kt
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package com.jetpackduba.gitnuro.git

import com.jetpackduba.gitnuro.ui.SelectedItem
import org.eclipse.jgit.revwalk.RevCommit

sealed interface TaskEvent {
data class ScrollToGraphItem(val selectedItem: SelectedItem) : TaskEvent
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package com.jetpackduba.gitnuro.git.branches

import com.jetpackduba.gitnuro.extensions.simpleName
import org.eclipse.jgit.api.Git
import org.eclipse.jgit.lib.Config
import org.eclipse.jgit.lib.Ref
import org.eclipse.jgit.lib.Repository
import org.eclipse.jgit.lib.StoredConfig
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ object LocalConfigConstants {

const val DEFAULT_SIGN_OFF_FORMAT_USER = "%user"
const val DEFAULT_SIGN_OFF_FORMAT_EMAIL = "%email"
const val DEFAULT_SIGN_OFF_FORMAT = "Signed-off-by: $DEFAULT_SIGN_OFF_FORMAT_USER <$DEFAULT_SIGN_OFF_FORMAT_EMAIL>"
const val DEFAULT_SIGN_OFF_FORMAT =
"Signed-off-by: $DEFAULT_SIGN_OFF_FORMAT_USER <$DEFAULT_SIGN_OFF_FORMAT_EMAIL>"
const val DEFAULT_SIGN_OFF_ENABLED = false
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import org.eclipse.jgit.submodule.SubmoduleStatus
sealed class DiffResult(
val diffEntry: DiffEntry,
) {
sealed class TextDiff(diffEntry: DiffEntry): DiffResult(diffEntry)
sealed class TextDiff(diffEntry: DiffEntry) : DiffResult(diffEntry)

class Text(
diffEntry: DiffEntry,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ class GetLogUseCase @Inject constructor() {
private fun cachedGraphWalk(repository: Repository): GraphWalk {
val graphWalkCached = this.graphWalkCached

return if(graphWalkCached != null) {
return if (graphWalkCached != null) {
graphWalkCached
} else {
val newGraphWalk = GraphWalk(repository)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ class GetRebaseInteractiveStateUseCase @Inject constructor(

RebaseInteractiveState.ProcessingCommits(commitId)
}

else -> RebaseInteractiveState.AwaitingInteraction
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package com.jetpackduba.gitnuro.git.remote_operations

import com.jetpackduba.gitnuro.exceptions.FetchException
import com.jetpackduba.gitnuro.exceptions.GitnuroException
import com.jetpackduba.gitnuro.logging.printError
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
Expand Down Expand Up @@ -48,13 +47,13 @@ class FetchAllBranchesUseCase @Inject constructor(
} catch (ex: Exception) {
printError(TAG, "Fetch failed for remote ${remote.name} with error ${ex.message}", ex)

if(ex.message != "Cancelled authentication" && ex !is CancellationException) {
errors.add(remote to ex)
if (ex.message != "Cancelled authentication" && ex !is CancellationException) {
errors.add(remote to ex)
}
}
}

if(errors.isNotEmpty()) {
if (errors.isNotEmpty()) {
val errorText = errors.joinToString("\n") {
"Fetch failed for remote ${it.first.name}: ${it.second.message}"
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class HandleTransportUseCase @Inject constructor(
suspend operator fun invoke(git: Git?, block: suspend CredentialsHandler.() -> Unit) {
var cache: CredentialsCache? = null

val credentialsHandler = object: CredentialsHandler {
val credentialsHandler = object : CredentialsHandler {
override fun handleTransport(transport: Transport?) {
cache = when (transport) {
is SshTransport -> {
Expand All @@ -41,6 +41,7 @@ class HandleTransportUseCase @Inject constructor(
cache?.cacheCredentialsIfNeeded()
}
}

interface CredentialsCache {
suspend fun cacheCredentialsIfNeeded()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import com.jetpackduba.gitnuro.preferences.AppSettings
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.eclipse.jgit.api.Git
import org.eclipse.jgit.api.PullResult
import org.eclipse.jgit.api.RebaseResult
import org.eclipse.jgit.transport.CredentialsProvider
import javax.inject.Inject
Expand All @@ -23,7 +22,7 @@ class PullBranchUseCase @Inject constructor(
handleTransportUseCase(git) {
val pullResult = git
.pull()
.setTransportConfigCallback {this.handleTransport(it) }
.setTransportConfigCallback { this.handleTransport(it) }
.setRebase(pullWithRebase)
.setCredentialsProvider(CredentialsProvider.getDefault())
.call()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ class OpenSubmoduleRepositoryUseCase @Inject constructor(

val repository = openRepositoryUseCase(parent)

val submoduleRelativePath = directory.absolutePath.removePrefix("${repository.directory.parent}$systemSeparator")
val submoduleRelativePath =
directory.absolutePath.removePrefix("${repository.directory.parent}$systemSeparator")

return@withContext SubmoduleWalk.getSubmoduleRepository(repository, submoduleRelativePath)
?: throw InvalidDirectoryException("Invalid submodule directory. Check if the submodule has been initialized before trying to open it.")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package com.jetpackduba.gitnuro.git.submodules
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.eclipse.jgit.api.Git
import org.eclipse.jgit.lib.Config
import org.eclipse.jgit.storage.file.FileBasedConfig
import java.io.File
import javax.inject.Inject
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ class DoCommitUseCase @Inject constructor(
): RevCommit = withContext(Dispatchers.IO) {
val signOffConfig = loadSignOffConfigUseCase(git.repository)

val finalMessage = if(signOffConfig.isEnabled) {
val finalMessage = if (signOffConfig.isEnabled) {
val authorToSign = author ?: loadAuthorUseCase(git).toPersonIdent()

val signature = signOffConfig.format
Expand Down
Loading

0 comments on commit 9e31145

Please sign in to comment.